MM Flow
FlowScripts

Perfected FlowScript

Volatility Z-Score

Volatility Z-Score — Perfected Edition is indexed as 153_volatility_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.2 KB

Lines

427

Native Signal Candidates

6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.

6/6 guarded

Extreme High

line 334:9

Trigger

(showShapes) && (extremeUp)

Value

zSmooth

Deps

extremeUp:var, showShapes:input

Extreme Low

line 344:9

Trigger

(showShapes) && (extremeDown)

Value

zSmooth

Deps

extremeDown:var, showShapes:input

σ2 Up

line 354:9

Trigger

(showShapes) && (sigma2Up)

Value

zSmooth

Deps

showShapes:input, sigma2Up:var

σ2 Down

line 364:9

Trigger

(showShapes) && (sigma2Down)

Value

zSmooth

Deps

showShapes:input, sigma2Down:var

Zero Cross Up

line 374:9

Trigger

(showShapes) && (crossUp)

Value

0

Deps

crossUp:var, showShapes:input

Zero Cross Down

line 384:9

Trigger

(showShapes) && (crossDown)

Value

0

Deps

crossDown:var, showShapes:input

153_volatility_z_score.flowscript

source path: kscripts/perfected/153_volatility_z_score.flowscript · sha256:2ee717649eaa2a6713f8911e2072d74e3dd6e234d2608e2a5dd6db56fd05d8a1

hash verified
//@version=2
// ============================================================================
// Volatility Z-Score — Perfected Edition
// Author: BackQuant (@BackQuant) | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, ADVANCED, #volatility, #zscore, #regime, #momentum
//
// Production-quality statistical volatility oscillator that standardizes
// realized volatility into a z-score regime indicator. Implements rolling
// sigma-band visualization, regime detection, color-coded momentum, and
// comprehensive fill/shape/histogram visualization.
//
// Research papers underpinning this design:
//  1. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint":
//     z-score event triggers for mean reversion; normalized spread z̄ = (z−μ)/σ
//     with entry thresholds at ±1σ and ±2σ. IEEE TSP.
//  2. QuantOracle (2026), "Z-Score vs Bollinger Bands vs RSI": |z| > 2 signals
//     statistical rarity; combine with Hurst < 0.5 for regime filter.
//  3. Easley, López de Prado & O'Hara (2012), "Flow Toxicity and Liquidity in
//     a High-Frequency World": volume-synchronized volatility measurement via
//     Bulk Volume Classification (BVC) in volume-time buckets.
//  4. Poterba & Summers (1988), "Mean Reversion in Stock Prices": negative
//     autocorrelation at medium horizons; volatility clustering supports
//     rolling-window z-score normalization.
//  5. Mandelbrot (1963), "The Variation of Certain Speculative Prices":
//     fractal geometry in finance; volatility exhibits self-similarity and
//     heavy-tailed distributions, motivating multi-sigma band analysis.
// ============================================================================

define(
    title="Volatility Z-Score — Perfected Edition",
    position="offchart",
    axis=true
)

// ---------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// ---------------------------------------------------------------------------

// --- Volatility Settings ---
var rvPeriod = input(
    name="rvPeriod",
    type="number",
    defaultValue=14,
    label="RV Lookback (bars)",
    constraints={min: 5, max: 50, step: 1},
    group="Volatility Settings"
)
var zWindow = input(
    name="zWindow",
    type="number",
    defaultValue=60,
    label="Z-Score Window",
    constraints={min: 20, max: 200, step: 5},
    group="Volatility Settings"
)
var annualize = input(
    name="annualize",
    type="boolean",
    defaultValue=true,
    label="Annualize RV",
    group="Volatility Settings"
)
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=3,
    label="Z Smoothing Length",
    constraints={min: 1, max: 20, step: 1},
    group="Volatility Settings"
)

// --- Sigma Bands ---
var showBands = input(
    name="showBands",
    type="boolean",
    defaultValue=true,
    label="Show ±1/2/3σ Bands",
    group="Sigma Bands"
)
var band1Sigma = input(
    name="band1Sigma",
    type="number",
    defaultValue=1.0,
    label="1σ Band",
    constraints={min: 0.5, max: 2.0, step: 0.5},
    group="Sigma Bands"
)
var band2Sigma = input(
    name="band2Sigma",
    type="number",
    defaultValue=2.0,
    label="2σ Band",
    constraints={min: 1.0, max: 3.0, step: 0.5},
    group="Sigma Bands"
)
var band3Sigma = input(
    name="band3Sigma",
    type="number",
    defaultValue=3.0,
    label="3σ Band",
    constraints={min: 2.0, max: 4.0, step: 0.5},
    group="Sigma Bands"
)

// --- Display ---
var plotStyle = input(
    name="plotStyle",
    type="select",
    defaultValue="Histogram",
    label="Plot Style",
    options=["Histogram", "Line", "Both"],
    group="Display"
)
var showMomentum = input(
    name="showMomentum",
    type="boolean",
    defaultValue=true,
    label="Show Momentum Histogram",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Extreme Shapes",
    group="Display"
)
var showRegimeTable = input(
    name="showRegimeTable",
    type="boolean",
    defaultValue=true,
    label="Show Regime Table",
    group="Display"
)

// --- Colors ---
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Expansion Color",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Compression Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#78909c",
    label="Neutral Color",
    group="Colors"
)
var extremeColor = input(
    name="extremeColor",
    type="color",
    defaultValue="#ffeb3b",
    label="Extreme Color",
    group="Colors"
)
var lineColor = input(
    name="lineColor",
    type="color",
    defaultValue="#42a5f5",
    label="Line Color",
    group="Colors"
)

// ---------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = bars.close

if (isnan(close[0])) {
    return
}

// ---------------------------------------------------------------------------
// 3. REALIZED VOLATILITY — log-return standard deviation
// ---------------------------------------------------------------------------
// Per Easley et al. (2012), volume-synchronized volatility buckets improve
// robustness; here we use time-based log returns as the base input.
timeseries logRet = math.log(close / math.max(close[1], 0.0001))
timeseries rvRaw = stdev(logRet, rvPeriod)

// Annualize: multiply by sqrt(365) × 100 for percentage scale
timeseries rvAnnual = annualize ? rvRaw * math.sqrt(365) * 100.0 : rvRaw * 100.0

// ---------------------------------------------------------------------------
// 4. Z-SCORE NORMALIZATION — rolling window
// ---------------------------------------------------------------------------
// z = (RV − μ) / σ; guards against zero division.
timeseries mu = sma(rvAnnual, zWindow)
timeseries sigma = stdev(rvAnnual, zWindow)
timeseries z = (rvAnnual - mu) / math.max(sigma, 0.0001)

// Smoothed z for cleaner reading
timeseries zSmooth = ema(z, smoothLen)

// Momentum = rate of change in z
timeseries zMom = zSmooth - zSmooth[1]

// ---------------------------------------------------------------------------
// 5. REGIME DETECTION
// ---------------------------------------------------------------------------
// Regime classification based on z position relative to sigma bands:
//   Vol-Expansion (Hot):    z > +1σ  → unusually high volatility
//   Vol-Compression (Cold): z < −1σ  → unusually low volatility
//   Normal:                 |z| ≤ 1σ → typical regime

var regimeHot = zSmooth > band1Sigma
var regimeCold = zSmooth < -band1Sigma
var regimeNormal = !regimeHot && !regimeCold

var regimeColor = regimeHot ? bullColor : (regimeCold ? bearColor : neutralColor)

// ---------------------------------------------------------------------------
// 6. STATIC STATE TRACKING — regime duration
// ---------------------------------------------------------------------------
static hotBars = 0
static coldBars = 0
static normalBars = 0
static lastRegime = 0

if (regimeHot) {
    hotBars = hotBars + 1
    coldBars = 0
    normalBars = 0
    lastRegime = 1
} else if (regimeCold) {
    coldBars = coldBars + 1
    hotBars = 0
    normalBars = 0
    lastRegime = -1
} else {
    normalBars = normalBars + 1
    hotBars = 0
    coldBars = 0
    lastRegime = 0
}

// ---------------------------------------------------------------------------
// 7. ALERT CONDITIONS
// ---------------------------------------------------------------------------
var extremeUp = zSmooth > band3Sigma && zSmooth[1] <= band3Sigma
var extremeDown = zSmooth < -band3Sigma && zSmooth[1] >= -band3Sigma
var sigma2Up = zSmooth > band2Sigma && zSmooth[1] <= band2Sigma
var sigma2Down = zSmooth < -band2Sigma && zSmooth[1] >= -band2Sigma

// Zero-line cross (regime shift between expansion and compression)
var crossUp = zSmooth > 0 && zSmooth[1] <= 0
var crossDown = zSmooth < 0 && zSmooth[1] >= 0

// ---------------------------------------------------------------------------
// 8. PLOTTING
// ---------------------------------------------------------------------------

// --- Zero line ---
hline(value=0, color="#ffffff30", width=1)

// --- Sigma Bands (±1/2/3σ) with fill ---
if (showBands) {
    hline(value=band1Sigma, color=transparency(bullColor, 60), width=1)
    hline(value=-band1Sigma, color=transparency(bearColor, 60), width=1)
    hline(value=band2Sigma, color=transparency(bullColor, 40), width=1)
    hline(value=-band2Sigma, color=transparency(bearColor, 40), width=1)
    hline(value=band3Sigma, color=transparency(extremeColor, 30), width=1)
    hline(value=-band3Sigma, color=transparency(extremeColor, 30), width=1)

    // Fill between ±1σ and ±2σ bands
    plotLine(
        value=[band2Sigma, band1Sigma],
        width=1,
        colors=[transparency(bullColor, 15), transparency(bullColor, 15)],
        fill=true,
        label=["2σ Band", "1σ Band"],
        desc=["Upper 2σ band", "Upper 1σ band"]
    )
    plotLine(
        value=[-band1Sigma, -band2Sigma],
        width=1,
        colors=[transparency(bearColor, 15), transparency(bearColor, 15)],
        fill=true,
        label=["1σ Band", "2σ Band"],
        desc=["Lower 1σ band", "Lower 2σ band"]
    )
}

// --- Z-Score Line (regime-colored) ---
if (plotStyle == "Line" || plotStyle == "Both") {
    plotLine(
        value=zSmooth,
        width=2,
        colors=[regimeColor],
        label=["Vol Z"],
        desc=["Smoothed volatility z-score (regime-colored)"]
    )
}

// --- Z-Score Histogram (color-coded by regime) ---
if (plotStyle == "Histogram" || plotStyle == "Both") {
    var histColorIdx = regimeHot ? 0 : (regimeCold ? 1 : 2)
    plotBar(
        value=zSmooth,
        colors=[transparency(bullColor, 60), transparency(bearColor, 60), transparency(neutralColor, 50)],
        colorIndex=histColorIdx,
        width=1,
        label=["Vol Z Hist"],
        desc=["Volatility z-score histogram (color-coded by regime)"]
    )
}

// --- Momentum Histogram ---
if (showMomentum) {
    var momBull = zMom >= 0
    plotBar(
        value=zMom,
        colors=[transparency(bullColor, 40), transparency(bearColor, 40)],
        colorIndex=momBull ? 0 : 1,
        width=1,
        label=["Z Momentum"],
        desc=["Rate of change in smoothed z-score"]
    )
}

// --- Extreme Shape Markers ---
if (showShapes) {
    if (extremeUp) {
        plotShape(
            value=zSmooth,
            shape="triangledown",
            colorIndex=extremeColor,
            width=3,
            label=["Extreme High"],
            desc=["Volatility z-score exceeded +3σ — potential exhaustion / snap-back"]
        )
    }
    if (extremeDown) {
        plotShape(
            value=zSmooth,
            shape="triangleup",
            colorIndex=extremeColor,
            width=3,
            label=["Extreme Low"],
            desc=["Volatility z-score fell below −3σ — potential compression / expansion setup"]
        )
    }
    if (sigma2Up) {
        plotShape(
            value=zSmooth,
            shape="xcross",
            colorIndex=bullColor,
            width=2,
            label=["σ2 Up"],
            desc=["Volatility z-score crossed above +2σ — expansion warning"]
        )
    }
    if (sigma2Down) {
        plotShape(
            value=zSmooth,
            shape="xcross",
            colorIndex=bearColor,
            width=2,
            label=["σ2 Down"],
            desc=["Volatility z-score crossed below −2σ — compression warning"]
        )
    }
    if (crossUp) {
        plotShape(
            value=0,
            shape="circle",
            colorIndex=bullColor,
            width=2,
            label=["Zero Cross Up"],
            desc=["Z-score crossed above zero — expansion beginning"]
        )
    }
    if (crossDown) {
        plotShape(
            value=0,
            shape="circle",
            colorIndex=bearColor,
            width=2,
            label=["Zero Cross Down"],
            desc=["Z-score crossed below zero — compression beginning"]
        )
    }
}

// ---------------------------------------------------------------------------
// 9. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (showRegimeTable && isLastBar) {
    var regimeText = regimeHot ? "EXPANSION" : (regimeCold ? "COMPRESSION" : "NORMAL")
    var regimeTextColor = regimeHot ? bullColor : (regimeCold ? bearColor : neutralColor)

    plotTable(
        data=[
            ["Vol Z-Score — Perfected", regimeText],
            ["Z-Score", zSmooth[0]],
            ["RV Annual", rvAnnual[0]],
            ["RV Mean", mu[0]],
            ["RV Std", sigma[0]],
            ["Z Momentum", zMom[0]],
            ["Hot Bars", hotBars],
            ["Cold Bars", coldBars],
            ["Normal Bars", normalBars]
        ],
        position="top_right",
        headerRow=true,
        headerColumn=true,
        textColor="#e2e8f0",
        headerTextColor="#ffffff",
        backgroundColor=transparency("#0f172a", 40),
        headerBackgroundColor=transparency("#1e293b", 40),
        borderColor=transparency("#334155", 40),
        borderWidth=1,
        fontSize=10,
        cellPadding=4
    )
}