Seasonal Monthly Heatmap - Multi-Asset, Roll-Adjusted

WarrenLeaks · study · 170 行 · 点赞 3 · 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("Seasonal Monthly Heatmap - Multi-Asset, Roll-Adjusted", shorttitle = "Seasonal Heatmap", overlay = true)
 
// ── Inputs ──
yearsBack = input.int(25, "Years to average", minval = 3, maxval = 40)
presetIn  = input.string("Futures", "List", options = ["Futures", "US Sectors", "Custom"])
detrend   = input.bool(true, "Detrend (pure seasonality)")
adjDiv    = input.bool(true, "Adjust for dividends (stocks/ETFs)")
showMean  = input.bool(true, "Show mean return")
posIn     = input.string("Bottom right", "Position", options = ["Top right", "Middle", "Bottom right"])
txtSize   = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal"])
 
gC = "Custom list"
c1  = input.symbol("AMEX:IWM",    "Symbol 1",  group = gC)
c2  = input.symbol("AMEX:XRT",    "Symbol 2",  group = gC)
c3  = input.symbol("AMEX:XHB",    "Symbol 3",  group = gC)
c4  = input.symbol("AMEX:KRE",    "Symbol 4",  group = gC)
c5  = input.symbol("NASDAQ:SMH",  "Symbol 5",  group = gC)
c6  = input.symbol("NASDAQ:AAPL", "Symbol 6",  group = gC)
c7  = input.symbol("NASDAQ:MSFT", "Symbol 7",  group = gC)
c8  = input.symbol("AMEX:GLD",    "Symbol 8",  group = gC)
c9  = input.symbol("NASDAQ:TLT",  "Symbol 9",  group = gC)
c10 = input.symbol("AMEX:XLE",    "Symbol 10", group = gC)
 
if not timeframe.isdaily
    runtime.error("Use this indicator on the daily (1D) timeframe.")
 
pick(string fut, string sec, string cus) =>
    presetIn == "Futures" ? fut : presetIn == "US Sectors" ? sec : cus
 
s1  = pick("CME_MINI:NQ1!",  "AMEX:SPY",   c1)
s2  = pick("CME_MINI:ES1!",  "NASDAQ:QQQ", c2)
s3  = pick("CBOT_MINI:YM1!", "AMEX:IWM",   c3)
s4  = pick("CME_MINI:RTY1!", "AMEX:XLK",   c4)
s5  = pick("COMEX:GC1!",     "AMEX:XLF",   c5)
s6  = pick("COMEX:SI1!",     "AMEX:XLE",   c6)
s7  = pick("NYMEX:CL1!",     "AMEX:XLV",   c7)
s8  = pick("NYMEX:NG1!",     "AMEX:XLY",   c8)
s9  = pick("CBOT:ZN1!",      "AMEX:XLP",   c9)
s10 = pick("CME:6E1!",       "AMEX:XLU",   c10)
 
// ── Roll-safe daily return (futures) with optional dividend adjustment (stocks) ──
dailyRet(string sym) =>
    adjMode = adjDiv ? adjustment.dividends : adjustment.splits
    float dA = request.security(ticker.modify(sym, adjustment = adjMode, backadjustment = backadjustment.on),  "D", close - close[1], gaps = barmerge.gaps_on)
    float p1 = request.security(ticker.modify(sym, adjustment = adjMode, backadjustment = backadjustment.off), "D", close[1],         gaps = barmerge.gaps_on)
    float r = na
    if not na(dA) and not na(p1) and p1 > 0
        r := math.max(dA / p1, -0.95)
    r
 
isCryptoSym(string sym) =>
    request.security(sym, "D", syminfo.type == "crypto")
 
shortName(string sym) =>
    array<string> p = str.split(sym, ":")
    p.get(p.size() - 1)
 
rets  = array.from(dailyRet(s1), dailyRet(s2), dailyRet(s3), dailyRet(s4), dailyRet(s5),
                   dailyRet(s6), dailyRet(s7), dailyRet(s8), dailyRet(s9), dailyRet(s10))
cryp  = array.from(isCryptoSym(s1), isCryptoSym(s2), isCryptoSym(s3), isCryptoSym(s4), isCryptoSym(s5),
                   isCryptoSym(s6), isCryptoSym(s7), isCryptoSym(s8), isCryptoSym(s9), isCryptoSym(s10))
names = array.from(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10)
 
// ── Per-symbol data: years x 12 months matrix of monthly log returns ──
type SymData
    matrix<float> data
    float         logM  = 0.0
    int           cnt   = 0
    bool          valid = false
 
var array<SymData> syms = array.new<SymData>()
if bar_index == 0
    for k = 0 to 9
        syms.push(SymData.new(matrix.new<float>(0, 12, na)))
 
bool newMonth = bar_index > 0 and month != month[1]
bool newYear  = bar_index == 0 or year != year[1]
 
for [i, s] in syms
    if newMonth
        int lr = s.data.rows() - 1
        if lr >= 0
            s.data.set(lr, month[1] - 1, s.valid and s.cnt >= 10 ? s.logM : na)
        s.logM  := 0.0
        s.cnt   := 0
        s.valid := true                     // first (partial) month of history is discarded
    if newYear
        s.data.add_row(s.data.rows(), array.new<float>(12, na))
        if s.data.rows() > yearsBack + 1
            s.data.remove_row(0)
    float r = rets.get(i)
    if not na(r)
        s.logM += math.log(1 + r)
        s.cnt  += 1
 
// ── Stats for one month: years, positives, mean % ──
monthStats(SymData s, int m, bool dt) =>
    int   n   = 0
    int   up  = 0
    float sum = 0.0
    int rows = s.data.rows()
    if rows > 0
        for i = 0 to rows - 1
            float v = s.data.get(i, m)
            if not na(v)
                float tot = na
                if dt                               // detrending needs the full year
                    float t    = 0.0
                    bool  full = true
                    for k = 0 to 11
                        float x = s.data.get(i, k)
                        if na(x)
                            full := false
                            break
                        t += x
                    tot := full ? t : na
                if not dt or not na(tot)
                    float lv = dt ? v - tot / 12.0 : v
                    n   += 1
                    sum += (math.exp(lv) - 1) * 100
                    if lv > 0
                        up += 1
    [n, up, n > 0 ? sum / n : na]
 
heatCol(float h) =>
    h >= 50 ? color.from_gradient(h, 50, 80, color.new(#3a3a3a, 0), color.new(#1b8a3a, 0)) :
              color.from_gradient(h, 20, 50, color.new(#b02a2a, 0), color.new(#3a3a3a, 0))
 
// ── Table ──
pos = posIn == "Middle" ? position.middle_center : posIn == "Bottom right" ? position.bottom_right : position.top_right
sz  = txtSize == "Tiny" ? size.tiny : txtSize == "Normal" ? size.normal : size.small
var table tbl = table.new(pos, 14, 12, bgcolor = color.new(color.black, 10), border_color = color.new(color.white, 85), border_width = 1)
var array<string> mNames = array.from("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
 
if barstate.islast
    tbl.cell(0, 0, detrend ? "vs trend" : "% years up", text_color = color.white, text_size = sz)
    for m = 0 to 11
        bool cur = m == month - 1
        tbl.cell(m + 1, 0, mNames.get(m), text_color = cur ? color.black : color.white,
                 bgcolor = cur ? color.orange : na, text_size = sz)
    tbl.cell(13, 0, "Years", text_color = color.white, text_size = sz)
 
    bool anyCrypto = false
    for [i, s] in syms
        if cryp.get(i) == true
            anyCrypto := true
        int maxN = 0
        tbl.cell(0, i + 1, shortName(names.get(i)), text_color = color.white, text_size = sz, text_halign = text.align_left)
        for m = 0 to 11
            [n, up, avg] = monthStats(s, m, detrend)
            maxN := math.max(maxN, n)
            if n >= 5
                float hit  = float(up) / n * 100
                float z    = (up - n * 0.5) / math.sqrt(n * 0.25)
                string txt = str.tostring(hit, "#") + "%" + (math.abs(z) >= 1.645 ? "*" : "")
                if showMean and not na(avg)
                    txt += "\n" + (avg >= 0 ? "+" : "") + str.tostring(avg, "0.0") + "%"
                tbl.cell(m + 1, i + 1, txt, text_color = color.white, bgcolor = heatCol(hit), text_size = sz)
            else
                tbl.cell(m + 1, i + 1, "-", text_color = color.gray, text_size = sz)
        tbl.cell(13, i + 1, str.tostring(maxN), text_color = color.white, text_size = sz)
 
    if anyCrypto and syminfo.type != "crypto"
        tbl.cell(0, 11, "Warning: crypto in the list. Load this heatmap on a crypto chart (e.g. BTC) so weekend moves are not lost.",
                 text_color = color.yellow, text_size = sz, text_halign = text.align_left)
        tbl.merge_cells(0, 11, 13, 11)

← 返回列表