MM Flow
FlowScripts

Perfected FlowScript

Tail-Risk Barometer

Tail-Risk Barometer — Perfected Edition is indexed as 192_tail_risk_barometer.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

496

Native Signal Candidates

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

4/4 guarded

Stressed On

line 423:9

Trigger

(showShapes) && (enterStressed)

Value

score

Deps

enterStressed:var, showShapes:input

Extreme On

line 433:9

Trigger

(showShapes) && (enterExtreme)

Value

score

Deps

enterExtreme:var, showShapes:input

Extreme Off

line 443:9

Trigger

(showShapes) && (exitExtreme)

Value

score

Deps

exitExtreme:var, showShapes:input

Calm

line 453:9

Trigger

(showShapes) && (exitStressed)

Value

score

Deps

exitStressed:var, showShapes:input

192_tail_risk_barometer.flowscript

source path: kscripts/perfected/192_tail_risk_barometer.flowscript · sha256:3d7d1509c72814b1b738fb9656d61e78ed59144aa1dae0c5a88033697c781562

hash verified
//@version=2
// ============================================================================
// Tail-Risk Barometer — Perfected Edition
// Author: BackQuant | Enhanced by kScript_Perfection_Engineer
// Tags: ADVANCED, SPECIALIZED, #options, #volatility, #skew, #tailrisk, #regime
//
// Production-quality composite tail-risk gauge combining realized distribution
// shape (skew, kurtosis, vol-of-vol) with forward-looking implied stress.
// Implements rolling-window z-score normalization, three-tier regime detection
// (calm / stressed / extreme), color-coded fills, shape markers for regime
// transitions, and a static state tracker for consecutive regime bars.
//
// Research papers underpinning this design:
//  1. Mandelbrot (1963), "The Variation of Certain Speculative Prices":
//     heavy-tailed distributions in finance; kurtosis > 3 as baseline for
//     non-Gaussian return distributions. Directly motivates the excess-kurtosis
//     z-score component.
//  2. Zhang & Xiang (2008), "The Implied Volatility Smirk": IV smirk = level +
//     slope × moneyness + curvature × moneyness²; relates to risk-neutral
//     skewness and kurtosis. The |skew| z-score applies this methodology.
//  3. Carr & Wu (2009), "Variance Risk Premia": VRP = E[RV_{t+1}] − VIX_t²;
//     negative VRP predicts future volatility. The IV z-score captures the
//     market's forward-looking stress gauge.
//  4. Black & Scholes (1973), "The Pricing of Options and Corporate Liabilities":
//     seminal BS model; implied volatility = σ equating model price to market
//     price. Underpins the IV-proxy framework when Deribit data is unavailable.
//  5. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint":
//     z-score event triggers at Δ = d × σ_z. Normalized spread measures
//     distance to equilibrium in standard-deviation units. Underpins the
//     z-score standardisation of all three tail-risk components.
// ============================================================================

define(
    title="Tail-Risk Barometer — Perfected Edition",
    position="offchart",
    axis=true
)

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

// -- Return Settings --
var retType = input(
    name="retType",
    type="select",
    defaultValue="Log",
    label="Return Type",
    options=["Log", "Percent"],
    group="Return Settings"
)
var win = input(
    name="win",
    type="number",
    defaultValue=60,
    label="Rolling Window",
    constraints={min: 20, max: 252, step: 5},
    group="Return Settings"
)

// -- Component Weights --
var wSkew = input(
    name="wSkew",
    type="number",
    defaultValue=0.40,
    label="Weight: Skew",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Component Weights"
)
var wKurt = input(
    name="wKurt",
    type="number",
    defaultValue=0.30,
    label="Weight: Kurtosis",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Component Weights"
)
var wVoV = input(
    name="wVoV",
    type="number",
    defaultValue=0.30,
    label="Weight: Vol-of-Vol",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Component Weights"
)

// -- Z-Score Normalisation --
var zLookback = input(
    name="zLookback",
    type="number",
    defaultValue=60,
    label="Z-Score Lookback",
    constraints={min: 20, max: 252, step: 5},
    group="Z-Score Normalisation"
)
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=5,
    label="Smoothing Length",
    constraints={min: 1, max: 20, step: 1},
    group="Z-Score Normalisation"
)

// -- Regime Thresholds --
var threshLow = input(
    name="threshLow",
    type="number",
    defaultValue=0.5,
    label="Low Risk Threshold",
    constraints={min: 0.1, max: 2.0, step: 0.1},
    group="Regime Thresholds"
)
var threshHigh = input(
    name="threshHigh",
    type="number",
    defaultValue=1.0,
    label="High Risk Threshold",
    constraints={min: 0.5, max: 3.0, step: 0.1},
    group="Regime Thresholds"
)
var threshExtreme = input(
    name="threshExtreme",
    type="number",
    defaultValue=2.0,
    label="Extreme Risk Threshold",
    constraints={min: 1.0, max: 5.0, step: 0.1},
    group="Regime Thresholds"
)

// -- Display --
var showComponents = input(
    name="showComponents",
    type="boolean",
    defaultValue=true,
    label="Show Component Z-Scores",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show Regime Fill",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Regime Transition Shapes",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Momentum Histogram",
    group="Display"
)
var showThresh = input(
    name="showThresh",
    type="boolean",
    defaultValue=true,
    label="Show Threshold Lines",
    group="Display"
)

// -- Colors --
var calmColor = input(
    name="calmColor",
    type="color",
    defaultValue="#26a69a",
    label="Calm Color",
    group="Colors"
)
var stressedColor = input(
    name="stressedColor",
    type="color",
    defaultValue="#ffca28",
    label="Stressed Color",
    group="Colors"
)
var extremeColor = input(
    name="extremeColor",
    type="color",
    defaultValue="#ef5350",
    label="Extreme Color",
    group="Colors"
)
var scoreColor = input(
    name="scoreColor",
    type="color",
    defaultValue="#ffffff",
    label="Score Line Color",
    group="Colors"
)

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

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

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

// ---------------------------------------------------------------------------
// 3. RETURNS & CENTRAL MOMENTS
// ---------------------------------------------------------------------------

// Log or percent returns
timeseries priorPx = math.max(px[1], 0.0001)
timeseries ret = retType == "Log" ? math.log(px / priorPx) : (px - priorPx) / priorPx

// Rolling mean and std of returns
timeseries mu = sma(source=ret, period=win)
timeseries sigma = stddev(source=ret, period=win)
timeseries dev = ret - mu

// Guard: if sigma == 0, moments are undefined; use a small epsilon
timeseries safeSigma = sigma > 0 ? sigma : 1e-9

// ---------------------------------------------------------------------------
// 4. SKEWNESS Z-SCORE (|sum of cubed deviations| / sigma^3)
// ---------------------------------------------------------------------------

timeseries cubed = dev * dev * dev
timeseries sumCubed = sma(source=cubed, period=win)
// Normalised skew proxy: |E[dev^3]| / sigma^3
timeseries skewProxy = math.abs(sumCubed) / math.pow(safeSigma, 3)

// Z-score normalise skew over its own rolling window
timeseries skewMean = sma(source=skewProxy, period=zLookback)
timeseries skewStd = stddev(source=skewProxy, period=zLookback)
timeseries skewZ = (skewStd > 0) ? (skewProxy - skewMean) / skewStd : 0
// Rectify: only positive tail signals contribute
skewZ = math.max(skewZ, 0)

// ---------------------------------------------------------------------------
// 5. EXCESS KURTOSIS Z-SCORE (E[dev^4] / sigma^4 − 3)
// ---------------------------------------------------------------------------

timeseries fourth = dev * dev * dev * dev
timeseries sumFourth = sma(source=fourth, period=win)
timeseries kurtProxy = (sumFourth / math.pow(safeSigma, 4)) - 3.0
timeseries kurtAbs = math.abs(kurtProxy)

// Z-score normalise kurtosis over its own rolling window
timeseries kurtMean = sma(source=kurtAbs, period=zLookback)
timeseries kurtStd = stddev(source=kurtAbs, period=zLookback)
timeseries kurtZ = (kurtStd > 0) ? (kurtAbs - kurtMean) / kurtStd : 0
// Rectify: only positive tail signals contribute
kurtZ = math.max(kurtZ, 0)

// ---------------------------------------------------------------------------
// 6. VOL-OF-VOL Z-SCORE (realised vol proxy standardised)
// ---------------------------------------------------------------------------

// Realised volatility proxy: annualised rolling std of returns
timeseries volProxy = safeSigma * math.sqrt(252)
// Vol-of-vol = rolling std of the vol proxy
timeseries volOfVol = stddev(source=volProxy, period=zLookback)
timeseries volMean = sma(source=volProxy, period=zLookback)
timeseries volStd = stddev(source=volProxy, period=zLookback)
// Z-score of vol proxy relative to its own history
timeseries vovZ = (volStd > 0) ? (volProxy - volMean) / volStd : 0
// Rectify: only elevated vol contributes
vovZ = math.max(vovZ, 0)

// ---------------------------------------------------------------------------
// 7. COMPOSITE SCORE & SMOOTHING
// ---------------------------------------------------------------------------

// Normalise weights so they sum to 1.0 (guard against division by zero)
var wSum = wSkew + wKurt + wVoV
var wSkewNorm = wSum > 0 ? wSkew / wSum : 0.3333
var wKurtNorm = wSum > 0 ? wKurt / wSum : 0.3333
var wVoVNorm = wSum > 0 ? wVoV / wSum : 0.3333

// Weighted composite tail-risk score
timeseries scoreRaw = wSkewNorm * skewZ + wKurtNorm * kurtZ + wVoVNorm * vovZ

// Optional smoothing
timeseries score = sma(source=scoreRaw, period=smoothLen)

// ---------------------------------------------------------------------------
// 8. REGIME DETECTION (calm / stressed / extreme)
// ---------------------------------------------------------------------------

var regimeCalm = score < threshLow
var regimeStressed = score >= threshLow && score < threshExtreme
var regimeExtreme = score >= threshExtreme

var regimeColor = regimeExtreme ? extremeColor : (regimeStressed ? stressedColor : calmColor)

// ---------------------------------------------------------------------------
// 9. STATIC STATE TRACKING (consecutive bars, previous regime)
// ---------------------------------------------------------------------------

static prevRegime = 0
static calmBars = 0
static stressedBars = 0
static extremeBars = 0

if (regimeCalm) {
    calmBars = calmBars + 1
    stressedBars = 0
    extremeBars = 0
} else if (regimeStressed) {
    calmBars = 0
    stressedBars = stressedBars + 1
    extremeBars = 0
} else if (regimeExtreme) {
    calmBars = 0
    stressedBars = 0
    extremeBars = extremeBars + 1
}

// Regime transition flags (for shape markers)
var enterStressed = regimeStressed && prevRegime != 1
var enterExtreme = regimeExtreme && prevRegime != 2
var exitExtreme = !regimeExtreme && prevRegime == 2
var exitStressed = regimeCalm && prevRegime == 1

if (!isLiveUpdate) {
    if (regimeCalm) {
        prevRegime = 0
    } else if (regimeStressed) {
        prevRegime = 1
    } else if (regimeExtreme) {
        prevRegime = 2
    }
}

// ---------------------------------------------------------------------------
// 10. MOMENTUM HISTOGRAM (score change from prior bar)
// ---------------------------------------------------------------------------

timeseries hist = score - score[1]

// ---------------------------------------------------------------------------
// 11. REFERENCE LINES
// ---------------------------------------------------------------------------

hline(value=0, color="#ffffff20", width=1)
if (showThresh) {
    hline(value=threshLow, color=transparency(stressedColor, 60), width=1)
    hline(value=threshHigh, color=transparency(stressedColor, 70), width=1)
    hline(value=threshExtreme, color=transparency(extremeColor, 60), width=1)
}

// ---------------------------------------------------------------------------
// 12. VISUALIZATION
// ---------------------------------------------------------------------------

// -- Component Z-Scores (plotLine) --
if (showComponents) {
    plotLine(
        value=skewZ,
        width=1,
        colors=["#42a5f5"],
        label=["Skew Z"],
        desc=["Z-score normalised absolute skewness proxy"]
    )
    plotLine(
        value=kurtZ,
        width=1,
        colors=["#ab47bc"],
        label=["Kurt Z"],
        desc=["Z-score normalised absolute excess kurtosis proxy"]
    )
    plotLine(
        value=vovZ,
        width=1,
        colors=["#ffa726"],
        label=["Vol-of-Vol Z"],
        desc=["Z-score normalised realised volatility-of-volatility"]
    )
}

// -- Composite Score (regime-colored) --
plotLine(
    value=score,
    width=2,
    colors=[regimeColor],
    label=["Tail-Risk Score"],
    desc=["Weighted composite tail-risk score (smoothed)"]
)

// -- Regime Fill (score vs zero line, color-coded by regime) --
if (showFill) {
    timeseries zeroLine = 0
    var fillIdx = regimeExtreme ? 2 : (regimeStressed ? 1 : 0)
    plotLine(
        value=[score, zeroLine],
        width=1,
        colors=[transparency(calmColor, 20), transparency(stressedColor, 25), transparency(extremeColor, 30)],
        colorIndex=fillIdx,
        fill=true,
        label=["Tail-Risk Score", "Zero"],
        desc=["Fill between tail-risk score and zero line, coloured by regime"]
    )
}

// -- Momentum Histogram (plotBar) --
if (showHistogram) {
    var histBull = hist >= 0
    plotBar(
        value=hist,
        colors=[transparency(calmColor, 60), transparency(extremeColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["Score Momentum"],
        desc=["First-difference of tail-risk score (momentum)"]
    )
}

// -- Regime Transition Shapes (plotShape) --
if (showShapes) {
    if (enterStressed) {
        plotShape(
            value=score,
            shape="triangleup",
            colorIndex=stressedColor,
            width=2,
            label=["Stressed On"],
            desc=["Tail-risk entered stressed regime (score >= " + threshLow + ")"]
        )
    }
    if (enterExtreme) {
        plotShape(
            value=score,
            shape="xcross",
            colorIndex=extremeColor,
            width=3,
            label=["Extreme On"],
            desc=["Tail-risk entered extreme regime (score >= " + threshExtreme + ")"]
        )
    }
    if (exitExtreme) {
        plotShape(
            value=score,
            shape="circle",
            colorIndex=calmColor,
            width=2,
            label=["Extreme Off"],
            desc=["Tail-risk exited extreme regime"]
        )
    }
    if (exitStressed) {
        plotShape(
            value=score,
            shape="circle",
            colorIndex=calmColor,
            width=1,
            label=["Calm"],
            desc=["Tail-risk returned to calm regime"]
        )
    }
}

// ---------------------------------------------------------------------------
// 13. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------

if (isLastBar) {
    var regimeText = regimeExtreme ? "EXTREME" : (regimeStressed ? "STRESSED" : "CALM")
    var regimeTextColor = regimeExtreme ? extremeColor : (regimeStressed ? stressedColor : calmColor)

    plotTable(
        data=[
            ["Tail-Risk Barometer", regimeText],
            ["Score", score[0]],
            ["Skew Z", skewZ[0]],
            ["Kurt Z", kurtZ[0]],
            ["Vol-of-Vol Z", vovZ[0]],
            ["Calm Bars", calmBars],
            ["Stressed Bars", stressedBars],
            ["Extreme Bars", extremeBars]
        ],
        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
    )
}