Seasonality Window Stats - Roll-Adjusted and Detrended

WarrenLeaks · study · 172 行 · 点赞 16 · 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/
// © WarrenLeaks
 
//@version=6
indicator("Seasonality Window Stats - Roll-Adjusted and Detrended", shorttitle = "Seasonality Window", overlay = true)
 
// ── Inputs ──
yearsBack = input.int(25, "Years to average", minval = 2, maxval = 40)
winMode   = input.string("Next N sessions", "Window", options = ["Rest of year", "Next N sessions"])
nSess     = input.int(20, "N sessions (calendar days on crypto)", minval = 1, maxval = 250)
detrend   = input.bool(false, "Detrend (pure seasonality)")
adjDiv    = input.bool(true, "Adjust for dividends (stocks/ETFs)")
showLine  = input.bool(true, "Show seasonal path for current year")
showProj  = input.bool(true, "Project window")
lineCol   = input.color(color.orange, "Color")
 
if not timeframe.isdaily
    runtime.error("This indicator works on the daily (1D) timeframe only.")
 
bool isCrypto = syminfo.type == "crypto"
 
// ── Roll-safe daily return: adjusted move / prior unadjusted price ──
adjMode = adjDiv ? adjustment.dividends : adjustment.splits
adjC = request.security(ticker.modify(syminfo.tickerid, adjustment = adjMode, backadjustment = backadjustment.on),  timeframe.period, close)
rawC = request.security(ticker.modify(syminfo.tickerid, adjustment = adjMode, backadjustment = backadjustment.off), timeframe.period, close)
 
float ret = 0.0
if bar_index > 0 and not na(adjC) and not na(adjC[1]) and not na(rawC[1]) and rawC[1] > 0
    ret := (adjC - adjC[1]) / rawC[1]
ret := math.max(ret, -0.95)   // guard against negative prices (e.g. crude oil, April 2020)
 
// ── Helpers ──
dayOfYear(int t) =>
    int y = year(t, syminfo.timezone)
    int(math.floor((t - timestamp(syminfo.timezone, y, 1, 1, 0, 0)) / 86400000)) + 1
 
// Cumulative log return of year i up to day d (d > 366 continues into the next year)
valAt(matrix<float> mx, int i, int d) =>
    float out = na
    if d <= 366
        out := mx.get(i, d)
    else if i + 1 < mx.rows() and d - 366 <= 366
        float a = mx.get(i, 366)
        float b = mx.get(i + 1, d - 366)
        if not na(a) and not na(b)
            out := a + b
    out
 
// Average cumulative log return at day d (current year excluded as origin)
avgAt(matrix<float> mx, int d, bool dt) =>
    float s = 0.0
    int   n = 0
    int rows = mx.rows()
    if rows > 1
        for i = 0 to rows - 2
            float v = valAt(mx, i, d)
            float e = mx.get(i, 366)
            if not na(v) and (not dt or not na(e))
                s += dt ? v - e * float(d) / 366.0 : v
                n += 1
    [n > 0 ? s / n : na, n]
 
// Window stats [d0, d0 + len]: years, positives, mean %, best %, worst %
windowStats(matrix<float> mx, int d0, int len, bool dt) =>
    int   n     = 0
    int   up    = 0
    float sum   = 0.0
    float best  = na
    float worst = na
    int rows = mx.rows()
    if rows > 1
        for i = 0 to rows - 2
            float v0 = mx.get(i, d0)
            float v1 = valAt(mx, i, d0 + len)
            float e  = mx.get(i, 366)
            if not na(v0) and not na(v1) and not na(e)
                float lr = (v1 - v0) - (dt ? e * float(len) / 366.0 : 0.0)
                float rr = (math.exp(lr) - 1) * 100
                n   += 1
                sum += rr
                if rr > 0
                    up += 1
                best  := na(best)  ? rr : math.max(best, rr)
                worst := na(worst) ? rr : math.min(worst, rr)
    [n, up, n > 0 ? sum / n : na, best, worst]
 
pctCol(float x) =>
    na(x) ? color.white : x >= 0 ? color.lime : color.red
 
// ── Storage: one row per year, columns = day of year, value = YTD log return ──
var matrix<float> m = matrix.new<float>(0, 367, na)
var float base     = na
var float f        = 1.0
var int   lastDoy  = 0
var bool  fullYear = false
 
int  doy     = dayOfYear(time)
bool newYear = bar_index == 0 or year != year[1]
 
if newYear
    if m.rows() > 0 and fullYear and lastDoy > 0 and lastDoy < 366
        int   lr    = m.rows() - 1
        float lastV = m.get(lr, lastDoy)
        for d = lastDoy + 1 to 366
            m.set(lr, d, lastV)
    base     := bar_index == 0 ? close : close[1]
    f        := 1.0
    fullYear := doy <= 7                    // first (partial) year of history is discarded
    m.add_row(m.rows(), array.new<float>(367, na))
    if m.rows() > yearsBack + 1
        m.remove_row(0)
    lastDoy := 0
 
f *= (1 + ret)
float L = math.log(f)
int   r = m.rows() - 1
 
if fullYear
    float prevL = lastDoy > 0 ? m.get(r, lastDoy) : 0.0
    if doy - lastDoy > 1                    // fill weekends and holidays
        for d = lastDoy + 1 to doy - 1
            m.set(r, d, prevL)
    m.set(r, doy, L)
lastDoy := doy
 
// ── Window length (crypto trades 7 days a week: sessions = days) ──
bool restMode = winMode == "Rest of year"
int  winLen   = restMode ? 366 - doy : isCrypto ? nSess : int(math.round(nSess * 7.0 / 5.0))
 
// ── Seasonal path for the current year ──
[avgNow, nYears] = avgAt(m, doy, detrend)
plot(showLine and not newYear and not na(avgNow) ? base * math.exp(avgNow) : na,
     "Seasonal path", lineCol, 2, plot.style_linebr)
 
// ── Projection + table ──
var polyline pl  = na
var table    tbl = table.new(position.top_right, 2, 7, bgcolor = color.new(color.black, 20), border_width = 1)
 
if barstate.islast and not na(avgNow)
    if not na(pl)
        pl.delete()
    if showProj and winLen > 0
        int y0 = timestamp(syminfo.timezone, year, 1, 1, 0, 0)
        pts = array.new<chart.point>()
        for d = doy to doy + winLen
            [a, _] = avgAt(m, d, detrend)
            if not na(a)
                pts.push(chart.point.from_time(y0 + (d - 1) * 86400000, close * math.exp(a - avgNow)))
        pl := polyline.new(pts, xloc = xloc.bar_time, line_color = lineCol, line_style = line.style_dashed, line_width = 2)
 
    [nR, upR, avgR, bestR, worstR] = windowStats(m, doy, winLen, detrend)
    float  hitPct = nR > 0 ? float(upR) / nR * 100 : na
    float  ytdNow = (math.exp(avgNow) - 1) * 100
    string unitLb = isCrypto ? " days" : " sessions"
    string winLbl = restMode ? "Rest of year" : "Next " + str.tostring(nSess) + unitLb
    string endLbl = str.format_time(time + winLen * 86400000, "dd MMM", syminfo.timezone)
 
    tbl.cell(0, 0, "Window", text_color = color.white)
    tbl.cell(1, 0, winLbl + " (to " + endLbl + ")", text_color = color.white)
    tbl.cell(0, 1, "Years used", text_color = color.white)
    tbl.cell(1, 1, str.tostring(nR), text_color = color.white)
    tbl.cell(0, 2, detrend ? "Mean excess vs trend" : "Mean return", text_color = color.white)
    tbl.cell(1, 2, na(avgR) ? "-" : str.tostring(avgR, "#.##") + " %", text_color = pctCol(avgR))
    tbl.cell(0, 3, detrend ? "Years above trend" : "Years up", text_color = color.white)
    tbl.cell(1, 3, nR > 0 ? str.tostring(upR) + "/" + str.tostring(nR) + "  (" + str.tostring(hitPct, "#") + " %)" : "-",
             text_color = na(hitPct) ? color.white : hitPct >= 68 ? color.lime : hitPct <= 32 ? color.red : color.yellow)
    tbl.cell(0, 4, "Best year", text_color = color.white)
    tbl.cell(1, 4, na(bestR) ? "-" : str.tostring(bestR, "#.##") + " %", text_color = pctCol(bestR))
    tbl.cell(0, 5, "Worst year", text_color = color.white)
    tbl.cell(1, 5, na(worstR) ? "-" : str.tostring(worstR, "#.##") + " %", text_color = pctCol(worstR))
    tbl.cell(0, 6, detrend ? "Deviation vs trend today" : "Average YTD today", text_color = color.white)
    tbl.cell(1, 6, str.tostring(ytdNow, "#.##") + " %", text_color = color.white)

← 返回列表