Dual Window Volatility-Scaled Forecast Fan

DCAlpha · study · 404 行 · 点赞 198 · TradingView 原页

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

Pine Script

//@version=6
indicator("Dual Window Volatility-Scaled Forecast Fan)", shorttitle="MCFan", overlay=true, max_polylines_count=100, max_labels_count=30, max_boxes_count=60, max_lines_count=10)
 
// ───────────────────────────────────────────────────────────────
// Kronos-style forecast fan for TradingView (v13).
// NOT the Kronos neural network (that runs in Python). Paths come from a
// volatility-scaled Monte Carlo of recent returns, TILTED BY THE CURRENT
// TREND so the fan angles up in an uptrend and down in a downtrend.
//  - Window 1 (short) and Window 2 (long), each with its own colours.
//  - Fan paths faded by likelihood, probability bands, p90/p10 lines,
//    glowing median, NOW pane, end-price histogram.
// p90 = high case (90% of paths end below). p10 = low case.
// Not financial advice.
// ───────────────────────────────────────────────────────────────
 
grp1 = "Forecast"
horizon1  = input.int(72, "Window 1: horizon (candles)", minval=2, maxval=200, group=grp1)
useSecond = input.bool(true, "Enable window 2 (longer)", group=grp1)
horizon2  = input.int(288, "Window 2: horizon (candles)", minval=10, maxval=450, group=grp1, tooltip="TradingView can draw at most ~500 bars into the future. The histogram shrinks automatically if there is not enough room.")
nPaths    = input.int(200, "Simulated paths", minval=50, maxval=400, group=grp1, tooltip="More paths = smoother histogram and steadier percentages, but slower. Only a few are drawn (see Style).")
lookback  = input.int(512, "Context (candles)", minval=50, maxval=2000, group=grp1)
volWin    = input.int(48, "Recent-vol window", minval=10, maxval=500, group=grp1)
method    = input.string("Bootstrap", "Sampling", options=["Bootstrap", "Gaussian"], group=grp1)
volHalf   = input.int(48, "Vol mean-reversion half-life (candles, 0 = off)", minval=0, maxval=2000, group=grp1, tooltip="Simulated volatility starts at the recent level and decays toward the long-run (context) level, halving the gap every N candles. 0 = keep today's volatility forever.")
seedIn    = input.int(42, "Seed", group=grp1)
 
grp0 = "Trend (angle of the projection)"
trendOn   = input.bool(true, "Follow the trend", group=grp0, tooltip="Tilts the whole fan along the current trend (slope of a regression line through recent prices), so it angles up in an uptrend and down in a downtrend, like in the original video.")
trendLen  = input.int(48, "Trend length (candles)", minval=5, maxval=500, group=grp0, tooltip="How many recent candles are used to measure the trend. Shorter = reacts faster, longer = smoother.")
trendMix  = input.float(1.0, "Trend strength", minval=0.0, maxval=3.0, step=0.1, group=grp0, tooltip="1.0 = continue the measured slope. 0.5 = half of it. 0 = flat (no trend).")
trendMaxZ = input.float(0.25, "Max tilt (x volatility per candle)", minval=0.02, maxval=1.0, step=0.01, group=grp0, tooltip="Safety cap on how steep the tilt can get, as a fraction of one candle's typical move. Stops extreme slopes from producing silly projections.")
trendFade = input.int(150, "Trend fades after (candles, half-life, 0 = never)", minval=0, maxval=2000, group=grp0, tooltip="Trends rarely continue forever. The tilt halves every N candles. 0 = the same slope all the way to the end.")
trendEvalWin = input.int(500, "Accuracy check window (candles)", minval=50, maxval=5000, group=grp0, tooltip="How many past forecasts are averaged in the accuracy rows. Consecutive forecasts overlap, so treat this as a rough guide, not a precise statistic.")
trendGate = input.bool(false, "Switch the tilt off when following the trend hasn't worked", group=grp0, tooltip="Per window: if the trend-following verdict is not FOLLOW on this chart, the fan is drawn flat (no tilt). Off by default so you always see the angled fan.")
 
grp2 = "Style"
showPaths  = input.bool(true, "Window 1: show individual paths", group=grp2)
pathsShort = input.int(10, "Window 1 (short): paths drawn", minval=0, maxval=40, group=grp2, tooltip="Only limits what is DRAWN. All simulated paths are still used for the percentages.")
pathsLong  = input.int(14, "Window 2 (long): paths drawn", minval=0, maxval=40, group=grp2)
hideRare   = input.bool(true, "Hide the rarest (least likely) paths", group=grp2)
showPaths2 = input.bool(true, "Window 2: show individual paths", group=grp2)
showFill   = input.bool(true, "Show probability bands (p25-p75, p10-p90)", group=grp2)
showLines  = input.bool(true, "Show p90 / p10 lines", group=grp2, tooltip="p90 = high case: 9 out of 10 simulated paths end BELOW this line.\np10 = low case: only 1 out of 10 simulated paths ends below this line.\nSo 80% of simulated outcomes land between the two lines.")
showHist   = input.bool(true, "Show end-price histogram", group=grp2, tooltip="Smooths the simulated end prices with a Gaussian kernel, then sums the density over price slices (a Riemann sum). Bar length = probability of that slice.")
histBins   = input.int(12, "Histogram bins", minval=5, maxval=20, group=grp2)
histWidth  = input.int(14, "Histogram longest bar (candles wide)", minval=4, maxval=40, group=grp2)
showPane   = input.bool(true, "Show NOW pane + forecast zone", group=grp2)
showGlow   = input.bool(true, "Glow on median", group=grp2)
showTable  = input.bool(true, "Show panel", group=grp2)
minOpac    = input.int(96, "Rarest path transparency (0-100)", minval=50, maxval=100, group=grp2)
maxOpac    = input.int(76, "Likeliest path transparency (0-100)", minval=0, maxval=95, group=grp2)
upBase     = input.color(#a3e635, "Window 1 (short): up colour (lime)", group=grp2)
dnBase     = input.color(#ff4d5e, "Window 1 (short): down colour (red)", group=grp2)
medCol     = input.color(#ffe14d, "Window 1 (short): median (yellow)", group=grp2)
upBase2    = input.color(#4da3ff, "Window 2 (long): up colour (blue)", group=grp2)
dnBase2    = input.color(#c06bff, "Window 2 (long): down colour (violet)", group=grp2)
medCol2    = input.color(#ff9f43, "Window 2 (long): median (orange)", group=grp2)
 
grp3 = "Calibration"
hitWin = input.int(20, "Coverage window (forecasts)", minval=5, maxval=200, group=grp3)
 
// ── series calculations (every bar) ──
r = math.log(close / close[1])
sigmaRecent = ta.stdev(r, volWin)
 
// trend slope: change per candle (in log price) of a regression line through the last trendLen candles
lrNow = ta.linreg(math.log(close), trendLen, 0)
lrPrev = ta.linreg(math.log(close), trendLen, 1)
trendSlope = lrNow - lrPrev
 
z90 = 1.2815516
lo1o = close[horizon1] * math.exp(-z90 * sigmaRecent[horizon1] * math.sqrt(horizon1))
hi1o = close[horizon1] * math.exp( z90 * sigmaRecent[horizon1] * math.sqrt(horizon1))
hit1 = (not na(lo1o)) and close >= lo1o and close <= hi1o ? 1.0 : 0.0
hitRate1 = ta.sma(hit1, hitWin)
lo2o = close[horizon2] * math.exp(-z90 * sigmaRecent[horizon2] * math.sqrt(horizon2))
hi2o = close[horizon2] * math.exp( z90 * sigmaRecent[horizon2] * math.sqrt(horizon2))
hit2 = (not na(lo2o)) and close >= lo2o and close <= hi2o ? 1.0 : 0.0
hitRate2 = ta.sma(hit2, hitWin)
 
lcg(float s) =>
    (s * 1664525.0 + 1013904223.0) % 4294967296.0
 
clipf(float x, float lo, float hi) =>
    math.max(lo, math.min(hi, x))
 
// nearest-rank percentile of an already sorted array
qs(array<float> a, float p) =>
    k = array.size(a)
    array.get(a, math.max(0, math.min(k - 1, int(math.ceil(p / 100.0 * k)) - 1)))
 
// ── trend accuracy: did the fan's direction, H candles ago, turn out right? (every bar) ──
// direction = sign of the trend tilt at that time; realised = price change over the next H candles.
// accuracy = share of correct directions; edge = average realised move in the predicted
// direction, measured in volatility units (σ). Positive edge = following the trend paid off.
tiltSer = trendOn and not na(trendSlope) and sigmaRecent > 0 ? trendMix * clipf(trendSlope, -trendMaxZ * sigmaRecent, trendMaxZ * sigmaRecent) : 0.0
 
pd1 = tiltSer[horizon1]
rh1 = math.log(close / close[horizon1])
sg1 = sigmaRecent[horizon1]
ok1 = not na(pd1) and not na(rh1) and not na(sg1) and sg1 > 0 and pd1 != 0
hitTr1 = ok1 ? ((pd1 > 0) == (rh1 > 0) ? 1.0 : 0.0) : na
edgTr1 = ok1 ? math.sign(pd1) * rh1 / (sg1 * math.sqrt(horizon1)) : na
accTr1 = ta.sma(hitTr1, trendEvalWin)
edgAvg1 = ta.sma(edgTr1, trendEvalWin)
 
pd2 = tiltSer[horizon2]
rh2 = math.log(close / close[horizon2])
sg2 = sigmaRecent[horizon2]
ok2 = not na(pd2) and not na(rh2) and not na(sg2) and sg2 > 0 and pd2 != 0
hitTr2 = ok2 ? ((pd2 > 0) == (rh2 > 0) ? 1.0 : 0.0) : na
edgTr2 = ok2 ? math.sign(pd2) * rh2 / (sg2 * math.sqrt(horizon2)) : na
accTr2 = ta.sma(hitTr2, trendEvalWin)
edgAvg2 = ta.sma(edgTr2, trendEvalWin)
 
var array<polyline> pls = array.new<polyline>()
var array<label> lbls = array.new<label>()
var array<box> boxes = array.new<box>()
var table tbl = na
 
// ── one full forecast window; draws and returns stats ──
runForecast(array<float> pool, float sdRec, int hz, int nP, bool drawP, int pN, color medC, color upC, color dnC, int fT1, int fT2, int seed, float sdLong, float d0) =>
    m = array.size(pool)
    // statistics are recorded every `stride` candles (always incl. the last) to keep it fast
    stride = math.max(1, int(math.ceil(hz / 96.0)))
    nc = int(math.ceil(hz / float(stride)))
    sims = matrix.new<float>(nP, nc, 0.0)
    finals = array.new_float()
    state = float(seed) * 7919.0 + 12345.0
    ups = 0
    // volatility path: starts at recent level, decays toward long-run level
    volRatio = array.new_float(hz, 1.0)
    if volHalf > 0 and sdRec > 0
        dec = math.pow(0.5, 1.0 / volHalf)
        for h = 0 to hz - 1
            array.set(volRatio, h, (sdLong + (sdRec - sdLong) * math.pow(dec, h)) / sdRec)
    // trend tilt: per-candle drift d0, optionally fading over time
    driftArr = array.new_float(hz, d0)
    if d0 != 0.0 and trendFade > 0
        for h = 0 to hz - 1
            array.set(driftArr, h, d0 * math.pow(0.5, h / float(trendFade)))
    for p = 0 to nP - 1
        px = close
        for h = 0 to hz - 1
            float ret = 0.0
            if method == "Bootstrap"
                state := lcg(state)
                idx = int(state / 4294967296.0 * m)
                ret := array.get(pool, math.min(idx, m - 1)) * array.get(volRatio, h) + array.get(driftArr, h)
            else
                state := lcg(state)
                u1 = math.max(state / 4294967296.0, 1e-9)
                state := lcg(state)
                u2 = state / 4294967296.0
                zz = math.sqrt(-2.0 * math.log(u1)) * math.cos(2.0 * math.pi * u2)
                ret := zz * sdRec * array.get(volRatio, h) + array.get(driftArr, h)
            px := px * math.exp(ret)
            if (h + 1) % stride == 0 or h == hz - 1
                matrix.set(sims, p, int(h / stride), px)
        array.push(finals, px)
        if px > close
            ups += 1
    pUp = ups / float(nP) * 100.0
    pDn = 100.0 - pUp
 
    // per-column statistics (sorted once per column)
    medArr = array.new<chart.point>()
    p10pts = array.new<chart.point>()
    p90pts = array.new<chart.point>()
    p25f = array.new<chart.point>()
    hi90v = array.new_float()
    hi75v = array.new_float()
    xcol = array.new_int()
    array.push(medArr, chart.point.from_index(bar_index, close))
    array.push(p10pts, chart.point.from_index(bar_index, close))
    array.push(p90pts, chart.point.from_index(bar_index, close))
    float medEnd = close
    float loEnd = close
    float hiEnd = close
    for j = 0 to nc - 1
        col = matrix.col(sims, j)
        array.sort(col)
        md = qs(col, 50)
        lo10 = qs(col, 10)
        hi90 = qs(col, 90)
        lo25 = qs(col, 25)
        hi75 = qs(col, 75)
        xx = bar_index + math.min((j + 1) * stride, hz)
        array.push(xcol, xx)
        array.push(medArr, chart.point.from_index(xx, md))
        array.push(p10pts, chart.point.from_index(xx, lo10))
        array.push(p90pts, chart.point.from_index(xx, hi90))
        array.push(p25f, chart.point.from_index(xx, lo25))
        array.push(hi90v, hi90)
        array.push(hi75v, hi75)
        if j == nc - 1
            medEnd := md
            loEnd := lo10
            hiEnd := hi90
 
    // ── Riemann-sum histogram of a smoothed end-price density ──
    // mass_i = density(centre_i) · bin width, normalised so Σ mass_i = 100%
    if showHist
        sdF = array.stdev(finals)
        hK = math.max(1.06 * sdF * math.pow(nP, -0.2), syminfo.mintick)
        gLo = array.min(finals) - hK
        gHi = array.max(finals) + hK
        nb = histBins
        bwH = math.max((gHi - gLo) / nb, syminfo.mintick)
        mass = array.new_float(nb, 0.0)
        float tot = 0.0
        for i = 0 to nb - 1
            cI = gLo + (i + 0.5) * bwH
            float dsum = 0.0
            for k = 0 to nP - 1
                zk = (cI - array.get(finals, k)) / hK
                dsum += math.exp(-0.5 * zk * zk)
            array.set(mass, i, dsum)
            tot += dsum
        float pMax = 0.0
        for i = 0 to nb - 1
            pm = tot > 0 ? array.get(mass, i) / tot : 0.0
            array.set(mass, i, pm)
            pMax := math.max(pMax, pm)
        // keep inside TradingView's ~500-bar future limit
        wMax = math.max(2, math.min(histWidth, 495 - hz))
        x0 = bar_index + hz + 3   // small horizontal gap between the fan end and the blocks
        if pMax > 0
            for i = 0 to nb - 1
                pm = array.get(mass, i)
                loI = gLo + i * bwH
                w = math.max(1, int(math.round(wMax * pm / pMax)))
                bc = (loI + bwH / 2) > close ? upC : dnC
                // small vertical gap between neighbouring blocks (8% of the bin height on each side)
                array.push(boxes, box.new(x0, loI + bwH * 0.92, x0 + w, loI + bwH * 0.08, border_color=na, bgcolor=color.new(bc, 58)))
 
    // probability bands
    bandBase = pUp >= pDn ? upC : dnC
    if showFill
        poly90 = array.new<chart.point>()
        poly50 = array.new<chart.point>()
        array.push(poly90, chart.point.from_index(bar_index, close))
        array.push(poly50, chart.point.from_index(bar_index, close))
        for j = 0 to nc - 1
            array.push(poly90, array.get(p10pts, j + 1))
            array.push(poly50, array.get(p25f, j))
        for j = nc - 1 to 0
            xx = array.get(xcol, j)
            array.push(poly90, chart.point.from_index(xx, array.get(hi90v, j)))
            array.push(poly50, chart.point.from_index(xx, array.get(hi75v, j)))
        array.push(pls, polyline.new(poly90, closed=true, line_color=na, fill_color=color.new(bandBase, fT1)))
        array.push(pls, polyline.new(poly50, closed=true, line_color=na, fill_color=color.new(bandBase, fT2)))
 
    // individual paths, faded by likelihood of their end price
    spread = hiEnd - loEnd
    nDraw = math.min(nP, pN)
    if drawP and nDraw > 0
        bw = math.max(spread / 10.0, syminfo.mintick)
        dens = array.new_float()
        float dMax = 1.0
        for p = 0 to nDraw - 1
            fp = array.get(finals, p)
            c = 0
            for q = 0 to nP - 1
                if math.abs(array.get(finals, q) - fp) <= bw
                    c += 1
            array.push(dens, float(c))
            dMax := math.max(dMax, float(c))
        for tier = (hideRare ? 1 : 0) to 2
            for p = 0 to nDraw - 1
                d = array.get(dens, p) / dMax
                t = d < 0.34 ? 0 : d < 0.67 ? 1 : 2
                if t == tier
                    pts = array.new<chart.point>()
                    array.push(pts, chart.point.from_index(bar_index, close))
                    for j = 0 to nc - 1
                        array.push(pts, chart.point.from_index(array.get(xcol, j), matrix.get(sims, p, j)))
                    fin = array.get(finals, p)
                    pc = color.from_gradient(fin, loEnd, hiEnd, dnC, upC)
                    transp = minOpac - (minOpac - maxOpac) * d
                    array.push(pls, polyline.new(pts, line_color=color.new(pc, int(transp)), line_width=1))
 
    // p90 / p10 lines
    if showLines
        array.push(pls, polyline.new(p90pts, line_color=color.new(upC, 25), line_width=1, line_style=line.style_dashed))
        array.push(pls, polyline.new(p10pts, line_color=color.new(dnC, 25), line_width=1, line_style=line.style_dashed))
    // median (+ glow)
    if showGlow
        array.push(pls, polyline.new(medArr, line_color=color.new(medC, 88), line_width=3))
    array.push(pls, polyline.new(medArr, line_color=color.new(medC, 12), line_width=1))
 
    // end labels
    xEnd = bar_index + hz
    tag = str.tostring(hz) + "c "
    array.push(lbls, label.new(xEnd, medEnd, tag + "median " + str.tostring(medEnd, format.mintick), style=label.style_label_left, color=color.new(#0b1520, 25), textcolor=medC, size=size.small, text_font_family=font.family_monospace))
    array.push(lbls, label.new(xEnd, hiEnd, tag + "▲ " + str.tostring(pUp, "#") + "%  p90 " + str.tostring(hiEnd, format.mintick), style=label.style_label_left, color=color.new(#0b1520, 25), textcolor=upC, size=size.small, text_font_family=font.family_monospace))
    array.push(lbls, label.new(xEnd, loEnd, tag + "▼ " + str.tostring(pDn, "#") + "%  p10 " + str.tostring(loEnd, format.mintick), style=label.style_label_left, color=color.new(#0b1520, 25), textcolor=dnC, size=size.small, text_font_family=font.family_monospace))
    [medEnd, loEnd, hiEnd, pUp, pDn]
 
// panel row helper
panelRow(table t, int row, string lbl, string v1, color c1, string v2, color c2, bool two) =>
    table.cell(t, 0, row, lbl, text_color=color.gray, text_size=size.small, text_halign=text.align_left, text_font_family=font.family_monospace)
    table.cell(t, 1, row, v1, text_color=c1, text_size=size.small, text_font_family=font.family_monospace)
    if two
        table.cell(t, 2, row, v2, text_color=c2, text_size=size.small, text_font_family=font.family_monospace)
 
if barstate.islast and bar_index > math.max(math.max(volWin, trendLen), 60) + 2
    for pl in pls
        polyline.delete(pl)
    array.clear(pls)
    for lb in lbls
        label.delete(lb)
    array.clear(lbls)
    for bx in boxes
        box.delete(bx)
    array.clear(boxes)
 
    n = math.min(lookback, bar_index - 1)
    rets = array.new_float()
    for i = 0 to n - 1
        v = r[i]
        if not na(v)
            array.push(rets, v)
    m = array.size(rets)
    mu = array.avg(rets)
    sdAll = array.stdev(rets)
    sdRec = sigmaRecent
    scale = sdAll > 0 ? sdRec / sdAll : 1.0
    pool = array.new_float()
    for i = 0 to m - 1
        array.push(pool, (array.get(rets, i) - mu) * scale)
 
    // trend tilt (per candle, in log price), capped relative to volatility
    d0 = trendOn and not na(trendSlope) ? trendMix * clipf(trendSlope, -trendMaxZ * sdRec, trendMaxZ * sdRec) : 0.0
 
    // trend verdicts from the accuracy check
    fol1 = not na(accTr1) and accTr1 >= 0.55 and nz(edgAvg1) > 0
    fad1 = not na(accTr1) and accTr1 <= 0.45 and nz(edgAvg1) < 0
    fol2 = not na(accTr2) and accTr2 >= 0.55 and nz(edgAvg2) > 0
    fad2 = not na(accTr2) and accTr2 <= 0.45 and nz(edgAvg2) < 0
    d0w1 = trendGate and not fol1 ? 0.0 : d0
    d0w2 = trendGate and not fol2 ? 0.0 : d0
 
    // window 2 first (drawn underneath), then window 1
    float med2 = na
    float lo2 = na
    float hi2 = na
    float pu2 = na
    float pd2 = na
    if useSecond
        [a, b, c, d, e] = runForecast(pool, sdRec, horizon2, nPaths, showPaths2, pathsLong, medCol2, upBase2, dnBase2, 98, 96, seedIn + 1, sdAll, d0w2)
        med2 := a
        lo2 := b
        hi2 := c
        pu2 := d
        pd2 := e
    [med1, lo1, hi1, pu1, pd1] = runForecast(pool, sdRec, horizon1, nPaths, showPaths, pathsShort, medCol, upBase, dnBase, 98, 96, seedIn, sdAll, d0w1)
 
    // NOW pane + faint forecast zone (spans the longest window)
    hzMax = useSecond ? math.max(horizon1, horizon2) : horizon1
    topAll = math.max(hi1, useSecond ? hi2 : hi1)
    botAll = math.min(lo1, useSecond ? lo2 : lo1)
    pad = (topAll - botAll) * 0.1
    paneTop = math.max(topAll, close) + pad
    paneBot = math.min(botAll, close) - pad
    if showPane
        array.push(boxes, box.new(bar_index, paneTop, bar_index + hzMax, paneBot, border_color=na, bgcolor=color.new(upBase, 97)))
        array.push(boxes, box.new(bar_index - 1, paneTop, bar_index + 1, paneBot, border_color=color.new(upBase, 50), border_width=1, bgcolor=color.new(upBase, 88)))
        array.push(lbls, label.new(bar_index, paneTop, "NOW", style=label.style_label_down, color=color.new(#0b1520, 25), textcolor=upBase, size=size.small, text_font_family=font.family_monospace))
 
    // regime
    sp1 = hi1 - lo1
    reg1 = sp1 > 0 and math.abs(med1 - close) / sp1 > 0.25 ? "TRENDING" : "CHOPPY"
    sp2 = hi2 - lo2
    reg2 = sp2 > 0 and math.abs(med2 - close) / sp2 > 0.25 ? "TRENDING" : "CHOPPY"
    mv1 = (med1 / close - 1.0) * 100.0
    mv2 = (med2 / close - 1.0) * 100.0
 
    if showTable
        table.delete(tbl)
        cols = useSecond ? 3 : 2
        tbl := table.new(position.top_right, cols, 13, bgcolor=color.new(#0b1520, 10), border_color=color.new(upBase, 70), border_width=1, frame_color=color.new(upBase, 50), frame_width=1)
        txt1 = str.tostring(horizon1) + "c"
        txt2 = str.tostring(horizon2) + "c"
        panelRow(tbl, 0, "KRONOS-STYLE", txt1, upBase, txt2, upBase2, useSecond)
        panelRow(tbl, 1, "Median", str.tostring(med1, format.mintick), medCol, str.tostring(med2, format.mintick), medCol2, useSecond)
        panelRow(tbl, 2, "Median move", (mv1 >= 0 ? "+" : "") + str.tostring(mv1, "0.00") + "%", mv1 >= 0 ? upBase : dnBase, (mv2 >= 0 ? "+" : "") + str.tostring(mv2, "0.00") + "%", mv2 >= 0 ? upBase2 : dnBase2, useSecond)
        panelRow(tbl, 3, "Chance up", str.tostring(pu1, "#") + "%", upBase, str.tostring(pu2, "#") + "%", upBase2, useSecond)
        panelRow(tbl, 4, "Chance down", str.tostring(pd1, "#") + "%", dnBase, str.tostring(pd2, "#") + "%", dnBase2, useSecond)
        panelRow(tbl, 5, "p90 · high case", str.tostring(hi1, format.mintick), upBase, str.tostring(hi2, format.mintick), upBase2, useSecond)
        panelRow(tbl, 6, "p10 · low case", str.tostring(lo1, format.mintick), dnBase, str.tostring(lo2, format.mintick), dnBase2, useSecond)
        panelRow(tbl, 7, "Spread (80%)", str.tostring(sp1, format.mintick), color.white, str.tostring(sp2, format.mintick), color.white, useSecond)
        cov1Col = na(hitRate1) ? color.white : math.abs(hitRate1 * 100 - 80) <= 10 ? upBase : #ffb454
        cov2Col = na(hitRate2) ? color.white : math.abs(hitRate2 * 100 - 80) <= 10 ? upBase2 : #ffb454
        panelRow(tbl, 8, "Coverage (≈80% ok)", na(hitRate1) ? "n/a" : str.tostring(hitRate1 * 100, "#") + "%", cov1Col, na(hitRate2) ? "n/a" : str.tostring(hitRate2 * 100, "#") + "%", cov2Col, useSecond)
        panelRow(tbl, 9, "Regime", reg1, reg1 == "TRENDING" ? upBase : #ffb454, reg2, reg2 == "TRENDING" ? upBase2 : #ffb454, useSecond)
        // did following the trend work on this chart? (past forecasts, same horizons as the windows)
        acc1Col = fol1 ? upBase : fad1 ? dnBase : #ffb454
        acc2Col = fol2 ? upBase2 : fad2 ? dnBase2 : #ffb454
        panelRow(tbl, 10, "Trend accuracy", na(accTr1) ? "n/a" : str.tostring(accTr1 * 100, "0") + "%", acc1Col, na(accTr2) ? "n/a" : str.tostring(accTr2 * 100, "0") + "%", acc2Col, useSecond)
        panelRow(tbl, 11, "Trend edge (σ)", na(edgAvg1) ? "n/a" : (edgAvg1 >= 0 ? "+" : "") + str.tostring(edgAvg1, "0.00"), acc1Col, na(edgAvg2) ? "n/a" : (edgAvg2 >= 0 ? "+" : "") + str.tostring(edgAvg2, "0.00"), acc2Col, useSecond)
        ver1 = na(accTr1) ? "n/a" : fol1 ? "FOLLOW" : fad1 ? "FADE" : "NO EDGE"
        ver2 = na(accTr2) ? "n/a" : fol2 ? "FOLLOW" : fad2 ? "FADE" : "NO EDGE"
        panelRow(tbl, 12, "Trend verdict", ver1, acc1Col, ver2, acc2Col, useSecond)

← 返回列表