Historical Volatility Compression

Intuit · study · 304 行 · 点赞 10 · TradingView 原页

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

Pine Script

//@version=6
indicator("Historical Volatility Compression", shorttitle="VolCmp", overlay=false, precision=2)
 
// ============================================================================
// INPUTS
// ============================================================================
 
string groupCalc = "Compression"
int periodDays = input.int(30, "Compression Period (Daily Bars)", minval=5, maxval=365, group=groupCalc, tooltip="Lookback used for realized volatility and the total high-low range.")
int minSamples = input.int(365, "Minimum Historical Samples", minval=60, maxval=5000, group=groupCalc, tooltip="The expanding percentile remains hidden until this many valid daily observations exist.")
float rvWeightPct = input.float(40.0, "Realized Volatility Weight %", minval=0.0, maxval=100.0, step=5.0, group=groupCalc, tooltip="The remaining weight is assigned to total-range compression. 40/60 emphasizes prolonged range constriction.")
int annualizationDays = input.int(365, "Annualization Days", minval=1, maxval=365, group=groupCalc, tooltip="Use 365 for crypto. 252 is commonly used for weekday-only markets.")
bool confirmedOnly = input.bool(false, "Completed Daily Bars Only", group=groupCalc, tooltip="When enabled, all calculations use the previous completed daily bar. This removes intraday changes in the current daily observation at the cost of a one-day lag.")
 
string groupDisplay = "Display"
bool showRVComponent = input.bool(false, "Show RV Compression", group=groupDisplay)
bool showRangeComponent = input.bool(false, "Show Range Compression", group=groupDisplay)
bool showPersistence = input.bool(false, "Show Persistence Score", group=groupDisplay)
bool showBackground = input.bool(true, "Highlight Extreme Regimes", group=groupDisplay)
bool showDashboard = input.bool(true, "Show Dashboard", group=groupDisplay)
 
// ============================================================================
// HELPERS
// ============================================================================
 
f_appendRank(array<float> history, float value, int minimumSamples) =>
    float rank = na
    int samples = array.size(history)
    if not na(value)
        array.push(history, value)
        samples := array.size(history)
        if samples >= minimumSamples
            rank := array.percentrank(history, samples - 1)
    [rank, samples]
 
f_signed(float value) =>
    string result = "N/A"
    if not na(value)
        string sign = value > 0.0 ? "+" : ""
        result := sign + str.tostring(value, "0.00")
    result
 
// ============================================================================
// DAILY COMPRESSION ENGINE
// ============================================================================
 
f_metrics() =>
    float c0 = confirmedOnly ? close[1] : close
    float c1 = confirmedOnly ? close[2] : close[1]
    float h0 = confirmedOnly ? high[1] : high
    float l0 = confirmedOnly ? low[1] : low
 
    float logReturn = c0 > 0.0 and c1 > 0.0 ? math.log(c0 / c1) : na
    float realizedVol = ta.stdev(logReturn, periodDays, false) * math.sqrt(annualizationDays) * 100.0
 
    float rangeHigh = ta.highest(h0, periodDays)
    float rangeLow = ta.lowest(l0, periodDays)
    float rangeMid = (rangeHigh + rangeLow) / 2.0
    float rangeWidth = not na(rangeMid) and rangeMid != 0.0 ? ((rangeHigh - rangeLow) / rangeMid) * 100.0 : na
 
    float rvWeight = rvWeightPct / 100.0
    float rangeWeight = 1.0 - rvWeight
    float rawCompression = na
    if not na(realizedVol) and not na(rangeWidth)
        float safeRV = math.max(realizedVol, 0.000001)
        float safeRange = math.max(rangeWidth, 0.000001)
        rawCompression := -(rvWeight * math.log(safeRV) + rangeWeight * math.log(safeRange))
 
    var array<float> rvHistory = array.new_float(0)
    var array<float> rangeHistory = array.new_float(0)
    var array<float> compositeHistory = array.new_float(0)
 
    [rvRank, rvSamples] = f_appendRank(rvHistory, realizedVol, minSamples)
    [rangeRank, rangeSamples] = f_appendRank(rangeHistory, rangeWidth, minSamples)
    [compressionPct, sampleCount] = f_appendRank(compositeHistory, rawCompression, minSamples)
 
    float rvCompression = na(rvRank) ? na : 100.0 - rvRank
    float rangeCompression = na(rangeRank) ? na : 100.0 - rangeRank
    float pctChange1D = compressionPct - compressionPct[1]
    float pctChange7D = compressionPct - compressionPct[7]
 
    var int streak90 = 0
    var int streak95 = 0
    var int streak99 = 0
    if na(compressionPct)
        streak90 := 0
        streak95 := 0
        streak99 := 0
    else
        streak90 := compressionPct >= 90.0 ? streak90 + 1 : 0
        streak95 := compressionPct >= 95.0 ? streak95 + 1 : 0
        streak99 := compressionPct >= 99.0 ? streak99 + 1 : 0
 
    var int maxStreak90 = 0
    var int maxStreak95 = 0
    var int maxStreak99 = 0
    maxStreak90 := math.max(maxStreak90, streak90)
    maxStreak95 := math.max(maxStreak95, streak95)
    maxStreak99 := math.max(maxStreak99, streak99)
 
    float persistenceScore = maxStreak90 > 0 ? math.min(100.0, 100.0 * streak90 / maxStreak90) : 0.0
 
    int observationTime = confirmedOnly ? time[1] : time
    [realizedVol, rangeWidth, rvCompression, rangeCompression, rawCompression, compressionPct, pctChange1D, pctChange7D, sampleCount, streak90, streak95, streak99, maxStreak90, maxStreak95, maxStreak99, persistenceScore, observationTime]
 
// ============================================================================
// REQUEST DAILY CALCULATIONS
// ============================================================================
 
// Completed mode uses only prior daily OHLC above, so it can safely deliver the
// result at the start of the next daily period. Live mode must keep lookahead_off.
// Preserve the existing last-intrabar selection on charts above daily.
bool alignConfirmedDaily = confirmedOnly and timeframe.in_seconds() < timeframe.in_seconds("1D")
[dRV, dRange, dRVCompression, dRangeCompression, dRawCompression, dCompressionPct, dPctChange1D, dPctChange7D, dSampleCount, dStreak90, dStreak95, dStreak99, dMaxStreak90, dMaxStreak95, dMaxStreak99, dPersistenceScore, dObservationTime] = request.security(syminfo.tickerid, "1D", f_metrics(), gaps=barmerge.gaps_off, lookahead=alignConfirmedDaily ? barmerge.lookahead_on : barmerge.lookahead_off)
 
// ============================================================================
// REGIMES
// ============================================================================
 
bool valid = not na(dCompressionPct)
 
string magnitudeRegime = "WARMUP"
if valid
    if dCompressionPct >= 99.0
        magnitudeRegime := "TOP 1%"
    else if dCompressionPct >= 95.0
        magnitudeRegime := "TOP 5%"
    else if dCompressionPct >= 90.0
        magnitudeRegime := "TOP 10%"
    else if dCompressionPct >= 75.0
        magnitudeRegime := "HIGH"
    else if dCompressionPct >= 25.0
        magnitudeRegime := "NORMAL"
    else
        magnitudeRegime := "EXPANDED"
 
string durationRegime = "NONE"
if valid and dStreak90 > 0
    if dPersistenceScore >= 100.0
        durationRegime := "RECORD"
    else if dPersistenceScore >= 75.0
        durationRegime := "VERY LONG"
    else if dPersistenceScore >= 40.0
        durationRegime := "PROLONGED"
    else
        durationRegime := "EARLY"
 
string changeRegime = "STABLE"
if valid and not na(dPctChange1D)
    if dPctChange1D <= -10.0 or dPctChange7D <= -20.0
        changeRegime := "SHARP RELEASE"
    else if dPctChange1D <= -5.0 or dPctChange7D <= -10.0
        changeRegime := "RELEASING"
    else if dPctChange1D >= 10.0 or dPctChange7D >= 20.0
        changeRegime := "SHARP COMPRESSION"
    else if dPctChange1D >= 5.0 or dPctChange7D >= 10.0
        changeRegime := "COMPRESSING"
 
string compressionState = magnitudeRegime
if valid and dCompressionPct >= 95.0 and dStreak90 >= 14
    compressionState := "EXTREME + PERSISTENT"
else if valid and dCompressionPct >= 90.0 and dStreak90 >= 14
    compressionState := "PERSISTENT"
else if valid and dPctChange1D <= -10.0
    compressionState := "VOL EXPANSION WATCH"
 
// ============================================================================
// COLORS AND PLOTS
// ============================================================================
 
color mainColor = color.blue
if valid
    if dCompressionPct >= 99.0
        mainColor := color.fuchsia
    else if dCompressionPct >= 95.0
        mainColor := color.red
    else if dCompressionPct >= 90.0
        mainColor := color.orange
    else if dCompressionPct >= 75.0
        mainColor := color.yellow
    else if dCompressionPct >= 25.0
        mainColor := color.aqua
 
color backgroundColor = na
if showBackground and valid
    if dCompressionPct >= 99.0
        backgroundColor := color.new(color.fuchsia, 90)
    else if dCompressionPct >= 95.0
        backgroundColor := color.new(color.red, 94)
    else if dCompressionPct >= 90.0
        backgroundColor := color.new(color.orange, 96)
 
plot(dCompressionPct, title="Historical Compression Percentile", color=mainColor, linewidth=3)
plot(showRVComponent ? dRVCompression : na, title="RV Compression Percentile", color=color.new(color.blue, 45), linewidth=1)
plot(showRangeComponent ? dRangeCompression : na, title="Range Compression Percentile", color=color.new(color.gray, 35), linewidth=1)
plot(showPersistence ? dPersistenceScore : na, title="Persistence Score", color=chart.fg_color, linewidth=1)
plot(dRawCompression, title="Raw Compression Composite", display=display.data_window)
 
hline(50.0, "Median", color=color.new(color.gray, 80), linestyle=hline.style_dotted)
hline(90.0, "Top 10%", color=color.new(color.orange, 60), linestyle=hline.style_dashed)
hline(95.0, "Top 5%", color=color.new(color.red, 50), linestyle=hline.style_dashed)
hline(99.0, "Top 1%", color=color.new(color.fuchsia, 35), linestyle=hline.style_dashed)
bgcolor(backgroundColor)
 
// ============================================================================
// COMPACT DASHBOARD
// ============================================================================
 
string currentPctText = na(dCompressionPct) ? "N/A" : str.tostring(dCompressionPct, "0.00") + "%"
string rangeCompText = na(dRangeCompression) ? "N/A" : str.tostring(dRangeCompression, "0.00") + "%"
string rvCompText = na(dRVCompression) ? "N/A" : str.tostring(dRVCompression, "0.00") + "%"
string rvText = na(dRV) ? "N/A" : str.tostring(dRV, "0.00") + "%"
string rangeText = na(dRange) ? "N/A" : str.tostring(dRange, "0.00") + "%"
string changeText = f_signed(dPctChange1D) + " / " + f_signed(dPctChange7D)
string dataText = (confirmedOnly ? "CLOSED DAILY" : "LIVE DAILY") + " • " + str.tostring(dSampleCount) + " obs"
 
color stateBg = color.new(color.gray, 85)
if valid
    if dCompressionPct >= 99.0
        stateBg := color.new(color.fuchsia, 72)
    else if dCompressionPct >= 95.0
        stateBg := color.new(color.red, 78)
    else if dCompressionPct >= 90.0
        stateBg := color.new(color.orange, 78)
 
var table dashboard = table.new(position.top_right, 3, 11, border_width=1)
 
if barstate.islast
    if showDashboard
        table.cell(dashboard, 0, 0, "VOL COMPRESSION", bgcolor=color.new(color.gray, 80), text_color=chart.fg_color)
        table.cell(dashboard, 1, 0, currentPctText, bgcolor=stateBg, text_color=chart.fg_color)
        table.cell(dashboard, 2, 0, compressionState, bgcolor=stateBg, text_color=chart.fg_color)
 
        table.cell(dashboard, 0, 1, "Range Compression")
        table.cell(dashboard, 1, 1, rangeCompText)
        table.cell(dashboard, 2, 1, dRangeCompression >= 99.0 ? "TOP 1%" : dRangeCompression >= 95.0 ? "TOP 5%" : dRangeCompression >= 90.0 ? "TOP 10%" : "")
 
        table.cell(dashboard, 0, 2, "RV Compression")
        table.cell(dashboard, 1, 2, rvCompText)
        table.cell(dashboard, 2, 2, dRVCompression >= 99.0 ? "TOP 1%" : dRVCompression >= 95.0 ? "TOP 5%" : dRVCompression >= 90.0 ? "TOP 10%" : "")
 
        table.cell(dashboard, 0, 3, str.tostring(periodDays) + "D Realized Vol")
        table.cell(dashboard, 1, 3, rvText)
        table.cell(dashboard, 2, 3, "")
 
        table.cell(dashboard, 0, 4, str.tostring(periodDays) + "D Total Range")
        table.cell(dashboard, 1, 4, rangeText)
        table.cell(dashboard, 2, 4, "")
 
        table.cell(dashboard, 0, 5, ">=99% Streak")
        table.cell(dashboard, 1, 5, str.tostring(dStreak99) + "d")
        table.cell(dashboard, 2, 5, "max " + str.tostring(dMaxStreak99) + "d")
 
        table.cell(dashboard, 0, 6, ">=95% Streak")
        table.cell(dashboard, 1, 6, str.tostring(dStreak95) + "d")
        table.cell(dashboard, 2, 6, "max " + str.tostring(dMaxStreak95) + "d")
 
        table.cell(dashboard, 0, 7, ">=90% Streak")
        table.cell(dashboard, 1, 7, str.tostring(dStreak90) + "d")
        table.cell(dashboard, 2, 7, "max " + str.tostring(dMaxStreak90) + "d")
 
        table.cell(dashboard, 0, 8, "Persistence")
        table.cell(dashboard, 1, 8, str.tostring(dPersistenceScore, "0.0") + "%")
        table.cell(dashboard, 2, 8, durationRegime)
 
        table.cell(dashboard, 0, 9, "1D / 7D Change")
        table.cell(dashboard, 1, 9, changeText)
        table.cell(dashboard, 2, 9, changeRegime)
 
        table.cell(dashboard, 0, 10, "Data")
        table.cell(dashboard, 1, 10, dataText)
        table.cell(dashboard, 2, 10, "")
    else
        table.clear(dashboard, 0, 0, 2, 10)
 
// ============================================================================
// ALERTS
// ============================================================================
 
// Evaluate at chart-bar close. In live mode, daily data can still change after
// an intraday chart bar closes. Require a valid previous value after warmup.
bool alertReady = barstate.isconfirmed and valid and not na(dCompressionPct[1])
bool enter90 = alertReady and dCompressionPct >= 90.0 and dCompressionPct[1] < 90.0
bool enter95 = alertReady and dCompressionPct >= 95.0 and dCompressionPct[1] < 95.0
bool enter99 = alertReady and dCompressionPct >= 99.0 and dCompressionPct[1] < 99.0
bool exit99 = alertReady and dCompressionPct < 99.0 and dCompressionPct[1] >= 99.0
bool exit95 = alertReady and dCompressionPct < 95.0 and dCompressionPct[1] >= 95.0
bool exit90 = alertReady and dCompressionPct < 90.0 and dCompressionPct[1] >= 90.0
 
// Commit the latch only at chart-bar close, avoiding intrabar rollback issues.
// Key it to the requested observation, not the chart date (gaps_off can carry
// yesterday's value forward). A new qualifying daily observation may alert again.
var int lastSharpReleaseObservation = na
bool sharpReleaseEvent = barstate.isconfirmed and valid and not na(dObservationTime) and dPctChange1D <= -10.0 and (na(lastSharpReleaseObservation) or dObservationTime != lastSharpReleaseObservation)
if sharpReleaseEvent
    lastSharpReleaseObservation := dObservationTime
 
alertcondition(enter90, title="Compression Top 10%", message="Volatility compression entered the historical top 10%.")
alertcondition(enter95, title="Compression Top 5%", message="Volatility compression entered the historical top 5%.")
alertcondition(enter99, title="Compression Top 1%", message="Volatility compression entered the historical top 1%.")
alertcondition(exit99, title="Top 1% Compression Release", message="Volatility compression fell below the historical top 1%.")
alertcondition(exit95, title="Top 5% Compression Release", message="Volatility compression fell below the historical top 5%.")
alertcondition(exit90, title="Major Compression Release", message="Volatility compression fell below the historical top 10%.")
alertcondition(sharpReleaseEvent, title="Sharp Compression Release", message="Historical compression percentile fell by at least 10 percentile points in one daily observation. One event per daily observation.")

← 返回列表