ETF Sector Rotation (Sector Selector Style)

Retired_Kopite · study · 181 行 · 点赞 8 · TradingView 原页

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

Pine Script

//@version=6
indicator("ETF Sector Rotation (Sector Selector Style)", shorttitle="Sector Rotation", overlay=false, max_labels_count=100)
 
// ─────────────────────────────────────────────────────────────
// Ranks the 11 SPDR sector ETFs by momentum and plots the rank
// of each sector over time (rank 1 at the top, rank 11 at the
// bottom), like the weekly "Sector Selector" bump chart.
// Top-N sectors are drawn as thick lines with markers.
// Best used on a Weekly chart.
// ─────────────────────────────────────────────────────────────
 
// ── Inputs ───────────────────────────────────────────────────
GRP1 = "Ranking"
tf       = input.timeframe("W", "Ranking Timeframe", group=GRP1)
lookback = input.int(13, "Momentum Lookback (bars)", minval=3, group=GRP1)
method   = input.string("ROC", "Score Method", options=["ROC", "Multi-Period", "Price vs SMA"], group=GRP1,
     tooltip="ROC: rate of change over the lookback.\nMulti-Period: average of ROC over lookback/3, lookback and lookback*2.\nPrice vs SMA: % distance of price from its SMA.")
topN     = input.int(3, "Highlight Top N Sectors", minval=1, maxval=11, group=GRP1)
 
GRP2 = "Display"
showTable  = input.bool(true, "Show Ranking Table", group=GRP2)
showLabels = input.bool(true, "Show Right-Edge Labels", group=GRP2)
tblPos     = input.string("Top Right", "Table Position", options=["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group=GRP2)
 
GRP3 = "Sector ETFs"
sym1  = input.symbol("AMEX:XLU",  "Utilities",        group=GRP3)
sym2  = input.symbol("AMEX:XLRE", "Real Estate",      group=GRP3)
sym3  = input.symbol("AMEX:XLI",  "Industrials",      group=GRP3)
sym4  = input.symbol("AMEX:XLY",  "Discretionary",    group=GRP3)
sym5  = input.symbol("AMEX:XLP",  "Staples",          group=GRP3)
sym6  = input.symbol("AMEX:XLK",  "Technology",       group=GRP3)
sym7  = input.symbol("AMEX:XLF",  "Financials",       group=GRP3)
sym8  = input.symbol("AMEX:XLB",  "Materials",        group=GRP3)
sym9  = input.symbol("AMEX:XLC",  "Communications",   group=GRP3)
sym10 = input.symbol("AMEX:XLV",  "Health Care",      group=GRP3)
sym11 = input.symbol("AMEX:XLE",  "Energy",           group=GRP3)
 
// ── Constants ────────────────────────────────────────────────
var names = array.from("Utilities", "Real Estate", "Industrials", "Discretionary", "Staples",
     "Technology", "Financials", "Materials", "Communications", "Health Care", "Energy")
 
var cols = array.from(
     color.rgb(0, 200, 0),      // Utilities
     color.rgb(30, 144, 255),   // Real Estate
     color.rgb(255, 120, 0),    // Industrials
     color.rgb(150, 40, 200),   // Discretionary
     color.rgb(160, 160, 160),  // Staples
     color.rgb(255, 105, 180),  // Technology
     color.rgb(240, 200, 0),    // Financials
     color.rgb(0, 190, 190),    // Materials
     color.rgb(140, 80, 30),    // Communications
     color.rgb(110, 140, 50),   // Health Care
     color.rgb(230, 20, 20))    // Energy
 
// ── Scoring ──────────────────────────────────────────────────
f_score() =>
    n3   = math.max(1, int(math.round(lookback / 3.0)))
    roc1 = ta.roc(close, lookback)
    roc2 = (ta.roc(close, n3) + ta.roc(close, lookback) + ta.roc(close, lookback * 2)) / 3.0
    sma1 = (close / ta.sma(close, lookback) - 1.0) * 100.0
    method == "ROC" ? roc1 : method == "Multi-Period" ? roc2 : sma1
 
f_ticker(s) =>
    parts = str.split(s, ":")
    parts.size() > 1 ? parts.get(1) : s
 
s1  = request.security(sym1,  tf, f_score(), gaps=barmerge.gaps_off)
s2  = request.security(sym2,  tf, f_score(), gaps=barmerge.gaps_off)
s3  = request.security(sym3,  tf, f_score(), gaps=barmerge.gaps_off)
s4  = request.security(sym4,  tf, f_score(), gaps=barmerge.gaps_off)
s5  = request.security(sym5,  tf, f_score(), gaps=barmerge.gaps_off)
s6  = request.security(sym6,  tf, f_score(), gaps=barmerge.gaps_off)
s7  = request.security(sym7,  tf, f_score(), gaps=barmerge.gaps_off)
s8  = request.security(sym8,  tf, f_score(), gaps=barmerge.gaps_off)
s9  = request.security(sym9,  tf, f_score(), gaps=barmerge.gaps_off)
s10 = request.security(sym10, tf, f_score(), gaps=barmerge.gaps_off)
s11 = request.security(sym11, tf, f_score(), gaps=barmerge.gaps_off)
 
scores = array.from(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11)
syms   = array.from(sym1, sym2, sym3, sym4, sym5, sym6, sym7, sym8, sym9, sym10, sym11)
 
// ── Ranking (1 = strongest) ──────────────────────────────────
ranks = array.new_float(11, na)
for i = 0 to 10
    si = scores.get(i)
    if not na(si)
        r = 1
        for j = 0 to 10
            if j != i
                sj = scores.get(j)
                if not na(sj) and (sj > si or (sj == si and j < i))
                    r += 1
        ranks.set(i, r)
 
// Plot value: invert so rank 1 sits at the top (11) and rank 11 at the bottom (1)
f_y(i) =>
    r = ranks.get(i)
    na(r) ? na : 12.0 - r
 
f_top(i) =>
    r = ranks.get(i)
    not na(r) and r <= topN
 
y1  = f_y(0),  y2  = f_y(1),  y3  = f_y(2),  y4  = f_y(3),  y5  = f_y(4),  y6 = f_y(5)
y7  = f_y(6),  y8  = f_y(7),  y9  = f_y(8),  y10 = f_y(9),  y11 = f_y(10)
 
// ── Plots: thin line for every sector, thick + markers for top N ──
plot(y1,  "Utilities",      color=color.new(cols.get(0),  70), linewidth=1)
plot(y2,  "Real Estate",    color=color.new(cols.get(1),  70), linewidth=1)
plot(y3,  "Industrials",    color=color.new(cols.get(2),  70), linewidth=1)
plot(y4,  "Discretionary",  color=color.new(cols.get(3),  70), linewidth=1)
plot(y5,  "Staples",        color=color.new(cols.get(4),  70), linewidth=1)
plot(y6,  "Technology",     color=color.new(cols.get(5),  70), linewidth=1)
plot(y7,  "Financials",     color=color.new(cols.get(6),  70), linewidth=1)
plot(y8,  "Materials",      color=color.new(cols.get(7),  70), linewidth=1)
plot(y9,  "Communications", color=color.new(cols.get(8),  70), linewidth=1)
plot(y10, "Health Care",    color=color.new(cols.get(9),  70), linewidth=1)
plot(y11, "Energy",         color=color.new(cols.get(10), 70), linewidth=1)
 
plot(f_top(0)  ? y1  : na, "Utilities (Top)",      color=cols.get(0),  linewidth=4, style=plot.style_linebr)
plot(f_top(1)  ? y2  : na, "Real Estate (Top)",    color=cols.get(1),  linewidth=4, style=plot.style_linebr)
plot(f_top(2)  ? y3  : na, "Industrials (Top)",    color=cols.get(2),  linewidth=4, style=plot.style_linebr)
plot(f_top(3)  ? y4  : na, "Discretionary (Top)",  color=cols.get(3),  linewidth=4, style=plot.style_linebr)
plot(f_top(4)  ? y5  : na, "Staples (Top)",        color=cols.get(4),  linewidth=4, style=plot.style_linebr)
plot(f_top(5)  ? y6  : na, "Technology (Top)",     color=cols.get(5),  linewidth=4, style=plot.style_linebr)
plot(f_top(6)  ? y7  : na, "Financials (Top)",     color=cols.get(6),  linewidth=4, style=plot.style_linebr)
plot(f_top(7)  ? y8  : na, "Materials (Top)",      color=cols.get(7),  linewidth=4, style=plot.style_linebr)
plot(f_top(8)  ? y9  : na, "Communications (Top)", color=cols.get(8),  linewidth=4, style=plot.style_linebr)
plot(f_top(9)  ? y10 : na, "Health Care (Top)",    color=cols.get(9),  linewidth=4, style=plot.style_linebr)
plot(f_top(10) ? y11 : na, "Energy (Top)",         color=cols.get(10), linewidth=4, style=plot.style_linebr)
 
// Reference lines for rank levels
hline(11, "Rank 1",  color=color.new(color.gray, 85))
hline(6,  "Rank 6",  color=color.new(color.gray, 85))
hline(1,  "Rank 11", color=color.new(color.gray, 85))
 
// ── Right-edge labels (rank + ticker) ────────────────────────
var array<label> lbls = array.new<label>()
if barstate.islast and showLabels
    for l in lbls
        label.delete(l)
    lbls.clear()
    for i = 0 to 10
        r = ranks.get(i)
        if not na(r)
            lbls.push(label.new(bar_index + 1, 12.0 - r, str.format("{0} {1}", int(r), f_ticker(syms.get(i))),
                 style=label.style_label_left, color=color.new(cols.get(i), 15), textcolor=color.white, size=size.small))
 
// ── Ranking table ────────────────────────────────────────────
tPos = switch tblPos
    "Top Left"     => position.top_left
    "Bottom Right" => position.bottom_right
    "Bottom Left"  => position.bottom_left
    => position.top_right
 
var table tbl = table.new(tPos, 4, 12, bgcolor=color.new(color.black, 25), border_width=1, border_color=color.new(color.gray, 60))
 
if barstate.islast and showTable
    table.cell(tbl, 0, 0, "#",      text_color=color.white, text_size=size.small, bgcolor=color.new(color.gray, 40))
    table.cell(tbl, 1, 0, "Sector", text_color=color.white, text_size=size.small, bgcolor=color.new(color.gray, 40))
    table.cell(tbl, 2, 0, "ETF",    text_color=color.white, text_size=size.small, bgcolor=color.new(color.gray, 40))
    table.cell(tbl, 3, 0, "Score",  text_color=color.white, text_size=size.small, bgcolor=color.new(color.gray, 40))
    for k = 1 to 11
        idx = -1
        for i = 0 to 10
            if ranks.get(i) == k
                idx := i
        if idx >= 0
            bg = k <= topN ? color.new(cols.get(idx), 55) : na
            table.cell(tbl, 0, k, str.tostring(k), text_color=color.white, text_size=size.small, bgcolor=bg)
            table.cell(tbl, 1, k, names.get(idx), text_color=cols.get(idx), text_size=size.small, text_halign=text.align_left, bgcolor=bg)
            table.cell(tbl, 2, k, f_ticker(syms.get(idx)), text_color=color.white, text_size=size.small, bgcolor=bg)
            table.cell(tbl, 3, k, str.tostring(scores.get(idx), "#.##"), text_color=color.white, text_size=size.small, bgcolor=bg)
 
// ── Alert: leader changed ────────────────────────────────────
leader = -1
for i = 0 to 10
    if ranks.get(i) == 1
        leader := i
 
alertcondition(leader != leader[1] and leader >= 0, "New Sector Leader", "The #1 ranked sector has changed.")

← 返回列表