MM Flow
FlowScripts

Perfected FlowScript

Z-Score Mean Reversion

Z-Score Mean Reversion — Perfected Edition is indexed as 250_z_score_mean_reversion.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

20.9 KB

Lines

515

Native Signal Candidates

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

7/7 guarded

Stretched Pos

line 410:9

Trigger

(showShapes) && (crossUp)

Value

zScore

Deps

crossUp:var, showShapes:input

Stretched Neg

line 420:9

Trigger

(showShapes) && (crossDn)

Value

zScore

Deps

crossDn:var, showShapes:input

Extreme Pos

line 430:9

Trigger

(showShapes) && (extremeUpCross)

Value

zScore

Deps

extremeUpCross:var, showShapes:input

Extreme Neg

line 440:9

Trigger

(showShapes) && (extremeDnCross)

Value

zScore

Deps

extremeDnCross:var, showShapes:input

Zero Cross Up

line 450:9

Trigger

(showShapes) && (zeroUp)

Value

zScore

Deps

showShapes:input, zeroUp:var

Zero Cross Down

line 460:9

Trigger

(showShapes) && (zeroDn)

Value

zScore

Deps

showShapes:input, zeroDn:var

Reverting

line 470:9

Trigger

(showShapes) && (revertSignal)

Value

zScore

Deps

revertSignal:var, showShapes:input

250_z_score_mean_reversion.flowscript

source path: kscripts/perfected/250_z_score_mean_reversion.flowscript · sha256:5d3f02021d9657e5248952bc52f5f773382dbbac6b5b92b20265c1565b1f60ca

hash verified
//@version=2
// ============================================================================
// Z-Score Mean Reversion — Perfected Edition
// Author: D (@ddave334)  |  Perfected by: kScript Perfection Engineer
// Tags: CORE, #zscore, #meanreversion, #volatility, #regime, #momentum
//
// Production-quality z-score oscillator with multi-metric normalization,
// regime detection (stretched / reverting / neutral), dynamic volatility-
// adjusted thresholds, color-coded histogram, fill visualization, and
// comprehensive shape-marker alerts for statistical-extremity events.
//
// FORMULA FOUNDATION:
// 1. Z-Score: z = (x − μ) / σ  where μ = rolling mean, σ = rolling std dev.
//    Per Zhao & Palomar (2018), z-score measures distance to equilibrium in
//    standard deviations; entry thresholds at d × σ (typically d = 1 or 2).
// 2. Regime Segmentation:
//    Stretched: |z| > upperZ (statistically extreme, mean-reversion expected).
//    Extreme: |z| > extremeUp (rare event, ~0.3% tail probability).
//    Reverting: |z| < 1 and prior |z| > upperZ (returning toward mean).
//    Neutral: everything else (random walk zone).
//    Per Poterba & Summers (1988), negative autocorrelation at medium horizons.
// 3. Dynamic Thresholds: adjusted by rolling RSI volatility per Poterba &
//    Summers (1988); mean-reversion intensity varies with volatility regime.
// 4. Mean Reversion Bands on Price: μ ± k·σ for visual envelope of expected
//    price range, per Bollinger (2001) and Leung & Chong (2003).
//
// RESEARCH BASIS:
//  • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint",
//    IEEE Trans. Signal Processing 66(9), 2346–2360. Z-score event triggers
//    for mean reversion: z̄_t = (z_t − μ_z) / σ_z; entry at ±d·σ.
//  • Poterba & Summers (1988), "Mean Reversion in Stock Prices: Evidence and
//    Implications", J. Financial Economics 22(1), 27–59. Negative
//    autocorrelation at medium horizons; temporary deviations revert.
//  • Lo & MacKinlay (1988), "Stock Market Prices Do Not Follow Random Walks:
//    Evidence from a Simple Specification Test", Rev. Financial Studies 1(1),
//    41–66. Variance ratio test: VR(q) > 1 = momentum, VR(q) < 1 = mean
//    reversion. Underpins regime-switching interpretation of z-score.
//  • Bollinger (2001), "Bollinger on Bollinger Bands". Band methodology:
//    moving average ± k·standard deviations; ~95% of price within 2σ.
//  • Leung & Chong (2003), "An Empirical Comparison of Moving Average Envelopes
//    and Bollinger Bands". BB at 2σ captures ~95% of movement; superior to
//    MA envelopes for abrupt fluctuations.
//  • Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling Losers".
//    Momentum as cross-sectional anomaly; z-score extremes can flag both
//    mean-reversion entries and momentum continuation in strong trends.
// ============================================================================

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

// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------

// --- Z-Score Settings ---
var lookback = input(name="lookback", type="number", defaultValue=20, label="Lookback (bars)", constraints={min: 5, max: 200, step: 1}, group="Z-Score")
var zSource = input(name="zSource", type="select", defaultValue="close", label="Z-Score Source", options=["close", "hlc3", "returns", "volume"], group="Z-Score")
var useLogReturns = input(name="useLogReturns", type="boolean", defaultValue=false, label="Use Log Returns (if source=returns)", group="Z-Score")

// --- Smoothing ---
var smoothLen = input(name="smoothLen", type="number", defaultValue=3, label="EMA Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Smoothing")
var useSignalMA = input(name="useSignalMA", type="boolean", defaultValue=true, label="Use Signal SMA", group="Smoothing")
var signalLen = input(name="signalLen", type="number", defaultValue=14, label="Signal SMA Length", constraints={min: 2, max: 50, step: 1}, group="Smoothing")

// --- Thresholds ---
var upperZ = input(name="upperZ", type="number", defaultValue=2.0, label="Upper Z Threshold (σ)", constraints={min: 0.5, max: 5.0, step: 0.1}, group="Thresholds")
var lowerZ = input(name="lowerZ", type="number", defaultValue=-2.0, label="Lower Z Threshold (σ)", constraints={min: -5.0, max: -0.5, step: 0.1}, group="Thresholds")
var extremeUp = input(name="extremeUp", type="number", defaultValue=3.0, label="Extreme Upper (σ)", constraints={min: 1.5, max: 6.0, step: 0.1}, group="Thresholds")
var extremeDn = input(name="extremeDn", type="number", defaultValue=-3.0, label="Extreme Lower (σ)", constraints={min: -6.0, max: -1.5, step: 0.1}, group="Thresholds")
var useDynamic = input(name="useDynamic", type="boolean", defaultValue=false, label="Dynamic Thresholds (vol-adjusted)", group="Thresholds")
var volLookback = input(name="volLookback", type="number", defaultValue=20, label="Volatility Lookback", constraints={min: 5, max: 100, step: 1}, group="Thresholds")
var volMultiplier = input(name="volMultiplier", type="number", defaultValue=1.0, label="Volatility Multiplier", constraints={min: 0.5, max: 3.0, step: 0.1}, group="Thresholds")

// --- Display ---
var showHistogram = input(name="showHistogram", type="boolean", defaultValue=true, label="Show Z-Score Histogram", group="Display")
var showLine = input(name="showLine", type="boolean", defaultValue=true, label="Show Z-Score Line", group="Display")
var showSignal = input(name="showSignal", type="boolean", defaultValue=true, label="Show Signal SMA", group="Display")
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Fill Area", group="Display")
var showGuides = input(name="showGuides", type="boolean", defaultValue=true, label="Show Guide Lines", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Alert Shapes", group="Display")
var showPriceBands = input(name="showPriceBands", type="boolean", defaultValue=false, label="Show Price Mean Reversion Bands", group="Display")

// --- Colors ---
var zColor = input(name="zColor", type="color", defaultValue="#ffffff", label="Z-Score Color", group="Colors")
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="Bullish / Positive Z", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ef5350", label="Bearish / Negative Z", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var extremeColor = input(name="extremeColor", type="color", defaultValue="#ffeb3b", label="Extreme Color", group="Colors")
var revertColor = input(name="revertColor", type="color", defaultValue="#29b6f6", label="Reverting Color", group="Colors")
var signalColor = input(name="signalColor", type="color", defaultValue="#ffffff", label="Signal Line Color", group="Colors")

// ------------------------------------------------------------------------------
// Data Sources & NaN Guard
// ------------------------------------------------------------------------------
timeseries ohlcvTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = ohlcvTS.close
timeseries hlc3 = (ohlcvTS.high + ohlcvTS.low + ohlcvTS.close) / 3

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

// ------------------------------------------------------------------------------
// Z-Score Source Selection
// ------------------------------------------------------------------------------
// Choose the series to normalize: close price, HLC3, returns, or volume.

timeseries source = px

if (zSource == "hlc3") {
    source = hlc3
} else if (zSource == "returns") {
    if (useLogReturns) {
        source = px[0] > 0 && px[1] > 0 ? math.log(px[0] / px[1]) : 0.0
    } else {
        source = px[1] != 0 ? (px[0] - px[1]) / px[1] : 0.0
    }
} else if (zSource == "volume") {
    source = ohlcvTS.volume
}

// ------------------------------------------------------------------------------
// Z-Score Computation
// ------------------------------------------------------------------------------
// z = (x − μ) / σ  over rolling lookback window.
// Per Zhao & Palomar (2018), standardized deviation from equilibrium.

timeseries mean = sma(source=source, period=lookback)
timeseries std = stddev(source=source, period=lookback)
timeseries zRaw = std > 0 ? (source - mean) / std : 0.0

// EMA smoothing for noise reduction
timeseries zScore = ema(source=zRaw, period=smoothLen)

// Signal SMA for crossover detection
timeseries signal = useSignalMA ? sma(source=zScore, period=signalLen) : 0.0

// ------------------------------------------------------------------------------
// Dynamic Thresholds (volatility-adjusted per Poterba & Summers 1988)
// ------------------------------------------------------------------------------
// Adjust OB/OS bands by rolling z-score standard deviation.

timeseries zVol = stddev(source=zScore, period=volLookback)
var dynUpper = useDynamic ? math.min(4.0, upperZ + zVol * volMultiplier) : upperZ
var dynLower = useDynamic ? math.max(-4.0, lowerZ - zVol * volMultiplier) : lowerZ
var dynExtremeUp = useDynamic ? math.min(5.0, extremeUp + zVol * volMultiplier * 0.5) : extremeUp
var dynExtremeDn = useDynamic ? math.max(-5.0, extremeDn - zVol * volMultiplier * 0.5) : extremeDn

// Guard: ensure dynamic bands never cross
if (dynUpper <= dynLower) {
    dynUpper = 2.0
    dynLower = -2.0
}
if (dynExtremeUp <= dynExtremeDn) {
    dynExtremeUp = 3.0
    dynExtremeDn = -3.0
}

// ------------------------------------------------------------------------------
// Regime Detection
// ------------------------------------------------------------------------------
// Regime classification:
//   Stretched Positive: zScore ≥ dynUpper
//   Stretched Negative: zScore ≤ dynLower
//   Extreme Positive: zScore ≥ dynExtremeUp
//   Extreme Negative: zScore ≤ dynExtremeDn
//   Reverting: prior |z| > dynUpper and now |z| < dynUpper and moving toward 0
//   Neutral: everything else

var regime = 0       // 0 = neutral, 1 = stretched pos, -1 = stretched neg
var extremeRegime = 0   // 0 = normal, 1 = extreme pos, -1 = extreme neg
var isReverting = false
var momentumBull = false
var momentumBear = false

if (zScore >= dynUpper) {
    regime = 1
} else if (zScore <= dynLower) {
    regime = -1
}

if (zScore >= dynExtremeUp) {
    extremeRegime = 1
} else if (zScore <= dynExtremeDn) {
    extremeRegime = -1
}

// Reverting detection: was stretched and is now returning toward mean
var priorStretched = !isnan(zScore[1]) && (zScore[1] >= dynUpper || zScore[1] <= dynLower)
var nowLessStretched = zScore < dynUpper && zScore > dynLower
var movingTowardZero = !isnan(zScore[1]) && math.abs(zScore) < math.abs(zScore[1])
if (priorStretched && nowLessStretched && movingTowardZero) {
    isReverting = true
}

// Momentum: zScore above signal and positive / below signal and negative
if (useSignalMA) {
    momentumBull = zScore > signal && zScore > 0
    momentumBear = zScore < signal && zScore < 0
}

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Tracks max/min z, threshold crosses, extreme events, and reversion counts.

static lastRegime = 0
static maxZ = -999999.0
static minZ = 999999.0
static crossAboveCount = 0
static crossBelowCount = 0
static extremeAboveCount = 0
static extremeBelowCount = 0
static revertCount = 0
static lastBarIndex = 0
static lastZ = 0.0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    lastBarIndex = currentBarIndex

    if (zScore > maxZ) {
        maxZ = zScore
    }
    if (zScore < minZ) {
        minZ = zScore
    }

    if (lastRegime != regime) {
        lastRegime = regime
    }

    // Cross above threshold
    if (lastZ < dynUpper && zScore >= dynUpper) {
        crossAboveCount = crossAboveCount + 1
    }
    // Cross below threshold
    if (lastZ > dynLower && zScore <= dynLower) {
        crossBelowCount = crossBelowCount + 1
    }
    // Extreme above
    if (lastZ < dynExtremeUp && zScore >= dynExtremeUp) {
        extremeAboveCount = extremeAboveCount + 1
    }
    // Extreme below
    if (lastZ > dynExtremeDn && zScore <= dynExtremeDn) {
        extremeBelowCount = extremeBelowCount + 1
    }
    // Reversion
    if (isReverting) {
        revertCount = revertCount + 1
    }

    lastZ = zScore
}

// ------------------------------------------------------------------------------
// Mean Reversion Bands on Price (Bollinger 2001)
// ------------------------------------------------------------------------------
// Optional overlay: price ± k·σ envelope for visual mean-reversion context.

if (showPriceBands) {
    timeseries upperBand = mean + upperZ * std
    timeseries lowerBand = mean + lowerZ * std
    timeseries extremeUpperBand = mean + extremeUp * std
    timeseries extremeLowerBand = mean + extremeDn * std

    plotLine(
        value=[upperBand, mean, lowerBand],
        width=[1, 2, 1],
        colors=[bullColor, zColor, bearColor],
        label=["Upper Band", "Mean", "Lower Band"],
        desc=["Mean reversion envelope: μ ± k·σ (Zhao & Palomar 2018)"]
    )

    hline(value=extremeUpperBand, color=opacity(extremeColor, 20), width=1)
    hline(value=extremeLowerBand, color=opacity(extremeColor, 20), width=1)
}

// ------------------------------------------------------------------------------
// Plots — Multiple Visualization Types (Line, Bar, Fill, Shape, HLine)
// ------------------------------------------------------------------------------

// Horizontal guide lines — zero line and threshold zones
hline(value=0, color="#ffffff30", width=1)

if (showGuides) {
    hline(value=dynUpper, color=opacity(bullColor, 30), width=1)
    hline(value=dynLower, color=opacity(bearColor, 30), width=1)
    hline(value=dynExtremeUp, color=opacity(extremeColor, 20), width=1)
    hline(value=dynExtremeDn, color=opacity(extremeColor, 20), width=1)
}

// Z-Score histogram (color-coded by regime)
if (showHistogram) {
    var histColorIdx = 0
    if (extremeRegime == 1) {
        histColorIdx = 3  // extreme
    } else if (extremeRegime == -1) {
        histColorIdx = 3  // extreme
    } else if (regime == 1) {
        histColorIdx = 0  // stretched pos
    } else if (regime == -1) {
        histColorIdx = 1  // stretched neg
    } else if (isReverting) {
        histColorIdx = 4  // reverting
    } else {
        histColorIdx = 2  // neutral
    }

    plotBar(
        value=zScore,
        colors=[bullColor, bearColor, neutralColor, extremeColor, revertColor],
        colorIndex=histColorIdx,
        width=1,
        label=["Z-Score Histogram"],
        desc=["Standardized deviation histogram (green=pos stretched, red=neg stretched, yellow=extreme, blue=reverting, grey=neutral)"]
    )
}

// Z-Score line with regime-coded fill
if (showLine) {
    var lineColorIdx = 0
    if (extremeRegime == 1) {
        lineColorIdx = 3
    } else if (extremeRegime == -1) {
        lineColorIdx = 3
    } else if (regime == 1) {
        lineColorIdx = 0
    } else if (regime == -1) {
        lineColorIdx = 1
    } else if (isReverting) {
        lineColorIdx = 4
    } else {
        lineColorIdx = 2
    }

    plotLine(
        value=zScore,
        width=2,
        colors=[bullColor, bearColor, neutralColor, extremeColor, revertColor],
        colorIndex=lineColorIdx,
        label=["Z-Score"],
        desc=["Smoothed z-score with regime coloring (Poterba & Summers 1988)"],
        fill=showFill
    )
}

// Fill area between z-score and zero line
if (showFill) {
    var fillColorIdx = zScore >= 0 ? 0 : 1
    plotLine(
        value=[zScore, 0],
        width=1,
        colors=[opacity(bullColor, 20), opacity(bearColor, 20)],
        colorIndex=fillColorIdx,
        fill=true,
        label=["Z-Score", "Zero"],
        desc=["Fill between z-score and zero line"]
    )
}

// Signal SMA line
if (showSignal && useSignalMA) {
    plotLine(
        value=signal,
        width=1,
        colors=[signalColor],
        label=["Signal SMA"],
        desc=["SMA of smoothed z-score (" + signalLen + ") — crossover detection"]
    )
}

// Signal crossover fill (z-score vs signal)
if (showFill && useSignalMA) {
    var sigBull = zScore > signal
    plotLine(
        value=[zScore, signal],
        width=1,
        colors=[opacity(bullColor, 15), opacity(bearColor, 15)],
        colorIndex=sigBull ? 0 : 1,
        fill=true,
        label=["Z-Score", "Signal"],
        desc=["Fill between z-score and signal SMA"]
    )
}

// Alert shapes
if (showShapes) {
    // Cross above upper threshold
    var crossUp = zScore >= dynUpper && !isnan(zScore[1]) && zScore[1] < dynUpper
    // Cross below lower threshold
    var crossDn = zScore <= dynLower && !isnan(zScore[1]) && zScore[1] > dynLower
    // Cross into extreme upper
    var extremeUpCross = zScore >= dynExtremeUp && !isnan(zScore[1]) && zScore[1] < dynExtremeUp
    // Cross into extreme lower
    var extremeDnCross = zScore <= dynExtremeDn && !isnan(zScore[1]) && zScore[1] > dynExtremeDn
    // Zero cross up
    var zeroUp = zScore >= 0 && !isnan(zScore[1]) && zScore[1] < 0
    // Zero cross down
    var zeroDn = zScore <= 0 && !isnan(zScore[1]) && zScore[1] > 0
    // Reversion signal
    var revertSignal = isReverting

    if (crossUp) {
        plotShape(
            value=zScore,
            shape="triangleup",
            color=bullColor,
            width=3,
            label=["Stretched Pos"],
            desc=["Z-score crossed above upper threshold — statistically stretched, mean reversion expected"]
        )
    }
    if (crossDn) {
        plotShape(
            value=zScore,
            shape="triangledown",
            color=bearColor,
            width=3,
            label=["Stretched Neg"],
            desc=["Z-score crossed below lower threshold — statistically stretched, mean reversion expected"]
        )
    }
    if (extremeUpCross) {
        plotShape(
            value=zScore,
            shape="diamond",
            color=extremeColor,
            width=4,
            label=["Extreme Pos"],
            desc=["Z-score reached extreme positive level — rare event, high mean-reversion probability"]
        )
    }
    if (extremeDnCross) {
        plotShape(
            value=zScore,
            shape="diamond",
            color=extremeColor,
            width=4,
            label=["Extreme Neg"],
            desc=["Z-score reached extreme negative level — rare event, high mean-reversion probability"]
        )
    }
    if (zeroUp) {
        plotShape(
            value=zScore,
            shape="circle",
            color=bullColor,
            width=2,
            label=["Zero Cross Up"],
            desc=["Z-score crossed above zero — momentum turning positive"]
        )
    }
    if (zeroDn) {
        plotShape(
            value=zScore,
            shape="circle",
            color=bearColor,
            width=2,
            label=["Zero Cross Down"],
            desc=["Z-score crossed below zero — momentum turning negative"]
        )
    }
    if (revertSignal) {
        plotShape(
            value=zScore,
            shape="xcross",
            color=revertColor,
            width=2,
            label=["Reverting"],
            desc=["Z-score returning from stretched toward mean — mean reversion in progress (Poterba & Summers 1988)"]
        )
    }
}

// ------------------------------------------------------------------------------
// Regime Table (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = extremeRegime == 1 ? "EXTREME POS" : (extremeRegime == -1 ? "EXTREME NEG" : (regime == 1 ? "STRETCHED POS" : (regime == -1 ? "STRETCHED NEG" : "NEUTRAL")))
    var regimeTextColor = extremeRegime == 1 ? extremeColor : (extremeRegime == -1 ? extremeColor : (regime == 1 ? bullColor : (regime == -1 ? bearColor : neutralColor)))
    var dynText = useDynamic ? "Dynamic" : "Static"

    plotTable(
        data=[
            ["Z-Score — Perfected", regimeText],
            ["Z-Score Value", zScore[0]],
            ["Session Max Z", maxZ],
            ["Session Min Z", minZ],
            ["Signal SMA", signal[0]],
            [dynText + " Upper", dynUpper],
            [dynText + " Lower", dynLower],
            ["Stretched Crosses", crossAboveCount + crossBelowCount],
            ["Extreme Events", extremeAboveCount + extremeBelowCount],
            ["Reversions", revertCount]
        ],
        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
    )
}