Volatility Term-Structure Concordance [RC Tools]

RC-Tools · study · 258 行 · 点赞 6 · 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/
// © RAC97
 
//@version=6
indicator("Volatility Term-Structure Concordance [RC Tools]", shorttitle="RCT Vol Term Conc", overlay=false, precision=2)
 
// ─────────────────────────────────────────────────────────────────────────────
// ABOUT
// ─────────────────────────────────────────────────────────────────────────────
// Measures the SHAPE of realised volatility across lookback windows, rather
// than its level. Realised volatility is computed over a ladder of
// increasing windows (short to long). If short-window volatility sits above
// every longer window, volatility is expanding across the board (an
// "inverted" term structure). If it sits below every longer window,
// volatility is compressed relative to its own longer-run history (a
// "normal" term structure). A tangled ladder scores near zero.
//
// Built from rank concordance (the Kendall's-tau family of pairwise
// agreement measures), a public, decades-old statistical concept, and
// standard realised volatility (standard deviation of log returns).
// Independent implementation. Not derived from, or related in code to, any
// other author's published script.
//
// This is a volatility-STRUCTURE tool, not a directional one. It says
// nothing about whether price will rise or fall.
//
// The concordance score and its band classification update ONLY on confirmed
// bar close, so nothing here repaints.
// ─────────────────────────────────────────────────────────────────────────────
 
 
// ─────────────────────────────────────────────────────────────────────────────
// INPUTS
// ─────────────────────────────────────────────────────────────────────────────
 
// ── Volatility Ladder ─────────────────────────────────────────────────────────
float  source     = input.source(close, "Source", group="Volatility Ladder",
     tooltip="Realised volatility is the standard deviation of log returns of this source.")
int    baseLen    = input.int(10, "Shortest Window", minval=2, group="Volatility Ladder",
     tooltip="Lookback (bars) of the shortest volatility window in the ladder.")
float  growth     = input.float(1.6, "Window Growth Factor", minval=1.2, maxval=3.0, step=0.1, group="Volatility Ladder",
     tooltip="Each successive window is this many times longer than the one before (rounded to whole bars). Default 1.6 with 6 windows gives 5, 8, 13, 20, 33, 52.")
int    ladderSize = input.int(7, "Number of Windows", minval=3, maxval=8, group="Volatility Ladder",
     tooltip="More windows = a richer read of the term structure, but the longest window adds warm-up and lag.")
 
// ── Post-Smoothing ────────────────────────────────────────────────────────────
int postSmoothLen = input.int(8, "Score Smoothing Length", minval=1, group="Post-Smoothing",
     tooltip="EMA smoothing applied to the raw concordance score, which is otherwise a somewhat steppy pairwise count. Set to 1 for no smoothing.")
 
// ── Bands ──────────────────────────────────────────────────────────────────────
float strongThresh = input.float(60.0, "Strong Threshold", minval=1.0, maxval=99.0, group="Bands",
     tooltip="Score above this (or below its negative) = Strong Expansion / Strong Compression. Between 0 and this = Mild.")
 
// ── Table ──────────────────────────────────────────────────────────────────────
bool   showTable = input.bool(true, "Show Stats Table", group="Table")
string tablePos  = input.string("Top Right", "Table Position", options=["Top Right","Top Left","Bottom Right","Bottom Left"], group="Table")
 
// ── Colours ────────────────────────────────────────────────────────────────────
color colStrongExp  = input.color(color.new(color.orange, 60), "Strong Expansion",   group="Colours")
color colMildExp    = input.color(color.new(color.orange, 85), "Mild Expansion",     group="Colours")
color colMildComp   = input.color(color.new(color.aqua,   85), "Mild Compression",   group="Colours")
color colStrongComp = input.color(color.new(color.aqua,   60), "Strong Compression", group="Colours")
bool  paintMainChart = input.bool(true, "Paint Main Chart Background", group="Colours",
     tooltip="Uses force_overlay so the band background shows on the price chart even though the score lives in its own pane.")
 
 
// ─────────────────────────────────────────────────────────────────────────────
// VOLATILITY LADDER
// ─────────────────────────────────────────────────────────────────────────────
// NOTE: window lengths are derived from inputs only (never from a loop
// counter), and each stdev is written out explicitly. A for-loop counter is
// always "series int" in Pine, so it cannot be used to build a length
// argument the way a literal multiplier can. Unrolled for that reason.
int maxLadder = 8
 
float logRet = math.log(source / source[1])
 
int w0 = math.max(2, math.round(baseLen * math.pow(growth, 0)))
int w1 = math.max(2, math.round(baseLen * math.pow(growth, 1)))
int w2 = math.max(2, math.round(baseLen * math.pow(growth, 2)))
int w3 = math.max(2, math.round(baseLen * math.pow(growth, 3)))
int w4 = math.max(2, math.round(baseLen * math.pow(growth, 4)))
int w5 = math.max(2, math.round(baseLen * math.pow(growth, 5)))
int w6 = math.max(2, math.round(baseLen * math.pow(growth, 6)))
int w7 = math.max(2, math.round(baseLen * math.pow(growth, 7)))
 
// Computed unconditionally every bar (required for ta.* consistency), then
// masked by ladder size when stored.
float rv0 = ta.stdev(logRet, w0)
float rv1 = ta.stdev(logRet, w1)
float rv2 = ta.stdev(logRet, w2)
float rv3 = ta.stdev(logRet, w3)
float rv4 = ta.stdev(logRet, w4)
float rv5 = ta.stdev(logRet, w5)
float rv6 = ta.stdev(logRet, w6)
float rv7 = ta.stdev(logRet, w7)
 
var float[] volVals = array.new_float(maxLadder, na)
array.set(volVals, 0, 0 < ladderSize ? rv0 : na)
array.set(volVals, 1, 1 < ladderSize ? rv1 : na)
array.set(volVals, 2, 2 < ladderSize ? rv2 : na)
array.set(volVals, 3, 3 < ladderSize ? rv3 : na)
array.set(volVals, 4, 4 < ladderSize ? rv4 : na)
array.set(volVals, 5, 5 < ladderSize ? rv5 : na)
array.set(volVals, 6, 6 < ladderSize ? rv6 : na)
array.set(volVals, 7, 7 < ladderSize ? rv7 : na)
 
 
// ─────────────────────────────────────────────────────────────────────────────
// RANK CONCORDANCE SCORE
// For every pair (i, j) with i the shorter window: +1 if vol[i] > vol[j]
// (short-term vol above long-term vol = expansion-consistent ordering),
// -1 if reversed (compression-consistent), 0 if tied. Sum and normalise to
// -100..+100 by the number of pairs actually compared.
// ─────────────────────────────────────────────────────────────────────────────
float concSum   = 0.0
int   pairCount = 0
for i = 0 to ladderSize - 2
    for j = i + 1 to ladderSize - 1
        float vi = array.get(volVals, i)
        float vj = array.get(volVals, j)
        if not na(vi) and not na(vj)
            concSum += vi > vj ? 1.0 : (vi < vj ? -1.0 : 0.0)
            pairCount += 1
 
float rawScore      = pairCount > 0 ? (concSum / pairCount) * 100.0 : na
float smoothedScore = postSmoothLen > 1 ? ta.ema(rawScore, postSmoothLen) : rawScore
 
// ── Enough history? ────────────────────────────────────────────────────────────
int usedLongest   = ladderSize == 3 ? w2 : ladderSize == 4 ? w3 : ladderSize == 5 ? w4 : ladderSize == 6 ? w5 : ladderSize == 7 ? w6 : w7
bool warmedUp     = bar_index >= usedLongest + 1 and not na(smoothedScore)
 
// ── Short/long vol ratio (context for the table) ─────────────────────────────
float shortVol = array.get(volVals, 0)
float longVol  = array.get(volVals, ladderSize - 1)
float ratio    = (not na(shortVol) and not na(longVol) and longVol > 0) ? shortVol / longVol : na
 
// ── Confirmed-close-only display (non-repainting) ─────────────────────────────
var float dispScore = na
var float dispRatio = na
if barstate.isconfirmed
    dispScore := warmedUp ? smoothedScore : na
    dispRatio := warmedUp ? ratio : na
 
 
// ─────────────────────────────────────────────────────────────────────────────
// BANDS
// Band codes: 0 = Strong Expansion, 1 = Mild Expansion,
//             2 = Mild Compression, 3 = Strong Compression, 4 = Warming up
// ─────────────────────────────────────────────────────────────────────────────
bandOf(v) =>
    na(v) ? 4 :
     v >=  strongThresh ? 0 :
     v >=  0.0          ? 1 :
     v > -strongThresh  ? 2 : 3
 
bandName(b) =>
    b == 0 ? "Strong Expansion" :
     b == 1 ? "Mild Expansion" :
     b == 2 ? "Mild Compression" :
     b == 3 ? "Strong Compression" : "Warming up…"
 
bandColor(b) =>
    b == 0 ? colStrongExp :
     b == 1 ? colMildExp :
     b == 2 ? colMildComp :
     b == 3 ? colStrongComp : na
 
int currentBand = bandOf(dispScore)
 
 
// ─────────────────────────────────────────────────────────────────────────────
// BAND STREAK & OCCUPANCY
// ─────────────────────────────────────────────────────────────────────────────
var int   lastBand = na
var int   streak   = 0
var int[] occ      = array.new_int(4, 0)
var int   occTotal = 0
if barstate.isconfirmed
    if currentBand == lastBand
        streak := streak + 1
    else
        streak := 1
        lastBand := currentBand
    if currentBand < 4
        array.set(occ, currentBand, array.get(occ, currentBand) + 1)
        occTotal += 1
 
 
// ─────────────────────────────────────────────────────────────────────────────
// PLOTS
// ─────────────────────────────────────────────────────────────────────────────
plot(dispScore, "Term-Structure Concordance", color=color.new(color.yellow, 0), linewidth=2)
hline(0,             "Zero",               color=color.gray, linestyle=hline.style_solid)
hline(strongThresh,  "Strong Expansion",   color=colStrongExp,  linestyle=hline.style_dashed)
hline(-strongThresh, "Strong Compression", color=colStrongComp, linestyle=hline.style_dashed)
 
bgcolor(warmedUp ? bandColor(currentBand) : na, title="Band Background (pane)")
bgcolor(paintMainChart and warmedUp ? bandColor(currentBand) : na, force_overlay=true, title="Band Background (main chart)")
 
 
// ─────────────────────────────────────────────────────────────────────────────
// STATS TABLE
// Shows current band, streak, short/long vol ratio, and how much of the
// chart's loaded history each band has occupied. Occupancy is a description
// of past time-in-state only; it is not a forward-looking or performance
// statistic.
// ─────────────────────────────────────────────────────────────────────────────
getPosition(p) =>
    p == "Top Left"     ? position.top_left :
     p == "Bottom Right" ? position.bottom_right :
     p == "Bottom Left"  ? position.bottom_left : position.top_right
 
occPct(b) => occTotal > 0 ? str.tostring(array.get(occ, b) / occTotal * 100.0, "#.0") + "%" : "—"
 
if showTable and barstate.islast
    var table t = table.new(getPosition(tablePos), 2, 8,
         bgcolor=color.new(color.black, 15), border_width=1, border_color=color.gray,
         frame_color=color.gray, frame_width=1)
 
    table.cell(t, 0, 0, "Vol Term-Structure", text_color=color.white, text_size=size.small, bgcolor=color.new(color.black, 0))
    table.cell(t, 1, 0, "", bgcolor=color.new(color.black, 0))
 
    table.cell(t, 0, 1, "Current", text_color=color.white, text_size=size.small)
    table.cell(t, 1, 1, warmedUp ? bandName(currentBand) : "Warming up…", text_color=warmedUp ? bandColor(currentBand) : color.gray, text_size=size.small)
 
    table.cell(t, 0, 2, "In state for", text_color=color.gray, text_size=size.small)
    table.cell(t, 1, 2, warmedUp ? str.tostring(streak) + " bars" : "—", text_color=color.gray, text_size=size.small)
 
    table.cell(t, 0, 3, "Short / long vol", text_color=color.gray, text_size=size.small)
    table.cell(t, 1, 3, not na(dispRatio) ? str.tostring(dispRatio, "#.00") + "x" : "—", text_color=color.gray, text_size=size.small)
 
    table.cell(t, 0, 4, "Time in Strong Exp.",  text_color=color.gray, text_size=size.small)
    table.cell(t, 1, 4, occPct(0), text_color=color.gray, text_size=size.small)
    table.cell(t, 0, 5, "Time in Mild Exp.",    text_color=color.gray, text_size=size.small)
    table.cell(t, 1, 5, occPct(1), text_color=color.gray, text_size=size.small)
    table.cell(t, 0, 6, "Time in Mild Comp.",   text_color=color.gray, text_size=size.small)
    table.cell(t, 1, 6, occPct(2), text_color=color.gray, text_size=size.small)
    table.cell(t, 0, 7, "Time in Strong Comp.", text_color=color.gray, text_size=size.small)
    table.cell(t, 1, 7, occPct(3), text_color=color.gray, text_size=size.small)
 
 
// ─────────────────────────────────────────────────────────────────────────────
// LIMITATIONS (see published description for the full-length version)
// ─────────────────────────────────────────────────────────────────────────────
// - This measures the SHAPE of realised volatility across windows. It is not
//   directional and does not predict the direction of any move.
// - Strong Compression describes volatility that is low relative to its own
//   longer-run history. Compression can persist for a long time; it is not a
//   timing signal for an expansion.
// - Realised volatility over very short windows is noisy by construction.
//   The shortest windows will flip ordering against longer ones more often.
// - Window ladder and growth factor are a real trade-off: longer ladders
//   read a richer term structure but add warm-up and lag.
// - Band occupancy is a description of time spent in each state on the loaded
//   chart history, which varies with how much history the chart has loaded.
// - Score and band update on confirmed bar close only. Nothing repaints.
// ─────────────────────────────────────────────────────────────────────────────

← 返回列表