MM Flow
FlowScripts

Perfected FlowScript

SCF Historical Volatility

SCF Historical Volatility — Perfected Edition is indexed as 110_scf_historical_volatility.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.7 KB

Lines

503

Native Signal Candidates

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

5/5 guarded

Z-Score High

line 416:9

Trigger

(showZScoreShapes && showZScore) && (zScoreExtremeHigh)

Value

zScore

Deps

showZScore:input, showZScoreShapes:input, zScoreExtremeHigh:var

Z-Score Low

line 426:9

Trigger

(showZScoreShapes && showZScore) && (zScoreExtremeLow)

Value

zScore

Deps

showZScore:input, showZScoreShapes:input, zScoreExtremeLow:var

Z-Score Normal

line 436:9

Trigger

(showZScoreShapes && showZScore) && (zScoreReturnNormal)

Value

zScore

Deps

showZScore:input, showZScoreShapes:input, zScoreReturnNormal:var

Vol Regime Up

line 450:9

Trigger

(showRegimeShapes && regimeChange) && (regimeChangeUp)

Value

annualizedVol

Deps

regimeChange:var, regimeChangeUp:var, showRegimeShapes:input

Vol Regime Down

line 460:9

Trigger

(showRegimeShapes && regimeChange) && (regimeChangeDown)

Value

annualizedVol

Deps

regimeChange:var, regimeChangeDown:var, showRegimeShapes:input

110_scf_historical_volatility.flowscript

source path: kscripts/perfected/110_scf_historical_volatility.flowscript · sha256:b1da2ad3205d87190f22b99ddab4f0651b6dbd5ce6072f707e05e091e24b51a0

hash verified
//@version=2
// ============================================================================
// SCF Historical Volatility — Perfected Edition
// Author: SoulzBTC (@SoulzBTC) | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, SPECIALIZED, #volatility, #historicalvolatility, #zscore, #regime
//
// Production-quality institutional-grade volatility measurement using
// logarithmic returns, z-score normalization, and dynamic regime detection.
// Implements the canonical Black-Scholes historical volatility estimator with
// annualization, rolling z-score standardization, and comprehensive
// histogram/fill/shape visualization.
//
// Research papers underpinning this design:
//  1. Black & Scholes (1973), "The Pricing of Options and Corporate Liabilities":
//     seminal option pricing model assumes constant volatility as key input.
//     Historical volatility σ = sqrt(252 × variance of log returns) is the
//     industry-standard estimator for this input.
//  2. Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes in
//     Supply and Demand": comprehensive review of market impact theory. Log-
//     return-based volatility calculation is the standard approach in this
//     literature for measuring price variability.
//  3. Heynen, Kemna & Vorst (1994), "Analysis of the Term Structure of
//     Implied Volatilities": documents mean-reversion in short-term IV.
//     Annualized historical volatility is the benchmark against which implied
//     volatility is compared.
//  4. Gatheral (2006), "The Volatility Surface: A Practitioner's Guide":
//     covers stochastic volatility, local volatility, and jump-diffusion.
//     Historical volatility is an essential input for volatility surface
//     calibration.
//  5. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint":
//     z-score normalization z_t = (x_t − μ) / σ measures distance to equilibrium
//     in units of standard deviations. Entry thresholds typically at ±1σ or ±2σ.
// ============================================================================

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

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

// --- Volatility Calculation ---
var returnLen = input(
    name="returnLen",
    type="number",
    defaultValue=1,
    label="Return Period",
    constraints={min: 1, max: 10, step: 1},
    group="Volatility Calculation"
)
var volLen = input(
    name="volLen",
    type="number",
    defaultValue=20,
    label="Volatility Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Volatility Calculation"
)
var useLog = input(
    name="useLog",
    type="boolean",
    defaultValue=true,
    label="Use Log Returns",
    group="Volatility Calculation"
)
var annualization = input(
    name="annualization",
    type="number",
    defaultValue=365,
    label="Annualization Factor (365=crypto, 252=equities)",
    constraints={min: 1, max: 1000, step: 1},
    group="Volatility Calculation"
)

// --- Smoothing ---
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=5,
    label="EMA Smoothing Length",
    constraints={min: 1, max: 50, step: 1},
    group="Smoothing"
)

// --- Z-Score ---
var showZScore = input(
    name="showZScore",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score",
    group="Z-Score"
)
var zScoreLookback = input(
    name="zScoreLookback",
    type="number",
    defaultValue=50,
    label="Z-Score Lookback",
    constraints={min: 10, max: 200, step: 1},
    group="Z-Score"
)
var zScoreThreshold = input(
    name="zScoreThreshold",
    type="number",
    defaultValue=2.0,
    label="Z-Score Extreme Threshold",
    constraints={min: 1.0, max: 4.0, step: 0.5},
    group="Z-Score"
)

// --- Regime Detection ---
var showRegimeBands = input(
    name="showRegimeBands",
    type="boolean",
    defaultValue=true,
    label="Show Regime Bands",
    group="Regime Detection"
)
var regimeLookback = input(
    name="regimeLookback",
    type="number",
    defaultValue=50,
    label="Regime Lookback",
    constraints={min: 10, max: 200, step: 1},
    group="Regime Detection"
)
var highVolSigmas = input(
    name="highVolSigmas",
    type="number",
    defaultValue=1.0,
    label="High Vol Regime (σ above mean)",
    constraints={min: 0.5, max: 3.0, step: 0.5},
    group="Regime Detection"
)
var lowVolSigmas = input(
    name="lowVolSigmas",
    type="number",
    defaultValue=1.0,
    label="Low Vol Regime (σ below mean)",
    constraints={min: 0.5, max: 3.0, step: 0.5},
    group="Regime Detection"
)

// --- Display ---
var showDaily = input(
    name="showDaily",
    type="boolean",
    defaultValue=true,
    label="Show Daily Volatility",
    group="Display"
)
var showAnnualized = input(
    name="showAnnualized",
    type="boolean",
    defaultValue=true,
    label="Show Annualized Volatility",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Color-Coded Histogram",
    group="Display"
)
var showZScoreShapes = input(
    name="showZScoreShapes",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Shape Alerts",
    group="Display"
)
var showRegimeShapes = input(
    name="showRegimeShapes",
    type="boolean",
    defaultValue=true,
    label="Show Regime Change Shapes",
    group="Display"
)

// --- Colors ---
var annualizedColor = input(
    name="annualizedColor",
    type="color",
    defaultValue="#2962ff",
    label="Annualized Vol Color",
    group="Colors"
)
var dailyColor = input(
    name="dailyColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Daily Vol Color",
    group="Colors"
)
var highVolColor = input(
    name="highVolColor",
    type="color",
    defaultValue="#ef5350",
    label="High Vol Regime Color",
    group="Colors"
)
var lowVolColor = input(
    name="lowVolColor",
    type="color",
    defaultValue="#00e676",
    label="Low Vol Regime Color",
    group="Colors"
)
var midVolColor = input(
    name="midVolColor",
    type="color",
    defaultValue="#ffca28",
    label="Mid Vol Regime Color",
    group="Colors"
)

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

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

// -----------------------------------------------------------------------------
// 3. HISTORICAL VOLATILITY (Black-Scholes 1973)
// -----------------------------------------------------------------------------
// Log returns: log(P_t / P_{t-1})
// Simple returns: (P_t − P_{t-1}) / P_{t-1}
// Annualized: σ_annual = σ_period × sqrt(periods_per_year)

timeseries priorClose = math.max(close[returnLen], 0.0001)
timeseries logRet = math.log(close / priorClose)
timeseries simpleRet = (close - priorClose) / priorClose
timeseries returns = useLog ? logRet : simpleRet

// Rolling standard deviation of returns
timeseries stdRet = stdev(source=returns, period=volLen)

// Daily volatility (per-period, not annualized)
timeseries dailyVol = stdRet

// Annualized: multiply by sqrt(periods per year / return period)
timeseries annualizedVol = dailyVol * math.sqrt(annualization / returnLen)

// Guard: if NaN from insufficient data, set to 0
if (isnan(dailyVol[0])) {
    dailyVol = 0
}
if (isnan(annualizedVol[0])) {
    annualizedVol = 0
}

// -----------------------------------------------------------------------------
// 4. SMOOTHING
// -----------------------------------------------------------------------------
timeseries dailySmooth = ema(source=dailyVol, period=smoothLen)
timeseries annualizedSmooth = ema(source=annualizedVol, period=smoothLen)

// -----------------------------------------------------------------------------
// 5. Z-SCORE NORMALIZATION (Zhao & Palomar 2018)
// -----------------------------------------------------------------------------
// z_t = (x_t − μ) / σ over rolling window
// Measures distance from equilibrium in standard deviation units

timeseries volMean = sma(source=annualizedVol, period=zScoreLookback)
timeseries volStd = stdev(source=annualizedVol, period=zScoreLookback)

timeseries zScore = volStd > 0 ? (annualizedVol - volMean) / volStd : 0

// Guard NaN
if (isnan(zScore[0])) {
    zScore = 0
}

// -----------------------------------------------------------------------------
// 6. REGIME DETECTION (static tracking)
// -----------------------------------------------------------------------------
// High volatility: annualizedVol > mean + highVolSigmas × σ
// Low volatility: annualizedVol < mean − lowVolSigmas × σ
// Medium volatility: everything else

timeseries regimeMean = sma(source=annualizedVol, period=regimeLookback)
timeseries regimeStd = stdev(source=annualizedVol, period=regimeLookback)

timeseries highRegime = regimeMean + highVolSigmas * regimeStd
timeseries lowRegime = math.max(0, regimeMean - lowVolSigmas * regimeStd)

var isHighVol = annualizedVol > highRegime
var isLowVol = annualizedVol < lowRegime
var isMidVol = !isHighVol && !isLowVol

// Regime color for histogram and lines
var volRegimeColor = isHighVol ? highVolColor : (isLowVol ? lowVolColor : midVolColor)

// Regime change detection (static tracking)
static prevRegime = 0  // 0=none, 1=low, 2=mid, 3=high
var regimeChange = false
var regimeChangeUp = false
var regimeChangeDown = false

var currentRegime = isHighVol ? 3 : (isLowVol ? 1 : 2)
if (prevRegime > 0 && prevRegime != currentRegime) {
    regimeChange = true
    regimeChangeUp = currentRegime > prevRegime  // low->mid, mid->high, low->high
    regimeChangeDown = currentRegime < prevRegime  // high->mid, mid->low, high->low
}
prevRegime = currentRegime

// -----------------------------------------------------------------------------
// 7. Z-SCORE EXTREME ALERTS
// -----------------------------------------------------------------------------
var zScoreExtremeHigh = zScore > zScoreThreshold && zScore[1] <= zScoreThreshold
var zScoreExtremeLow = zScore < -zScoreThreshold && zScore[1] >= -zScoreThreshold
var zScoreReturnNormal = (zScore[1] > zScoreThreshold || zScore[1] < -zScoreThreshold) && zScore <= zScoreThreshold && zScore >= -zScoreThreshold

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

// --- Daily Volatility ---
if (showDaily) {
    plotLine(
        value=dailyVol,
        width=1,
        colors=[dailyColor],
        label=["Daily Vol"],
        desc=["Daily per-period volatility (non-annualized)"]
    )
    plotLine(
        value=dailySmooth,
        width=2,
        colors=[dailyColor],
        label=["Daily Vol Smooth"],
        desc=["EMA-smoothed daily volatility (" + smoothLen + ")"]
    )
}

// --- Annualized Volatility ---
if (showAnnualized) {
    plotLine(
        value=annualizedVol,
        width=1,
        colors=[annualizedColor],
        label=["Annualized Vol"],
        desc=["Annualized historical volatility (" + annualization + " days)"]
    )
    plotLine(
        value=annualizedSmooth,
        width=2,
        colors=[annualizedColor],
        label=["Annualized Vol Smooth"],
        desc=["EMA-smoothed annualized volatility (" + smoothLen + ")"]
    )
}

// --- Regime Bands ---
if (showRegimeBands) {
    hline(value=0, color="#ffffff20", width=1)
    plotLine(
        value=regimeMean,
        width=1,
        colors=["#ffffff"],
        label=["Vol Mean"],
        desc=["Rolling mean of annualized volatility (" + regimeLookback + ")"]
    )
    plotLine(
        value=highRegime,
        width=1,
        colors=[highVolColor],
        label=["High Regime"],
        desc=["High volatility threshold: mean + " + highVolSigmas + "σ"]
    )
    plotLine(
        value=lowRegime,
        width=1,
        colors=[lowVolColor],
        label=["Low Regime"],
        desc=["Low volatility threshold: mean − " + lowVolSigmas + "σ"]
    )
}

// --- Color-Coded Volatility Histogram ---
if (showHistogram) {
    plotBar(
        value=annualizedVol,
        colors=[transparency(highVolColor, 60), transparency(midVolColor, 60), transparency(lowVolColor, 60)],
        colorIndex=isHighVol ? 0 : (isMidVol ? 1 : 2),
        width=1,
        label=["Vol Histogram"],
        desc=["Color-coded annualized volatility histogram (regime-based)"]
    )
}

// --- Z-Score Line ---
if (showZScore) {
    plotLine(
        value=zScore,
        width=2,
        colors=["#ff9800"],
        label=["Z-Score"],
        desc=["Z-score normalized annualized volatility (" + zScoreLookback + ")"]
    )
    hline(value=zScoreThreshold, color=transparency(highVolColor, 60), width=1)
    hline(value=-zScoreThreshold, color=transparency(lowVolColor, 60), width=1)
}

// --- Z-Score Extreme Shapes ---
if (showZScoreShapes && showZScore) {
    if (zScoreExtremeHigh) {
        plotShape(
            value=zScore,
            shape="triangledown",
            colorIndex=highVolColor,
            width=2,
            label=["Z-Score High"],
            desc=["Z-score crossed above +" + zScoreThreshold + " (extreme high vol)"]
        )
    }
    if (zScoreExtremeLow) {
        plotShape(
            value=zScore,
            shape="triangleup",
            colorIndex=lowVolColor,
            width=2,
            label=["Z-Score Low"],
            desc=["Z-score crossed below -" + zScoreThreshold + " (extreme low vol)"]
        )
    }
    if (zScoreReturnNormal) {
        plotShape(
            value=zScore,
            shape="circle",
            colorIndex=midVolColor,
            width=1,
            label=["Z-Score Normal"],
            desc=["Z-score returned to normal range (±" + zScoreThreshold + ")"]
        )
    }
}

// --- Regime Change Shapes ---
if (showRegimeShapes && regimeChange) {
    if (regimeChangeUp) {
        plotShape(
            value=annualizedVol,
            shape="arrowup",
            colorIndex=highVolColor,
            width=2,
            label=["Vol Regime Up"],
            desc=["Volatility regime shifted up (increasing vol)"]
        )
    }
    if (regimeChangeDown) {
        plotShape(
            value=annualizedVol,
            shape="arrowdown",
            colorIndex=lowVolColor,
            width=2,
            label=["Vol Regime Down"],
            desc=["Volatility regime shifted down (decreasing vol)"]
        )
    }
}

// -----------------------------------------------------------------------------
// 9. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = isHighVol ? "HIGH VOL" : (isLowVol ? "LOW VOL" : "MID VOL")
    var regimeTextColor = isHighVol ? highVolColor : (isLowVol ? lowVolColor : midVolColor)
    var retLabel = useLog ? "Log Returns" : "Simple Returns"

    plotTable(
        data=[
            ["Hist Vol — Perfected", regimeText],
            ["Annualized Vol", annualizedVol[0]],
            ["Daily Vol", dailyVol[0]],
            ["Z-Score", zScore[0]],
            ["Vol Mean", regimeMean[0]],
            ["High Regime", highRegime[0]],
            ["Low Regime", lowRegime[0]],
            [retLabel, "P=" + returnLen]
        ],
        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
    )
}