MM Flow
FlowScripts

Perfected FlowScript

OBV Z-Score

OBV Z-Score Pro is indexed as 093_obv_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

15.6 KB

Lines

516

Native Signal Candidates

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

6/6 guarded

Ultra Accumulation

line 410:9

Trigger

(showShapes) && (isUltraAccum)

Value

threeSigma

Deps

isUltraAccum:var, showShapes:input

Ultra Distribution

line 420:9

Trigger

(showShapes) && (isUltraDist)

Value

negThreeSigma

Deps

isUltraDist:var, showShapes:input

Extreme Accum

line 430:9

Trigger

(showShapes) && (isExtremeAccum && !isUltraAccum)

Value

twoSigma

Deps

isExtremeAccum:var, isUltraAccum:var, showShapes:input

Extreme Dist

line 440:9

Trigger

(showShapes) && (isExtremeDist && !isUltraDist)

Value

negTwoSigma

Deps

isExtremeDist:var, isUltraDist:var, showShapes:input

OBV Bull Div

line 454:9

Trigger

(showDivergence) && (bullDiv)

Value

obvZ

Deps

bullDiv:var, showDivergence:input

OBV Bear Div

line 464:9

Trigger

(showDivergence) && (bearDiv)

Value

obvZ

Deps

bearDiv:var, showDivergence:input

093_obv_z_score.flowscript

source path: kscripts/perfected/093_obv_z_score.flowscript · sha256:a42c3603290d5b30af02d430e721516cb7a0145fd3abdcc7cdc54b0261369ff8

hash verified
//@version=2

// ============================================================================
// OBV Z-Score Pro — On-Balance Volume with Statistical Normalization & Regime Detection
// Author: BackQuant (@BackQuant) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, VOLUME, #obv, #zscore, #regime, #divergence
//
// Standardizes On-Balance Volume (OBV) into a rolling z-score to identify when
// volume accumulation or distribution is statistically unusual versus recent history.
// Features ±1/2/3σ bands with fill, regime detection (accumulation/distribution/neutral),
// price-OBV divergence alerts, and cumulative state tracking.
//
// Academic foundation (exact papers & formulas):
//  1. Granville (1963), original OBV concept: cumulative signed volume where
//     sign = +1 if close > prior close, −1 if close < prior close, 0 otherwise.
//     OBV_t = OBV_{t−1} + sign_t · volume_t
//
//  2. Wilder (1978), "New Concepts in Technical Trading Systems". Formalized
//     rule-based volume confirmation systems. OBV as a leading indicator of
//     price direction when divergences appear.
//
//  3. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint",
//     IEEE Transactions on Signal Processing. z_t = (x_t − μ_t) / σ_t with entry
//     thresholds at d × σ (typically d = 1, 2, 3). Validates z-score as a
//     mean-reversion signal generator.
//
//  4. Poterba & Summers (1988), "Mean Reversion in Stock Prices: Evidence and
//     Implications", Journal of Financial Economics, 22(1), 27–59.
//     Negative autocorrelation at medium horizons; extreme z-scores (> 2σ or < −2σ)
//     predict statistically significant return reversals.
//     DOI: https://doi.org/10.1016/0304-405X(88)90021-9
//
//  5. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//     Market Returns", Journal of Financial Economics, 65(1), 111–130.
//     Extreme signed volume imbalances predict return reversals. Directly
//     motivates the accumulation/distribution regime threshold design.
//     DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
//
//  6. Lo & MacKinlay (1988), "Stock Market Prices Do Not Follow Random Walks",
//     Review of Financial Studies, 1(1), 41–66. Variance-ratio test shows
//     significant autocorrelation in volume-augmented returns. Validates that
//     volume-weighted indicators carry predictive content beyond price alone.
//     DOI: https://doi.org/10.1093/rfs/1.1.41
//
//  7. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
//     Journal of Finance, 46(2), 733–746. Tick-test classification (close vs.
//     prior close) used as the OBV sign rule. 85–93% accuracy on NYSE TORQ data.
//     DOI: https://doi.org/10.1111/j.1540-6261.1991.tb02683.x
// ============================================================================

define(title="OBV Z-Score Pro", position="offchart", axis=true)

// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------

// -- Computation --
var zWindow = input(
    name="zWindow",
    type="number",
    defaultValue=30,
    label="Z-Score Lookback (bars)",
    constraints={min: 10, max: 200, step: 5},
    group="Computation"
)
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=3,
    label="EMA Smooth Length",
    constraints={min: 1, max: 20, step: 1},
    group="Computation"
)
var useSmooth = input(
    name="useSmooth",
    type="boolean",
    defaultValue=true,
    label="Apply EMA Smoothing",
    group="Computation"
)
var divLookback = input(
    name="divLookback",
    type="number",
    defaultValue=14,
    label="Divergence Lookback (bars)",
    constraints={min: 5, max: 50, step: 1},
    group="Computation"
)

// -- Sigma Bands --
var showSigma1 = input(
    name="showSigma1",
    type="boolean",
    defaultValue=true,
    label="Show ±1σ Band",
    group="Sigma Bands"
)
var showSigma2 = input(
    name="showSigma2",
    type="boolean",
    defaultValue=true,
    label="Show ±2σ Band",
    group="Sigma Bands"
)
var showSigma3 = input(
    name="showSigma3",
    type="boolean",
    defaultValue=true,
    label="Show ±3σ Band",
    group="Sigma Bands"
)

// -- Display --
var showRawOBV = input(
    name="showRawOBV",
    type="boolean",
    defaultValue=false,
    label="Show Raw OBV Line",
    group="Display"
)
var showZRaw = input(
    name="showZRaw",
    type="boolean",
    defaultValue=false,
    label="Show Unsmoothed Z-Score",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show Sigma Fill Areas",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Extreme Shape Alerts",
    group="Display"
)
var showDivergence = input(
    name="showDivergence",
    type="boolean",
    defaultValue=true,
    label="Show Price-OBV Divergence Shapes",
    group="Display"
)
var showRegime = input(
    name="showRegime",
    type="boolean",
    defaultValue=true,
    label="Show Regime Histogram",
    group="Display"
)

// -- Colors --
var accColor = input(
    name="accColor",
    type="color",
    defaultValue="#00c853",
    label="Accumulation Color",
    group="Colors"
)
var distColor = input(
    name="distColor",
    type="color",
    defaultValue="#d50000",
    label="Distribution Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#78909c",
    label="Neutral Color",
    group="Colors"
)
var obvColor = input(
    name="obvColor",
    type="color",
    defaultValue="#2962ff",
    label="OBV Line Color",
    group="Colors"
)
var zColor = input(
    name="zColor",
    type="color",
    defaultValue="#ffd600",
    label="Z-Score Line Color",
    group="Colors"
)

// ---------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ---------------------------------------------------------------------------

timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = bars.close
timeseries vol = bars.volume

// Guard: halt until price and volume data have loaded
if (isnan(close[0]) || isnan(vol[0])) {
    return
}

// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------

// -- 3.1 On-Balance Volume (Granville 1963; Wilder 1978) --
// OBV_t = OBV_{t−1} + sign_t · volume_t
// sign = +1 if close > close[1], −1 if close < close[1], 0 otherwise
// We use static state for true cumulative OBV to avoid platform-dependent cum() quirks.

static obvCum = 0.0

var priceUp = close > close[1]
var priceDn = close < close[1]
var signVol = priceUp ? vol : (priceDn ? -vol : 0)

if (!isnan(signVol[0])) {
    obvCum = obvCum + signVol[0]
}

// -- 3.2 Rolling-window OBV (stationary approximation for z-score) --
// We compute a rolling sum of signed volume over the lookback window so the
// series remains mean-reverting and amenable to z-score standardization.
timeseries obvRolling = sum(signVol, zWindow)

// -- 3.3 Z-score normalisation (all denominators guarded against zero) --
// Z_t = (OBV_t − μ_t) / σ_t, where μ_t = SMA(OBV, W), σ_t = StDev(OBV, W).
// Per Zhao & Palomar (2018): thresholds at d × σ, typically d = 1, 2, 3.

timeseries obvMean = sma(source=obvRolling, period=zWindow)
timeseries obvStd = stdev(source=obvRolling, period=zWindow)

timeseries obvZRaw = (obvStd > 0) ? (obvRolling - obvMean) / obvStd : 0
timeseries obvZ = useSmooth ? ema(source=obvZRaw, period=smoothLen) : obvZRaw

// -- 3.4 Sigma band levels --
timeseries zeroLine = 0
timeseries oneSigma = 1
timeseries twoSigma = 2
timeseries threeSigma = 3
timeseries negOneSigma = -1
timeseries negTwoSigma = -2
timeseries negThreeSigma = -3

// -- 3.5 Regime detection (accumulation vs distribution vs neutral) --
// Accumulation: z-score > +1σ (unusual buying pressure / volume accumulation)
// Distribution: z-score < −1σ (unusual selling pressure / volume distribution)
// Neutral: within ±1σ

var isAccumulation = obvZ > oneSigma
var isDistribution = obvZ < negOneSigma
var isNeutral = !isAccumulation && !isDistribution

// -- 3.6 Extreme regime detection (for shape alerts) --
var isExtremeAccum = obvZ > twoSigma
var isExtremeDist = obvZ < negTwoSigma
var isUltraAccum = obvZ > threeSigma
var isUltraDist = obvZ < negThreeSigma

// -- 3.7 Regime state tracking via static variables --
// Tracks consecutive bars in each regime for context-aware alerting.

static lastRegime = 0
static accBars = 0
static distBars = 0

if (isAccumulation) {
    accBars = accBars + 1
    distBars = 0
    lastRegime = 1
} else if (isDistribution) {
    distBars = distBars + 1
    accBars = 0
    lastRegime = -1
} else {
    accBars = 0
    distBars = 0
    lastRegime = 0
}

// -- 3.8 Price-OBV divergence detection (stateful via static) --
// Regular divergence: price makes higher high / lower low, OBV disagrees.

static prevPxHigh = -1.0
static prevObvHigh = -1.0
static prevPxLow = -1.0
static prevObvLow = -1.0

var bearDiv = false
var bullDiv = false

if (prevPxHigh < 0) {
    prevPxHigh = bars.high[0]
    prevObvHigh = obvZ[0]
    prevPxLow = bars.low[0]
    prevObvLow = obvZ[0]
}

if (!isLiveUpdate) {
    // Bearish divergence: price higher high, OBV lower high
    var pxHigh = highest(source=bars.high, period=divLookback)
    var obvHigh = highest(source=obvZ, period=divLookback)
    if (bars.high[0] > prevPxHigh) {
        if (obvZ[0] < prevObvHigh) {
            bearDiv = true
        }
        prevPxHigh = bars.high[0]
        prevObvHigh = obvZ[0]
    }

    // Bullish divergence: price lower low, OBV higher low
    var pxLow = lowest(source=bars.low, period=divLookback)
    var obvLow = lowest(source=obvZ, period=divLookback)
    if (bars.low[0] < prevPxLow) {
        if (obvZ[0] > prevObvLow) {
            bullDiv = true
        }
        prevPxLow = bars.low[0]
        prevObvLow = obvZ[0]
    }
}

// ---------------------------------------------------------------------------
// 4. VISUALIZATION
// ---------------------------------------------------------------------------

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

// 4.2 Sigma band hlines
if (showSigma1) {
    hline(value=oneSigma, color=transparency(accColor, 50), width=1)
    hline(value=negOneSigma, color=transparency(distColor, 50), width=1)
}
if (showSigma2) {
    hline(value=twoSigma, color=transparency(accColor, 40), width=1)
    hline(value=negTwoSigma, color=transparency(distColor, 40), width=1)
}
if (showSigma3) {
    hline(value=threeSigma, color=transparency(accColor, 30), width=1)
    hline(value=negThreeSigma, color=transparency(distColor, 30), width=1)
}

// 4.3 Z-score line with regime color coding
var regimeColor = isAccumulation ? accColor : (isDistribution ? distColor : neutralColor)
plotLine(
    value=obvZ,
    width=2,
    colors=[regimeColor],
    label=["OBV Z-Score"],
    desc=["Rolling z-score of OBV; > +1σ accumulation, < −1σ distribution"]
)

// 4.4 Optional unsmoothed z-score
if (showZRaw) {
    plotLine(
        value=obvZRaw,
        width=1,
        colors=[transparency(neutralColor, 50)],
        label=["Z-Score (Raw)"],
        desc=["Unsmoothed z-score of rolling OBV"]
    )
}

// 4.5 Sigma fill areas (color-coded by regime)
if (showFill) {
    // Fill between z-score and zero line
    var fillColor = isAccumulation ? transparency(accColor, 70) : (isDistribution ? transparency(distColor, 70) : transparency(neutralColor, 80))
    plotLine(
        value=[obvZ, zeroLine],
        width=1,
        colors=[fillColor],
        fill=true,
        label=["Z-Score Fill"],
        desc=["Filled area between z-score and zero line, color-coded by regime"]
    )

    // ±1σ band fill
    plotLine(
        value=[oneSigma, negOneSigma],
        width=1,
        colors=[transparency(neutralColor, 85)],
        fill=true,
        label=["±1σ Band"],
        desc=["Normal range band (±1 standard deviation)"]
    )
}

// 4.6 Regime histogram (plotBar)
if (showRegime) {
    var histColorIdx = isAccumulation ? 0 : (isDistribution ? 1 : 2)
    plotBar(
        value=obvZ,
        colors=[accColor, distColor, neutralColor],
        colorIndex=histColorIdx,
        width=1,
        label=["OBV Regime"],
        desc=["Histogram of OBV z-score colored by regime"]
    )
}

// 4.7 Extreme z-score shape alerts
if (showShapes) {
    if (isUltraAccum) {
        plotShape(
            value=threeSigma,
            shape="triangleup",
            colorIndex=accColor,
            width=3,
            label=["Ultra Accumulation"],
            desc=["OBV Z-Score > +3σ: extreme accumulation; potential distribution zone ahead"]
        )
    }
    if (isUltraDist) {
        plotShape(
            value=negThreeSigma,
            shape="triangledown",
            colorIndex=distColor,
            width=3,
            label=["Ultra Distribution"],
            desc=["OBV Z-Score < −3σ: extreme distribution; potential accumulation zone ahead"]
        )
    }
    if (isExtremeAccum && !isUltraAccum) {
        plotShape(
            value=twoSigma,
            shape="circle",
            colorIndex=accColor,
            width=2,
            label=["Extreme Accum"],
            desc=["OBV Z-Score > +2σ: strong accumulation regime"]
        )
    }
    if (isExtremeDist && !isUltraDist) {
        plotShape(
            value=negTwoSigma,
            shape="circle",
            colorIndex=distColor,
            width=2,
            label=["Extreme Dist"],
            desc=["OBV Z-Score < −2σ: strong distribution regime"]
        )
    }
}

// 4.8 Price-OBV divergence shapes
if (showDivergence) {
    if (bullDiv) {
        plotShape(
            value=obvZ,
            shape="triangleup",
            colorIndex=accColor,
            width=2,
            label=["OBV Bull Div"],
            desc=["Bullish divergence: price lower low, OBV z-score higher low (buying pressure building)"]
        )
    }
    if (bearDiv) {
        plotShape(
            value=obvZ,
            shape="triangledown",
            colorIndex=distColor,
            width=2,
            label=["OBV Bear Div"],
            desc=["Bearish divergence: price higher high, OBV z-score lower high (selling pressure building)"]
        )
    }
}

// 4.9 Optional raw OBV line
if (showRawOBV) {
    plotLine(
        value=obvCum,
        width=1,
        colors=[obvColor],
        label=["Raw OBV"],
        desc=["True cumulative OBV from first bar (Granville 1963)"]
    )
}

// ---------------------------------------------------------------------------
// 5. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = isAccumulation ? "ACCUMULATION" : (isDistribution ? "DISTRIBUTION" : "NEUTRAL")
    var regimeTextColor = isAccumulation ? accColor : (isDistribution ? distColor : neutralColor)

    plotTable(
        data=[
            ["OBV Z-Score Pro", regimeText],
            ["Z-Score", obvZ[0]],
            ["Raw OBV", obvCum],
            ["Acc Bars", accBars],
            ["Dist Bars", distBars],
            ["Bull Div", bullDiv ? "YES" : "NO"],
            ["Bear Div", bearDiv ? "YES" : "NO"]
        ],
        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
    )
}