Volatility Regime Meter [Holtermorter99]

Holtermorter99 · study · 157 行 · 点赞 11 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Holtermorter99
//
// Volatility Regime Meter — realized volatility ranked against its own history (percentile), with contraction /
// normal / expansion regimes and hysteresis, and statistics of the chart itself: how long each regime lasts and
// how volatility over the next N bars compared with the volatility at each bar, per regime. Regimes change on
// closed bars only.
 
//@version=6
indicator("Volatility Regime Meter [Holtermorter99]", "VRM", overlay = false, precision = 1)
 
// ─────────────────────────────── Inputs ───────────────────────────────
const string G_VOL  = "Volatility"
const string G_REG  = "Regimes"
const string G_STAT = "Statistics"
const string G_DISP = "Display"
const string G_COL  = "Colors"
 
int volLength  = input.int(20, "Volatility Length (bars)", minval = 5, maxval = 200, group = G_VOL, tooltip = "Realized volatility: standard deviation of the last N close-to-close log returns.")
int rankLength = input.int(252, "Percentile Lookback (bars)", minval = 50, maxval = 2000, group = G_VOL, tooltip = "The current volatility is ranked within a window of this many volatility values, the current one included (0 = lowest, 100 = highest).")
 
int expEnter = input.int(80, "Expansion: enter at or above", minval = 51, maxval = 99, group = G_REG)
int expExit  = input.int(60, "Expansion: exit below", minval = 50, maxval = 98, group = G_REG, tooltip = "Hysteresis: the regime starts when the percentile reaches the first value and ends only when it falls below the second.")
int conEnter = input.int(20, "Contraction: enter at or below", minval = 1, maxval = 49, group = G_REG)
int conExit  = input.int(40, "Contraction: exit above", minval = 2, maxval = 50, group = G_REG)
 
int horizon = input.int(20, "Forward Horizon (bars)", minval = 5, maxval = 200, group = G_STAT, tooltip = "For every bar, the volatility of the next N bars is compared with the volatility at that bar. Each bar is counted once those N bars have closed.")
 
bool   showBg        = input.bool(true, "Color Background by Regime", group = G_DISP)
bool   showDashboard = input.bool(true, "Show Dashboard", group = G_DISP)
string dashPosInput  = input.string("Top Right", "Dashboard Position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], inline = "dash", group = G_DISP)
string dashSizeInput = input.string("Small", "", options = ["Tiny", "Small", "Normal"], inline = "dash", group = G_DISP)
 
color expColor = input.color(#EF5350, "Expansion", group = G_COL)
color norColor = input.color(#787B86, "Normal", group = G_COL)
color conColor = input.color(#26A69A, "Contraction", group = G_COL)
 
if expExit >= expEnter or conExit <= conEnter or conExit >= expExit
    runtime.error("VRM: thresholds must satisfy contraction enter < contraction exit < expansion exit < expansion enter.")
 
// ─────────────────────────────── Volatility and regime ───────────────────────────────
// Standard candles only: Heikin Ashi, Renko and other chart types have synthetic closes.
float ret = chart.is_standard ? math.log(close / close[1]) : na
float vol = ta.stdev(ret, volLength)
float pctRank = ta.percentrank(vol, rankLength)
 
// Regime: 1 expansion, -1 contraction, 0 normal. Transitions are committed on closed bars only, so on the
// real-time bar the regime shown is the one of the last closed bar.
var int regime = 0
var int runLen = 0
// Completed runs: count and total length per regime (index 0 contraction, 1 normal, 2 expansion).
var array<int> runCount = array.new<int>(3, 0)
var array<int> runBars  = array.new<int>(3, 0)
var array<int> barsIn   = array.new<int>(3, 0)
var bool started = false
var bool firstRun = true   // the first run is cut by the start of the history: not counted
 
int prevRegime = regime
if barstate.isconfirmed and not na(pctRank)
    int nxt = regime
    if regime == 1
        nxt := pctRank < expExit ? (pctRank <= conEnter ? -1 : 0) : 1
    else if regime == -1
        nxt := pctRank > conExit ? (pctRank >= expEnter ? 1 : 0) : -1
    else
        nxt := pctRank >= expEnter ? 1 : pctRank <= conEnter ? -1 : 0
    if started and nxt != regime
        // A run ends and is counted (except the first one).
        if not firstRun
            runCount.set(regime + 1, runCount.get(regime + 1) + 1)
            runBars.set(regime + 1, runBars.get(regime + 1) + runLen)
        firstRun := false
        runLen := 0
    if not started
        started := true
        runLen := 0
    regime := nxt
    runLen += 1
    barsIn.set(regime + 1, barsIn.get(regime + 1) + 1)
 
bool changed = barstate.isconfirmed and started and regime != prevRegime and not na(pctRank[1])
 
// ─────────────────────────────── Forward-volatility statistics ───────────────────────────────
// At bar t the volatility of bars t-horizon+1..t is the "next N bars" volatility of bar t-horizon: compare it
// with the volatility at t-horizon, grouped by the regime at t-horizon. No future data is used.
var array<float> fwdSum = array.new<float>(3, 0.0)
var array<int>   fwdCnt = array.new<int>(3, 0)
var array<int>   fwdUp  = array.new<int>(3, 0)
float fwdVol = ta.stdev(ret, horizon)
var array<int> regHist = array.new<int>()
if barstate.isconfirmed
    regHist.push(na(pctRank) ? 9 : regime)
    if regHist.size() > horizon + 1
        regHist.shift()
    if regHist.size() == horizon + 1
        int r0 = regHist.get(0)
        float v0 = vol[horizon]
        if r0 != 9 and not na(v0) and v0 > 0 and not na(fwdVol)
            float ratio = fwdVol / v0
            fwdSum.set(r0 + 1, fwdSum.get(r0 + 1) + ratio)
            fwdCnt.set(r0 + 1, fwdCnt.get(r0 + 1) + 1)
            fwdUp.set(r0 + 1, fwdUp.get(r0 + 1) + (ratio > 1 ? 1 : 0))
 
// ─────────────────────────────── Plots ───────────────────────────────
color regColor = regime == 1 ? expColor : regime == -1 ? conColor : norColor
plot(pctRank, "Volatility Percentile", color = regColor, linewidth = 2)
hline(expEnter, "Expansion Enter", color = color.new(expColor, 50), linestyle = hline.style_dashed)
hline(expExit, "Expansion Exit", color = color.new(expColor, 80), linestyle = hline.style_dotted)
hline(conExit, "Contraction Exit", color = color.new(conColor, 80), linestyle = hline.style_dotted)
hline(conEnter, "Contraction Enter", color = color.new(conColor, 50), linestyle = hline.style_dashed)
bgcolor(showBg and regime != 0 ? color.new(regColor, 90) : na, title = "Regime Background")
 
plot(vol * 100, "Realized Volatility % (per bar)", display = display.data_window)
plot(regime, "Regime (1 exp, 0 normal, -1 contr)", display = display.data_window)
 
alertcondition(changed and regime == 1, "Expansion started", "VRM: volatility expansion regime started on {{ticker}}")
alertcondition(changed and regime == -1, "Contraction started", "VRM: volatility contraction regime started on {{ticker}}")
alertcondition(changed and regime == 0, "Back to normal", "VRM: volatility back to the normal regime on {{ticker}}")
if changed
    alert("VRM: " + (regime == 1 ? "expansion" : regime == -1 ? "contraction" : "normal") + " regime started on " + syminfo.ticker + " (percentile " + str.tostring(pctRank, "#") + ")", alert.freq_once_per_bar_close)
 
// ─────────────────────────────── Dashboard ───────────────────────────────
dashPosition(string p) =>
    switch p
        "Top Left"     => position.top_left
        "Bottom Right" => position.bottom_right
        "Bottom Left"  => position.bottom_left
        => position.top_right
 
var table dash = na
string dashSize = dashSizeInput == "Tiny" ? size.tiny : dashSizeInput == "Normal" ? size.normal : size.small
 
if barstate.islast
    table.delete(dash)
    dash := na
    if showDashboard
        dash := table.new(dashPosition(dashPosInput), 4, 5, bgcolor = color.new(chart.bg_color, 10), frame_color = color.new(chart.fg_color, 80), frame_width = 1, border_color = color.new(chart.fg_color, 90), border_width = 1)
        color dim = color.new(chart.fg_color, 30)
        string now = regime == 1 ? "Expansion" : regime == -1 ? "Contraction" : "Normal"
        table.cell(dash, 0, 0, "VRM", text_color = chart.fg_color, text_size = dashSize, text_halign = text.align_left)
        table.cell(dash, 1, 0, not chart.is_standard ? "use standard candles" : now + (na(pctRank) ? "" : " · p" + str.tostring(pctRank, "#")), text_color = chart.is_standard ? regColor : expColor, text_size = dashSize)
        table.merge_cells(dash, 1, 0, 3, 0)
        table.cell(dash, 0, 1, "Regime", text_color = dim, text_size = dashSize, text_halign = text.align_left)
        table.cell(dash, 1, 1, "Time in", text_color = dim, text_size = dashSize, tooltip = "Share of closed bars spent in the regime")
        table.cell(dash, 2, 1, "Avg run", text_color = dim, text_size = dashSize, tooltip = "Average length in bars of completed runs of the regime (n runs)")
        table.cell(dash, 3, 1, "Next " + str.tostring(horizon) + " vol", text_color = dim, text_size = dashSize, tooltip = "Average ratio: volatility of the next " + str.tostring(horizon) + " bars ÷ volatility at the bar, for bars in the regime; and share of those bars where it was higher (n bars)")
        int totalBars = barsIn.get(0) + barsIn.get(1) + barsIn.get(2)
        for i = 0 to 2
            int k = 2 - i
            string name = k == 2 ? "Expansion" : k == 0 ? "Contraction" : "Normal"
            color c = k == 2 ? expColor : k == 0 ? conColor : norColor
            int rc = runCount.get(k)
            int fc = fwdCnt.get(k)
            table.cell(dash, 0, i + 2, name, text_color = c, text_size = dashSize, text_halign = text.align_left)
            table.cell(dash, 1, i + 2, totalBars > 0 ? str.tostring(100.0 * barsIn.get(k) / totalBars, "#") + "%" : "—", text_color = chart.fg_color, text_size = dashSize)
            table.cell(dash, 2, i + 2, rc > 0 ? str.tostring(1.0 * runBars.get(k) / rc, "#") + " (n=" + str.tostring(rc) + ")" : "—", text_color = chart.fg_color, text_size = dashSize)
            table.cell(dash, 3, i + 2, fc > 0 ? str.tostring(fwdSum.get(k) / fc, "0.00") + "× · ↑" + str.tostring(100.0 * fwdUp.get(k) / fc, "#") + "% (n=" + str.tostring(fc) + ")" : "—", text_color = chart.fg_color, text_size = dashSize)

← 返回列表