MM Flow
FlowScripts

Perfected FlowScript

SCF ZScore

SCF ZScore — Perfected Edition is indexed as 098_scf_zscore.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

12.9 KB

Lines

440

Native Signal Candidates

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

5/5 guarded

+2σ Cross

line 360:9

Trigger

(showShapes) && (zoneUp2)

Value

z

Deps

showShapes:input, zoneUp2:var

+1σ Cross

line 370:9

Trigger

(showShapes) && (zoneUp1)

Value

z

Deps

showShapes:input, zoneUp1:var

−2σ Cross

line 380:9

Trigger

(showShapes) && (zoneDown2)

Value

z

Deps

showShapes:input, zoneDown2:var

−1σ Cross

line 390:9

Trigger

(showShapes) && (zoneDown1)

Value

z

Deps

showShapes:input, zoneDown1:var

Mean Return

line 400:9

Trigger

(showShapes) && (zoneReturn)

Value

z

Deps

showShapes:input, zoneReturn:var

098_scf_zscore.flowscript

source path: kscripts/perfected/098_scf_zscore.flowscript · sha256:f3b041695b98d1a3e8edbfd01aa401bb5f7d5fd512815478986843524f5c1e5a

hash verified
//@version=2
// ============================================================================
// SCF ZScore — Perfected Edition
// Author: SoulzBTC (@SoulzBTC) | Enhanced by kScript Perfection Engineer
// Tags: STATISTICAL, #zscore, #meanreversion, #regime, #bollinger, #sigma
//
// Production-grade statistical indicator measuring how many standard
// deviations the current price deviates from its historical mean, enhanced
// with ±1/2/3σ bands, color-coded fills, regime detection, shape markers,
// and adaptive smoothing. Identifies extreme price movements and mean
// reversion opportunities with institutional-grade statistical rigor.
//
// Academic foundations:
//  1. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint":
//     z̄ₜ = (zₜ − μ) / σ; entry thresholds at Δ = d × σ (d = 1, 2, 3). [^1]
//  2. QuantOracle (2026), "Z-Score vs Bollinger Bands vs RSI": Z-score < −2
//     or > 2 signals statistical rarity (~95% within ±2σ); composite stacks
//     recommended for confirmation. [^3]
//  3. Poterba & Summers (1988), "Mean Reversion in Stock Prices": returns
//     negatively autocorrelated at medium horizons; temporary deviations
//     from fundamental value revert. [^23]
//  4. Mittal (2025), "Gold-Silver Pair Trading": ML regime filters augment
//     z-score normalization; volatility features improve mean-reversion
//     performance during crisis regimes. [^2]
//  5. Bollinger (2001), "Bollinger on Bollinger Bands": %B = (Close − Lower)
//     / (Upper − Lower) × 100; band-based statistical framing of price
//     position. [^26]
// ============================================================================

define(
    title="SCF ZScore — Perfected Edition",
    position="offchart",
    axis=true
)

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

// --- Source & Lookback ---
var lookback = input(
    name="lookback",
    type="number",
    defaultValue=20,
    label="Z-Score Lookback",
    constraints={min: 5, max: 200, step: 1},
    group="Source & Lookback"
)
var srcChoice = input(
    name="srcChoice",
    type="select",
    defaultValue="close",
    label="Price Source",
    options=["close", "hl2", "ohlc4", "hlc3"],
    group="Source & Lookback"
)
var useLog = input(
    name="useLog",
    type="boolean",
    defaultValue=true,
    label="Use Log Returns",
    group="Source & Lookback"
)

// --- Smoothing ---
var useSmooth = input(
    name="useSmooth",
    type="boolean",
    defaultValue=true,
    label="Apply EMA Smoothing",
    group="Smoothing"
)
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=3,
    label="EMA Smoothing Length",
    constraints={min: 1, max: 20, step: 1},
    group="Smoothing"
)

// --- Sigma Bands ---
var show1Sigma = input(
    name="show1Sigma",
    type="boolean",
    defaultValue=true,
    label="Show ±1σ Bands",
    group="Sigma Bands"
)
var show2Sigma = input(
    name="show2Sigma",
    type="boolean",
    defaultValue=true,
    label="Show ±2σ Bands",
    group="Sigma Bands"
)
var show3Sigma = input(
    name="show3Sigma",
    type="boolean",
    defaultValue=true,
    label="Show ±3σ Bands",
    group="Sigma Bands"
)

// --- Display ---
var showZScore = input(
    name="showZScore",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Line",
    group="Display"
)
var showRaw = input(
    name="showRaw",
    type="boolean",
    defaultValue=false,
    label="Show Raw Z-Score",
    group="Display"
)
var showBandFill = input(
    name="showBandFill",
    type="boolean",
    defaultValue=true,
    label="Show Color-Coded Band Fill",
    group="Display"
)
var showHist = input(
    name="showHist",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Histogram",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Alert Shapes",
    group="Display"
)

// --- Colors ---
var zColor = input(
    name="zColor",
    type="color",
    defaultValue="#2962ff",
    label="Z-Score Line Color",
    group="Colors"
)
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#00e676",
    label="Bullish Color (below −2σ)",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ff5252",
    label="Bearish Color (above +2σ)",
    group="Colors"
)
var neutColor = input(
    name="neutColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)

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

if (isnan(close[0]) || isnan(high[0]) || isnan(low[0])) {
    return
}

// Source selection
timeseries src = srcChoice == "close" ? close : (srcChoice == "hl2" ? (high + low) / 2 : (srcChoice == "ohlc4" ? (open + high + low + close) / 4 : (high + low + close) / 3))

// -------------------------------------------------------------------------
// 3. Z-SCORE COMPUTATION
// -------------------------------------------------------------------------

// Mean and std dev over lookback
// Use log returns if requested; guard against log(0) or negative
var srcLog = useLog ? math.log(src) : src
var meanLog = useLog ? sma(source=math.log(src), period=lookback) : sma(source=src, period=lookback)

// For log z-score, we compute on log(src), then interpret in log space
timeseries mean = useLog ? exp(meanLog) : meanLog
timeseries std = stdev(source=srcLog, period=lookback)

// Raw z-score
timeseries zRaw = std > 0 ? (srcLog - meanLog) / std : 0

// If not using log, compute raw price z-score directly
if (!useLog) {
    zRaw = std > 0 ? (src - mean) / std : 0
}

// Smooth z-score
timeseries z = useSmooth ? ema(source=zRaw, period=smoothLen) : zRaw

// -------------------------------------------------------------------------
// 4. REGIME DETECTION
// -------------------------------------------------------------------------
// Regime classification based on σ levels:
//   Extreme Bullish (mean reversion): z < −2
//   Extreme Bearish (mean reversion): z > +2
//   Mild Bullish: z < −1
//   Mild Bearish: z > +1
//   Neutral: −1 ≤ z ≤ +1

var regimeExtremeBull = z < -2.0
var regimeExtremeBear = z > 2.0
var regimeMildBull = z < -1.0 && z >= -2.0
var regimeMildBear = z > 1.0 && z <= 2.0
var regimeNeutral = z >= -1.0 && z <= 1.0

var regimeColor = regimeExtremeBull ? bullColor : (regimeExtremeBear ? bearColor : (regimeMildBull ? transparency(bullColor, 60) : (regimeMildBear ? transparency(bearColor, 60) : neutColor)))

// -------------------------------------------------------------------------
// 5. STATIC STATE TRACKING
// -------------------------------------------------------------------------
static prevRegimeZone = 0  // 0=neutral, 1=mild bear, 2=extreme bear, -1=mild bull, -2=extreme bull
static prevZ = -999.0

var zoneUp2 = false
var zoneUp1 = false
var zoneDown2 = false
var zoneDown1 = false
var zoneReturn = false

var currentZone = 0
if (regimeExtremeBear) {
    currentZone = 2
} else if (regimeMildBear) {
    currentZone = 1
} else if (regimeExtremeBull) {
    currentZone = -2
} else if (regimeMildBull) {
    currentZone = -1
}

if (!isLiveUpdate) {
    if (currentZone == 2 && prevRegimeZone != 2) {
        zoneUp2 = true
    }
    if (currentZone == 1 && prevRegimeZone < 1) {
        zoneUp1 = true
    }
    if (currentZone == -2 && prevRegimeZone != -2) {
        zoneDown2 = true
    }
    if (currentZone == -1 && prevRegimeZone > -1) {
        zoneDown1 = true
    }
    if (currentZone == 0 && prevRegimeZone != 0) {
        zoneReturn = true
    }
    prevRegimeZone = currentZone
    prevZ = z
}

// -------------------------------------------------------------------------
// 6. PLOTTING
// -------------------------------------------------------------------------

// --- Mean line ---
hline(value=0, color="#ffffff40", width=1)

// --- ±1σ Bands ---
if (show1Sigma) {
    hline(value=1, color=transparency(bullColor, 60), width=1)
    hline(value=-1, color=transparency(bearColor, 60), width=1)
}

// --- ±2σ Bands ---
if (show2Sigma) {
    hline(value=2, color=transparency(bullColor, 40), width=1)
    hline(value=-2, color=transparency(bearColor, 40), width=1)
}

// --- ±3σ Bands ---
if (show3Sigma) {
    hline(value=3, color=transparency(bullColor, 20), width=1)
    hline(value=-3, color=transparency(bearColor, 20), width=1)
}

// --- Color-coded band fill (regime-based) ---
if (showBandFill) {
    var fillColor = regimeExtremeBull ? transparency(bullColor, 20) : (regimeExtremeBear ? transparency(bearColor, 20) : "#00000000")
    if (regimeExtremeBull) {
        plotLine(
            value=[0, z],
            width=1,
            colors=[transparency(bullColor, 30), transparency(bullColor, 30)],
            fill=transparency(bullColor, 15),
            label=["Fill", "Fill"],
            desc=["Extreme bullish zone fill", "Extreme bullish zone fill"]
        )
    } else if (regimeExtremeBear) {
        plotLine(
            value=[0, z],
            width=1,
            colors=[transparency(bearColor, 30), transparency(bearColor, 30)],
            fill=transparency(bearColor, 15),
            label=["Fill", "Fill"],
            desc=["Extreme bearish zone fill", "Extreme bearish zone fill"]
        )
    }
}

// --- Z-Score Line (regime-colored) ---
if (showZScore) {
    plotLine(
        value=z,
        width=2,
        colors=[regimeColor],
        label=["Z-Score"],
        desc=["Adaptive smoothed z-score (" + lookback + "-period lookback)"]
    )
}

// --- Raw Z-Score ---
if (showRaw) {
    plotLine(
        value=zRaw,
        width=1,
        colors=["#9e9e9e"],
        label=["Z Raw"],
        desc=["Unsmoothed z-score"]
    )
}

// --- Z-Score Histogram ---
if (showHist) {
    var histBull = z >= 0
    plotBar(
        value=z,
        colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["Z Histogram"],
        desc=["Z-score histogram (positive = above mean, negative = below mean)"]
    )
}

// --- Shape Markers ---
if (showShapes) {
    if (zoneUp2) {
        plotShape(
            value=z,
            shape="triangledown",
            colorIndex=bearColor,
            width=2,
            label=["+2σ Cross"],
            desc=["Z-score crossed above +2σ — extreme overbought / mean reversion signal"]
        )
    }
    if (zoneUp1) {
        plotShape(
            value=z,
            shape="arrowdown",
            colorIndex=transparency(bearColor, 60),
            width=1,
            label=["+1σ Cross"],
            desc=["Z-score crossed above +1σ — mildly extended"]
        )
    }
    if (zoneDown2) {
        plotShape(
            value=z,
            shape="triangleup",
            colorIndex=bullColor,
            width=2,
            label=["−2σ Cross"],
            desc=["Z-score crossed below −2σ — extreme oversold / mean reversion signal"]
        )
    }
    if (zoneDown1) {
        plotShape(
            value=z,
            shape="arrowup",
            colorIndex=transparency(bullColor, 60),
            width=1,
            label=["−1σ Cross"],
            desc=["Z-score crossed below −1σ — mildly extended"]
        )
    }
    if (zoneReturn) {
        plotShape(
            value=z,
            shape="circle",
            colorIndex=neutColor,
            width=2,
            label=["Mean Return"],
            desc=["Z-score returned to neutral zone (−1σ to +1σ)"]
        )
    }
}

// -------------------------------------------------------------------------
// 7. REGIME TABLE (last bar only)
// -------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeExtremeBull ? "EXTREME BULL (MR)" : (regimeExtremeBear ? "EXTREME BEAR (MR)" : (regimeMildBull ? "MILD BULL" : (regimeMildBear ? "MILD BEAR" : "NEUTRAL")))
    var regimeTextColor = regimeExtremeBull ? bullColor : (regimeExtremeBear ? bearColor : neutColor)

    plotTable(
        data=[
            ["SCF ZScore — Perfected", regimeText],
            ["Z-Score", z[0]],
            ["Mean", mean[0]],
            ["Std Dev", std[0]],
            ["Source", src[0]],
            ["Lookback", lookback]
        ],
        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
    )
}