Perfected FlowScript
Price Z-Score
Price Z-Score [Perfected] is indexed as 139_price_z_score.flowscript. The exact FlowScript is viewable here; chart observe and trading automation use the current mmflow chart/recipe signal proxy until FlowScript v2 transpilation is available.
This exact FlowScript uses the v2 source dialect. It is viewable and connected to the chart/automation proxy, but direct editor execution needs the FlowScript v2 transpiler.
Dialect
flowscript-v2
Compatibility
flowscript-v2-needs-transpile
Position
offchart
Axis
true
Size
13.4 KB
Lines
340
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
+1σ Cross
line 280:9
Trigger
(showShapes) && (crossUp1)
Value
zSmooth
Deps
crossUp1:var, showShapes:input
-1σ Cross
line 290:9
Trigger
(showShapes) && (crossDn1)
Value
zSmooth
Deps
crossDn1:var, showShapes:input
+2σ Cross
line 300:9
Trigger
(showShapes) && (crossUp2)
Value
zSmooth
Deps
crossUp2:var, showShapes:input
-2σ Cross
line 310:9
Trigger
(showShapes) && (crossDn2)
Value
zSmooth
Deps
crossDn2:var, showShapes:input
+3σ Cross
line 320:9
Trigger
(showShapes) && (crossUp3)
Value
zSmooth
Deps
crossUp3:var, showShapes:input
-3σ Cross
line 330:9
Trigger
(showShapes) && (crossDn3)
Value
zSmooth
Deps
crossDn3:var, showShapes:input
139_price_z_score.flowscript
source path: kscripts/perfected/139_price_z_score.flowscript · sha256:e118f5b907b8fe085be9465b5d502eb57617b943b8f5259c43c410dde8f14ff4
//@version=2
// ============================================================================
// Price Z-Score — Production-Quality Mean Reversion Indicator [Perfected]
// Author: BackQuant (@BackQuant) | Perfected by: kScript_Perfection_Engineer
// Tags: CORE, ADVANCED, #price, #zscore
//
// Standardizes price relative to its recent norm using a rolling z-score.
// Computes z = (close − mean) / standard deviation on a configurable window.
// Includes ±1/2/3σ bands with fill, regime detection, and shape markers for
// extreme mean-reversion events.
//
// FORMULA FOUNDATION:
// 1. Z-Score: z = (Close − μ) / σ [Zhao & Palomar 2018]
// 2. Bollinger %B equivalence: z-score = 2(%B − 50) [Bollinger 2001]
// 3. Mean Reversion: Returns negatively autocorrelated at medium horizons
// [Poterba & Summers 1988]
// 4. Gaussian Reference: ~68.2% within ±1σ, ~95.4% within ±2σ, ~99.7% within ±3σ
//
// RESEARCH BASIS:
// • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint".
// Canonical z-score trading framework: entry at d×σ, exit on mean reversion.
// • Bollinger (2001), "Bollinger on Bollinger Bands". %B = (Close − Lower) /
// (Upper − Lower) × 100; z-score is %B rescaled around 0 with ±2σ bands.
// • Poterba & Summers (1988), "Mean Reversion in Stock Prices". Medium-term
// negative autocorrelation supports z-score as mean-reversion signal.
// • QuantOracle (2026), "Z-Score vs Bollinger Bands vs RSI". Professional
// multi-indicator approach: combine z-score extremes with RSI/Bollinger
// confirmation for higher-probability mean-reversion entries.
// ============================================================================
define(
title="Price Z-Score [Perfected]",
position="offchart",
axis=true
)
// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------
// --- Statistics ---
var win = input(name="win", type="number", defaultValue=20, label="Rolling Window", constraints={min: 5, max: 200, step: 1}, group="Statistics")
var smoothLen = input(name="smoothLen", type="number", defaultValue=1, label="Smoothing Length (1 = off)", constraints={min: 1, max: 50, step: 1}, group="Statistics")
var useEma = input(name="useEma", type="boolean", defaultValue=false, label="Use EMA for Mean", group="Statistics")
var useEmaSmooth = input(name="useEmaSmooth", type="boolean", defaultValue=false, label="Use EMA for Smoothing", group="Statistics")
// --- Bands ---
var band1Mult = input(name="band1Mult", type="number", defaultValue=1.0, label="Band 1 Multiplier (σ)", constraints={min: 0.5, max: 5.0, step: 0.5}, group="Bands")
var band2Mult = input(name="band2Mult", type="number", defaultValue=2.0, label="Band 2 Multiplier (σ)", constraints={min: 0.5, max: 5.0, step: 0.5}, group="Bands")
var band3Mult = input(name="band3Mult", type="number", defaultValue=3.0, label="Band 3 Multiplier (σ)", constraints={min: 0.5, max: 5.0, step: 0.5}, group="Bands")
var showBand1 = input(name="showBand1", type="boolean", defaultValue=true, label="Show ±1σ Band", group="Bands")
var showBand2 = input(name="showBand2", type="boolean", defaultValue=true, label="Show ±2σ Band", group="Bands")
var showBand3 = input(name="showBand3", type="boolean", defaultValue=true, label="Show ±3σ Band", group="Bands")
var showBandFill = input(name="showBandFill", type="boolean", defaultValue=true, label="Show Band Fills", group="Bands")
// --- Display ---
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Band-Cross Shapes", group="Display")
var showGuides = input(name="showGuides", type="boolean", defaultValue=true, label="Show Zero Line", group="Display")
// --- Colors ---
var lineColor = input(name="lineColor", type="color", defaultValue="#26a69a", label="Z-Score Line Color", group="Colors")
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="Bullish Regime Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ef5350", label="Bearish Regime Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var extremeBullColor = input(name="extremeBullColor", type="color", defaultValue="#00e676", label="Extreme Bull Color", group="Colors")
var extremeBearColor = input(name="extremeBearColor", type="color", defaultValue="#ff1744", label="Extreme Bear Color", group="Colors")
var bandColor = input(name="bandColor", type="color", defaultValue="#9e9e9e", label="Band Line Color", group="Colors")
// ------------------------------------------------------------------------------
// Data Sources
// ------------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries c = bars.close
timeseries h = bars.high
timeseries l = bars.low
// NaN guard — prevent computation on incomplete data (Cont et al. 2014 best practice)
if (isnan(c[0]) || isnan(bars.volume[0]) || isnan(h[0]) || isnan(l[0])) {
return
}
// ------------------------------------------------------------------------------
// Z-Score Computation (Zhao & Palomar 2018)
// ------------------------------------------------------------------------------
// Mean: SMA or EMA of close; StdDev: rolling standard deviation.
// The choice between SMA and EMA affects responsiveness: EMA adapts faster
// to recent changes while SMA offers more stability per Madhavan (2002).
timeseries cMean = useEma ? ema(c, win) : sma(c, win)
timeseries cStd = stdev(c, win)
timeseries zRaw = (c - cMean) / max(cStd, 1e-9)
// Smoothing: optional EMA or SMA of the raw z-score for a steadier read.
// When smoothLen = 1, no smoothing is applied (raw z-score).
timeseries zSmooth = smoothLen <= 1 ? zRaw : (useEmaSmooth ? ema(zRaw, smoothLen) : sma(zRaw, smoothLen))
// ------------------------------------------------------------------------------
// Standard Deviation Bands (Gaussian reference levels)
// ------------------------------------------------------------------------------
// ~68.2% of observations within ±1σ, ~95.4% within ±2σ, ~99.7% within ±3σ.
// These bands serve as objective thresholds for mean-reversion triggers.
var band1Hi = band1Mult
var band1Lo = -band1Mult
var band2Hi = band2Mult
var band2Lo = -band2Mult
var band3Hi = band3Mult
var band3Lo = -band3Mult
// ------------------------------------------------------------------------------
// Regime Detection (5-tier classification based on σ-band proximity)
// ------------------------------------------------------------------------------
// 0 = extreme bull (≥ +2σ), 1 = bull (+1σ to +2σ), 2 = neutral (−1σ to +1σ),
// 3 = bear (−2σ to −1σ), 4 = extreme bear (≤ −2σ)
//
// Per Bollinger (2001), price outside ±2σ is an extreme that tends to revert.
// Per Poterba & Summers (1988), medium-term negative autocorrelation supports
// this mean-reversion interpretation.
var regime = 2
if (zSmooth >= band2Mult) {
regime = 0
} else if (zSmooth >= band1Mult) {
regime = 1
} else if (zSmooth <= -band2Mult) {
regime = 4
} else if (zSmooth <= -band1Mult) {
regime = 3
} else {
regime = 2
}
// ------------------------------------------------------------------------------
// Static State Tracking (session-level persistence)
// ------------------------------------------------------------------------------
// Tracks session extremes, extreme-event counts, and regime transitions for
// diagnostic and alerting purposes.
static lastBarIndex = 0
static sessionHighZ = -999999.0
static sessionLowZ = 999999.0
static extremeBullCount = 0
static extremeBearCount = 0
static band2TouchCount = 0
static lastRegime = 2
static regimeChangeCount = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
if (zSmooth > sessionHighZ) {
sessionHighZ = zSmooth
}
if (zSmooth < sessionLowZ) {
sessionLowZ = zSmooth
}
if (zSmooth >= band2Mult) {
extremeBullCount = extremeBullCount + 1
}
if (zSmooth <= -band2Mult) {
extremeBearCount = extremeBearCount + 1
}
if (math.abs(zSmooth) >= band2Mult) {
band2TouchCount = band2TouchCount + 1
}
if (lastRegime != regime) {
lastRegime = regime
regimeChangeCount = regimeChangeCount + 1
}
}
// ------------------------------------------------------------------------------
// Plots — Multiple Visualization Types (Line, Fill, Shape, HLine)
// ------------------------------------------------------------------------------
// Zero line (center of the z-score distribution)
if (showGuides) {
hline(value=0, color="#ffffff30", width=1)
}
// ±3σ band lines (outermost — structural extremes per Gaussian distribution)
if (showBand3) {
plotLine(
value=band3Hi,
width=1,
colors=[bandColor],
label=["+3σ"],
desc=["+3σ band line: ~99.7% of observations lie within this boundary"]
)
plotLine(
value=band3Lo,
width=1,
colors=[bandColor],
label=["-3σ"],
desc=["−3σ band line: ~99.7% of observations lie within this boundary"]
)
}
// ±2σ band fill (moderate extremes — ~95.4% of observations)
if (showBand2) {
if (showBandFill) {
plotLine(
value=([band2Lo, band2Hi]),
width=1,
colors=[opacity(bandColor, 15)],
fill=true,
label=["±2σ Fill"],
desc=["±2σ band fill: ~95.4% of price observations within this range"]
)
}
plotLine(
value=band2Hi,
width=1,
colors=[bandColor],
label=["+2σ"],
desc=["+2σ band line: threshold for extreme bullish deviation"]
)
plotLine(
value=band2Lo,
width=1,
colors=[bandColor],
label=["-2σ"],
desc=["−2σ band line: threshold for extreme bearish deviation"]
)
}
// ±1σ band fill (typical range — ~68.2% of observations)
if (showBand1) {
if (showBandFill) {
plotLine(
value=([band1Lo, band1Hi]),
width=1,
colors=[opacity(bandColor, 10)],
fill=true,
label=["±1σ Fill"],
desc=["±1σ band fill: ~68.2% of price observations within this range"]
)
}
plotLine(
value=band1Hi,
width=1,
colors=[bandColor],
label=["+1σ"],
desc=["+1σ band line: threshold for moderate bullish deviation"]
)
plotLine(
value=band1Lo,
width=1,
colors=[bandColor],
label=["-1σ"],
desc=["−1σ band line: threshold for moderate bearish deviation"]
)
}
// Z-score line with 5-tier regime fill coloring
plotLine(
value=zSmooth,
width=2,
colors=[extremeBullColor, bullColor, neutralColor, bearColor, extremeBearColor],
colorIndex=regime,
label=["Price Z-Score"],
desc=["Price z-score with 5-tier regime coloring and fill to zero"],
fill=true
)
// Shape markers for band crosses (mean-reversion event triggers)
if (showShapes) {
var crossUp1 = zSmooth >= band1Mult && !isnan(zSmooth[1]) && zSmooth[1] < band1Mult
var crossDn1 = zSmooth <= -band1Mult && !isnan(zSmooth[1]) && zSmooth[1] > -band1Mult
var crossUp2 = zSmooth >= band2Mult && !isnan(zSmooth[1]) && zSmooth[1] < band2Mult
var crossDn2 = zSmooth <= -band2Mult && !isnan(zSmooth[1]) && zSmooth[1] > -band2Mult
var crossUp3 = zSmooth >= band3Mult && !isnan(zSmooth[1]) && zSmooth[1] < band3Mult
var crossDn3 = zSmooth <= -band3Mult && !isnan(zSmooth[1]) && zSmooth[1] > -band3Mult
if (crossUp1) {
plotShape(
value=zSmooth,
shape="triangleup",
color=bullColor,
width=2,
label=["+1σ Cross"],
desc=["Price z-score crossed above +1σ — moderate bullish deviation"]
)
}
if (crossDn1) {
plotShape(
value=zSmooth,
shape="triangledown",
color=bearColor,
width=2,
label=["-1σ Cross"],
desc=["Price z-score crossed below −1σ — moderate bearish deviation"]
)
}
if (crossUp2) {
plotShape(
value=zSmooth,
shape="triangleup",
color=extremeBullColor,
width=3,
label=["+2σ Cross"],
desc=["Price z-score crossed above +2σ — extreme bullish deviation (mean-reversion candidate)"]
)
}
if (crossDn2) {
plotShape(
value=zSmooth,
shape="triangledown",
color=extremeBearColor,
width=3,
label=["-2σ Cross"],
desc=["Price z-score crossed below −2σ — extreme bearish deviation (mean-reversion candidate)"]
)
}
if (crossUp3) {
plotShape(
value=zSmooth,
shape="diamond",
color=extremeBullColor,
width=4,
label=["+3σ Cross"],
desc=["Price z-score crossed above +3σ — structural extreme (~0.3% probability)"]
)
}
if (crossDn3) {
plotShape(
value=zSmooth,
shape="diamond",
color=extremeBearColor,
width=4,
label=["-3σ Cross"],
desc=["Price z-score crossed below −3σ — structural extreme (~0.3% probability)"]
)
}
}