EquityAugur 3.1 MystTrades

ralis24 · study · 268 行 · 点赞 6 · TradingView 原页

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

Pine Script

//@version=6
indicator("EquityAugur 3.1", overlay=false, max_bars_back=600, dynamic_requests=true)
 
// STORM: a direction-neutral volatility regime gauge. Based on AUGUR 3.0.
// Score = 25 * (rank(VIX/VIX3M) + rank(VIX) + rank(own RV20/RV252)
//                + 1 - rank(VIX / annualized SPX RV20)).
// These are relative ranks, not odds, directional calls, or trading signals.
 
const string G_VIEW = "Display"
const string G_DATA = "Daily feeds"
const string G_STORM = "Storm and historical record"
const string DAY = "1D"
const int MS_DAY = 86400000
const int MAX_AGE_DAYS = 5
 
bool showTable = input.bool(true, "Show table", group=G_VIEW)
string tablePosition = input.string("Bottom Right", "Table position", options=["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"], group=G_VIEW)
string tableSize = input.string("Small", "Table size", options=["Tiny", "Small", "Normal"], group=G_VIEW)
bool showRecord = input.bool(true, "Show historical record on 1D", group=G_VIEW)
bool shadeInversion = input.bool(true, "Shade fear curve inversion", group=G_VIEW)
 
string vixSymbol = input.symbol("TVC:VIX", "VIX", group=G_DATA)
string vix3mSymbol = input.symbol("CBOE:VIX3M", "VIX 3-month", group=G_DATA)
string spxSymbol = input.symbol("SP:SPX", "S&P 500", group=G_DATA)
 
int rankWindow = input.int(252, "Rank window (source daily sessions)", minval=60, maxval=500, group=G_STORM, tooltip="Ranks compare with prior sessions, excluding the observation being ranked. At least 90% of the window must have usable data.")
float calmLevel = input.float(26, "CALM below", minval=1, maxval=50, step=0.5, group=G_STORM)
float stormLevel = input.float(63, "STORM at or above", minval=50, maxval=99, step=0.5, group=G_STORM)
float extremeLevel = input.float(81.5, "EXTREME at or above", minval=50.5, maxval=100, step=0.5, group=G_STORM)
float inversionLevel = input.float(1, "Fear curve inverted above (VIX / VIX3M)", minval=0.9, maxval=1.2, step=0.01, group=G_STORM)
int horizon = input.int(20, "Horizon (daily closes)", minval=5, maxval=60, group=G_STORM)
float bigMultiple = input.float(1.5, "Big move (multiple of horizon sigma)", minval=0.5, maxval=4, step=0.1, group=G_STORM)
 
bool isOneDay = timeframe.isdaily and timeframe.multiplier == 1
bool supported = chart.is_standard and (isOneDay or timeframe.isminutes or timeframe.isseconds)
if barstate.isfirst
    if not supported
        runtime.error("EquityAugur requires standard price bars on a time-based intraday chart or exactly 1D.")
    if not (calmLevel < stormLevel and stormLevel < extremeLevel)
        runtime.error("EquityAugur thresholds must be ordered: CALM < STORM < EXTREME.")
 
f_logReturn() =>
    close > 0 and close[1] > 0 ? math.log(close / close[1]) : na
 
f_volatility(float returns, simple int length) =>
    float vol = ta.stdev(returns, length)
    float missing = math.sum(na(returns) ? 1.0 : 0.0, length)
    missing == 0 ? vol : na
 
// Runs in a native daily context, not on chart bars. Ties count as <=,
// as in 3.0; missing sessions inside the window do not become samples.
f_rank(float value) =>
    int count = 0
    int below = 0
    if not na(value)
        for k = 1 to rankWindow
            float sample = value[k]
            if not na(sample)
                count += 1
                if sample <= value
                    below += 1
    count >= math.ceil(rankWindow * 0.90) ? float(below) / count : na
 
// This packet is evaluated in the requested S&P daily context. The two
// nested requests use their own confirmed prior daily bars. 'time' is the
// OPEN of the bar that releases those prior values, not their sample date.
// No current-day close or volatility enters this packet, so outer
// lookahead_on does not expose a developing daily close.
f_marketPacket() =>
    [vix, vixDay, vixRelease] = request.security(vixSymbol, DAY, [close[1], time_tradingday[1], math.max(time, time_close[1])], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on, ignore_invalid_symbol=true)
    [vix3m, vix3mDay, vix3mRelease] = request.security(vix3mSymbol, DAY, [close[1], time_tradingday[1], math.max(time, time_close[1])], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on, ignore_invalid_symbol=true)
    int spxDay = time_tradingday[1]
    float spxRv = f_volatility(f_logReturn(), 20)[1]
    float spxHigh = ta.highest(close, 252)[1]
    bool aligned = not na(spxDay) and spxDay == vixDay and spxDay == vix3mDay
    int releaseAt = math.max(math.max(time, time_close[1]), math.max(vixRelease, vix3mRelease))
    bool feedsOK = aligned and not na(releaseAt) and vix > 0 and vix3m > 0 and close[1] > 0
    float term = feedsOK ? vix / vix3m : na
    float vixValue = feedsOK ? vix : na
    float logRatio = feedsOK and spxRv > 0 ? math.log(vix / (spxRv * math.sqrt(252.0) * 100.0)) : na
    float backdrop = close[252] > 0 and close[1] > 0 and spxHigh > 0 ? (close[1] / spxHigh - 1.0) * 100.0 : na
    float termRank = f_rank(term)
    float vixRank = f_rank(vixValue)
    float ratioRank = f_rank(logRatio)
    [spxDay, vixDay, vix3mDay, releaseAt, term, vixValue, logRatio, termRank, vixRank, ratioRank, backdrop]
 
f_symbolPacket() =>
    float r = f_logReturn()
    float rv20 = f_volatility(r, 20)
    float rv252 = f_volatility(r, 252)
    float ownRatio = not na(r) and rv252 > 0 ? rv20 / rv252 : na
    float ownRank = f_rank(ownRatio)
    [time_tradingday[1], math.max(time, time_close[1]), ownRatio[1], rv20[1], rv252[1], ownRank[1]]
 
[mDay, vDay, v3Day, mRelease, termRaw, vixRaw, vrpRaw, pTermRaw, pVixRaw, pVrpRaw, ddRaw] = request.security(spxSymbol, DAY, f_marketPacket(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on, ignore_invalid_symbol=true)
[sDay, sRelease, ownRaw, rv20Raw, rv252Raw, pOwnRaw] = request.security(syminfo.tickerid, DAY, f_symbolPacket(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
 
f_usable(int sourceDay, int releasedAt, int chartClose) =>
    not na(sourceDay) and not na(releasedAt) and not na(chartClose) and releasedAt <= chartClose and chartClose - 1 >= sourceDay and chartClose - 1 - sourceDay < (MAX_AGE_DAYS + 1) * MS_DAY
 
bool marketReleased = f_usable(mDay, mRelease, time_close)
bool symbolReleased = f_usable(sDay, sRelease, time_close)
bool marketOK = marketReleased and not na(termRaw)
bool symbolOK = symbolReleased and not na(ownRaw)
bool scoreOK = marketOK and symbolOK and not na(pTermRaw) and not na(pVixRaw) and not na(pVrpRaw) and not na(pOwnRaw)
 
float scoreRaw = scoreOK ? 25.0 * (pTermRaw + pVixRaw + pOwnRaw + 1.0 - pVrpRaw) : na
float sigmaYearRaw = symbolOK ? rv252Raw * math.sqrt(horizon) * 100.0 : na
float sigmaBlendRaw = symbolOK ? (rv20Raw + rv252Raw) * 0.5 * math.sqrt(horizon) * 100.0 : na
string dataRaw = na(mDay) or na(vDay) or na(v3Day) ? "Missing market feed" : mDay != vDay or mDay != v3Day ? "Market dates differ" : not marketReleased ? "Market data stale / pending" : not marketOK ? "Invalid market values" : na(vrpRaw) ? "S&P volatility unavailable" : not symbolReleased ? "Symbol data stale / pending" : not scoreOK ? "Warming up / insufficient data" : "Completed daily inputs"
 
// Hold the last committed display until the current chart bar closes.
// The unmasked series above provide prior committed values via [1].
bool confirmed = barstate.isconfirmed
float storm = confirmed ? scoreRaw : scoreRaw[1]
float term = confirmed ? (marketOK ? termRaw : na) : (marketOK[1] ? termRaw[1] : na)
float vix = confirmed ? (marketOK ? vixRaw : na) : (marketOK[1] ? vixRaw[1] : na)
float logVrp = confirmed ? (marketOK ? vrpRaw : na) : (marketOK[1] ? vrpRaw[1] : na)
float own = confirmed ? (symbolOK ? ownRaw : na) : (symbolOK[1] ? ownRaw[1] : na)
float pTerm = confirmed ? (marketOK ? pTermRaw : na) : (marketOK[1] ? pTermRaw[1] : na)
float pVix = confirmed ? (marketOK ? pVixRaw : na) : (marketOK[1] ? pVixRaw[1] : na)
float pVrp = confirmed ? (marketOK ? pVrpRaw : na) : (marketOK[1] ? pVrpRaw[1] : na)
float pOwn = confirmed ? (symbolOK ? pOwnRaw : na) : (symbolOK[1] ? pOwnRaw[1] : na)
float ddSpx = confirmed ? (marketOK ? ddRaw : na) : (marketOK[1] ? ddRaw[1] : na)
float sigmaBlend = confirmed ? sigmaBlendRaw : sigmaBlendRaw[1]
float bigMove = bigMultiple * (confirmed ? sigmaYearRaw : sigmaYearRaw[1])
string dataState = confirmed ? dataRaw : dataRaw[1]
int shownMarketDay = confirmed ? mDay : mDay[1]
int shownVixDay = confirmed ? vDay : vDay[1]
int shownVix3mDay = confirmed ? v3Day : v3Day[1]
int shownSymbolDay = confirmed ? sDay : sDay[1]
int tierIndex = na(storm) ? -1 : storm >= extremeLevel ? 3 : storm >= stormLevel ? 2 : storm < calmLevel ? 0 : 1
string tier = tierIndex == 3 ? "EXTREME" : tierIndex == 2 ? "STORM" : tierIndex == 1 ? "NORMAL" : tierIndex == 0 ? "CALM" : "UNAVAILABLE"
bool inverted = not na(term) and term > inversionLevel
 
const color C_CALM = #50F1AA
const color C_NORMAL = #45CBFF
const color C_STORM = #FFDC48
const color C_EXTREME = #FF648F
const color C_INVERT = #FFB255
const color C_TEXT = #FFFFFF
const color C_LABEL = #9CEEFF
const color C_HEADER = #5307F8
const color C_BG = #111427
const color C_FRAME = #4C4D73
color tierInk = tierIndex == 3 ? C_EXTREME : tierIndex == 2 ? C_STORM : tierIndex == 1 ? C_NORMAL : tierIndex == 0 ? C_CALM : C_TEXT
 
plot(storm, "Storm", color=tierInk, style=plot.style_columns)
hline(calmLevel, "CALM level", color=C_CALM, linestyle=hline.style_dotted)
hline(stormLevel, "STORM level", color=C_STORM, linestyle=hline.style_dotted)
hline(extremeLevel, "EXTREME level", color=C_EXTREME, linestyle=hline.style_dotted)
hline(0, "Zero", color=color.new(C_TEXT, 80))
hline(100, "Max", color=color.new(C_TEXT, 80))
bgcolor(shadeInversion and inverted ? color.new(C_INVERT, 87) : na, title="Fear curve inverted")
plot(pTerm * 100.0, "Fear curve percentile", color=C_INVERT, display=display.data_window)
plot(pVix * 100.0, "VIX percentile", color=C_EXTREME, display=display.data_window)
plot(pOwn * 100.0, "Own volatility percentile", color=C_NORMAL, display=display.data_window)
plot(pVrp * 100.0, "VIX / S&P realized percentile (inverse weight)", color=C_CALM, display=display.data_window)
plot(term, "VIX / VIX3M", color=C_INVERT, display=display.data_window)
plot(sigmaBlend, "Horizon volatility scale (%)", color=C_TEXT, display=display.data_window)
plot(bigMove, "Record threshold (%)", color=C_TEXT, display=display.data_window)
plot(ddSpx, "S&P % from 1-year high", color=C_TEXT, display=display.data_window)
 
// At t, evaluate the scored origin t-H using closes t-H+1 through t.
// Same chart price series as the native symbol request, on standard 1D.
bool recordEnabled = showTable and showRecord and isOneDay
float nextHigh = ta.highest(close, horizon)
float nextLow = ta.lowest(close, horizon)
float validFraction = ta.sma(close > 0 ? 1.0 : 0.0, horizon)
var array<int> trials = array.new_int(4, 0)
var array<int> hits = array.new_int(4, 0)
var int invertedTrials = 0
var int invertedHits = 0
int originTier = tierIndex[horizon]
float origin = close[horizon]
float threshold = bigMove[horizon] / 100.0
if recordEnabled and confirmed and originTier >= 0 and origin > 0 and threshold > 0 and validFraction == 1.0
    // Volatility is estimated in log returns. As in 3.0, the record uses
    // its magnitude as an approximate symmetric simple-return threshold.
    float width = origin * threshold
    bool hit = nextHigh >= origin + width or nextLow <= origin - width
    array.set(trials, originTier, array.get(trials, originTier) + 1)
    if hit
        array.set(hits, originTier, array.get(hits, originTier) + 1)
    if inverted[horizon]
        invertedTrials += 1
        if hit
            invertedHits += 1
 
// Table: show exact source dates so carried market data is distinguishable
// from a new session. The own-vol and market dates can legitimately differ.
string pos = switch tablePosition
    "Top Left" => position.top_left
    "Top Center" => position.top_center
    "Top Right" => position.top_right
    "Middle Left" => position.middle_left
    "Middle Center" => position.middle_center
    "Middle Right" => position.middle_right
    "Bottom Left" => position.bottom_left
    "Bottom Center" => position.bottom_center
    => position.bottom_right
 
string sz = tableSize == "Tiny" ? size.tiny : tableSize == "Normal" ? size.normal : size.small
var table tbl = table.new(pos, 2, 16, bgcolor=C_BG, border_width=1, border_color=C_FRAME, frame_width=1, frame_color=C_FRAME)
 
f_row(int row, string label, string val, color ink, string tip) =>
    color bg = row == 0 ? C_HEADER : C_BG
    table.cell(tbl, 0, row, label, text_color=row == 0 ? C_TEXT : C_LABEL, bgcolor=bg, text_size=sz, text_halign=text.align_left, tooltip=tip)
    table.cell(tbl, 1, row, val, text_color=row == 0 ? C_TEXT : ink, bgcolor=bg, text_size=sz, text_halign=text.align_right, tooltip=tip)
 
f_num(float value, string fmt, string suffix) =>
    na(value) ? "—" : str.tostring(value, fmt) + suffix
 
f_rankText(float value) =>
    na(value) ? "" : " · p" + str.tostring(value * 100.0, "#")
 
f_date(int stamp) =>
    na(stamp) ? "—" : str.format_time(stamp, "yyyy-MM-dd", "UTC")
 
f_rate(int hit, int n) =>
    n == 0 ? "— (n=0)" : str.tostring(100.0 * hit / n, "0.0") + "% (n=" + str.tostring(n) + ")"
 
if showTable and barstate.islast
    string scoreText = na(storm) ? "UNAVAILABLE" : tier + " " + str.tostring(storm, "0.0")
    string sourceTip = "SPX: " + f_date(shownMarketDay) + " | VIX: " + f_date(shownVixDay) + " | VIX3M: " + f_date(shownVix3mDay) + ". All three market trading dates must match. Completed bars are published on the next source session and committed on a chart bar close. Market data can carry across closures; samples more than five calendar dates old are withheld."
    f_row(0, "EquityAugur 3.1", scoreText, C_TEXT, "Four-factor relative volatility score, not a probability or direction forecast.")
    f_row(1, "Data", na(dataState) ? "Waiting for chart close" : dataState, na(storm) ? C_STORM : C_TEXT, sourceTip + " At defaults, the 252-day own-vol denominator plus rank warm-up can require roughly two years of daily history.")
    f_row(2, "SPX / symbol date", f_date(shownMarketDay) + " / " + f_date(shownSymbolDay), C_TEXT, sourceTip)
    f_row(3, "Fear curve", (inverted ? "INVERTED · " : "") + f_num(term, "0.00", "x") + f_rankText(pTerm), inverted ? C_INVERT : C_TEXT, "VIX divided by VIX3M. Inversion is not a direction call.")
    f_row(4, "VIX", f_num(vix, "0.0", "") + f_rankText(pVix), C_TEXT, "VIX level and rank versus previous matched S&P daily sessions.")
    f_row(5, "Own RV20 / RV252", f_num(own, "0.00", "x") + f_rankText(pOwn), C_TEXT, "20-day versus 252-day close-to-close log-return volatility, ranked in the chart symbol's daily context.")
    f_row(6, "VIX / SPX RV20", f_num(math.exp(logVrp), "0.00", "x") + f_rankText(pVrp), C_TEXT, "VIX divided by annualized 20-day S&P realized volatility. Its rank is inverted in the score.")
    f_row(7, str.tostring(horizon) + "d volatility scale", f_num(sigmaBlend, "0.0", "%"), C_TEXT, "Average of the symbol's 20-day and 252-day daily volatility, scaled by square root of horizon. A scale estimate, not a probability band.")
    f_row(8, "Big move threshold", f_num(bigMove, "0.0", "%"), C_TEXT, "Record threshold: horizon-scaled 252-day volatility times the selected multiple, measured from the origin close.")
    f_row(9, "S&P from 1y high", f_num(ddSpx, "0.0", "%"), C_TEXT, "Drawdown from the highest of the previous 252 completed S&P closes, including the shown S&P session.")
    if recordEnabled
        string recordTip = "Historical observations on loaded bars. Only scored origins with a fully completed horizon. Each hit is a qualifying close in the next " + str.tostring(horizon) + " daily bars. Windows overlap, and the observed rate is not a forward probability."
        f_row(10, "Record: EXTREME", f_rate(array.get(hits, 3), array.get(trials, 3)), C_EXTREME, recordTip)
        f_row(11, "Record: STORM", f_rate(array.get(hits, 2), array.get(trials, 2)), C_STORM, recordTip)
        f_row(12, "Record: NORMAL", f_rate(array.get(hits, 1), array.get(trials, 1)), C_NORMAL, recordTip)
        f_row(13, "Record: CALM", f_rate(array.get(hits, 0), array.get(trials, 0)), C_CALM, recordTip)
        f_row(14, "Record: inverted", f_rate(invertedHits, invertedTrials), C_INVERT, recordTip)
        f_row(15, "Record: all scored", f_rate(array.sum(hits), array.sum(trials)), C_TEXT, recordTip)
    else if showRecord
        f_row(10, "Historical record", "Switch to 1D", C_TEXT, "The forward horizon counts actual daily closes, so the record is shown only on a standard 1D chart.")
 
// No crossing from warm-up or from an unavailable prior observation.
// An inversion may be valid independently of the complete score.
bool stormUp = confirmed and not na(storm) and not na(storm[1]) and storm >= stormLevel and storm[1] < stormLevel
bool extremeUp = confirmed and not na(storm) and not na(storm[1]) and storm >= extremeLevel and storm[1] < extremeLevel
bool inversionUp = confirmed and not na(term) and not na(term[1]) and inverted and term[1] <= inversionLevel
 
alertcondition(stormUp, title="STORM", message="{{ticker}} EquityAugur 3.1 crossed into STORM or above. Volatility regime only.")
alertcondition(extremeUp, title="EXTREME", message="{{ticker}} EquityAugur 3.1 crossed into EXTREME. Volatility regime only.")
alertcondition(inversionUp, title="Fear curve inverted", message="{{ticker}} EquityAugur 3.1: VIX/VIX3M crossed the inversion level. No direction forecast.")
 
f_jsonNum(float value) =>
    na(value) ? "null" : str.tostring(value, "0.00")
 
f_jsonString(string value) =>
    string escaped = str.replace_all(value, "\\", "\\\\")
    escaped := str.replace_all(escaped, '"', '\\"')
    '"' + escaped + '"'
 
if stormUp or extremeUp or inversionUp
    string event = extremeUp ? "EXTREME" : stormUp ? "STORM" : "INVERSION"
    string payload = '{"version":"3.1","event":' + f_jsonString(event) + ',"ticker":' + f_jsonString(syminfo.ticker) + ',"interval":' + f_jsonString(timeframe.period) + ',"storm":' + f_jsonNum(storm) + ',"tier":' + f_jsonString(tier) + ',"inverted":' + (na(term) ? "null" : inverted ? "true" : "false") + ',"move_1sigma_pct":' + f_jsonNum(sigmaBlend) + ',"big_move_pct":' + f_jsonNum(bigMove) + ',"market_date":' + f_jsonString(f_date(shownMarketDay)) + ',"symbol_date":' + f_jsonString(f_date(shownSymbolDay)) + '}'
    alert(payload, alert.freq_once_per_bar_close)

← 返回列表