ETF Sector Rotation Beta/Stochastic

Retired_Kopite · study · 187 行 · 点赞 9 · TradingView 原页

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

Pine Script

//@version=6
// Rotation Beta/Stochastic (ETF Rotate Lower) - port of thinkorswim "beta_rotation_v2"
// Beta of each sector ETF vs SPX -> Ehlers ESS smoothing -> Stochastic (0..1)
// Includes ranked dashboard (leading sector on top)
indicator("Rotation Beta/Stochastic", shorttitle="ETF Rotate", overlay=false, max_labels_count=100)
 
// ───────── Inputs ─────────
betaLength    = input.int(21, "Beta Length", minval=2)
stochLength   = input.int(34, "Stoch Length", minval=2)
essLength     = input.int(8,  "ESS Filter Length", minval=2)
showBeta      = input.bool(false, "Show Beta (Cyclicals & Technology)")
showOverlay   = input.bool(true,  "Show Right-Edge Labels")
showDash      = input.bool(true,  "Show Ranked Dashboard")
flowLabelStep = input.int(40, "Money-Flow Label Step (bars)", minval=5)
 
refSym = input.symbol("SP:SPX",     "Reference (SPX)")
symY   = input.symbol("AMEX:XLY",   "Cyclicals")
symK   = input.symbol("AMEX:XLK",   "Technology")
symI   = input.symbol("AMEX:XLI",   "Industrials")
symB   = input.symbol("AMEX:XLB",   "Materials")
symE   = input.symbol("AMEX:XLE",   "Energy")
symP   = input.symbol("AMEX:XLP",   "Staples")
symV   = input.symbol("AMEX:XLV",   "HealthCare")
symU   = input.symbol("AMEX:XLU",   "Utilities")
symF   = input.symbol("AMEX:XLF",   "Financials")
 
// ───────── Functions ─────────
f_ret(src) =>
    src[1] == 0 ? 0.0 : (src - src[1]) / src[1] * 100
 
f_beta(secClose, refClose, len) =>
    s = f_ret(secClose)
    r = f_ret(refClose)
    cov = ta.sma(s * r, len) - ta.sma(s, len) * ta.sma(r, len)
    v = ta.variance(r, len)
    v == 0 ? na : cov / v
 
f_ess(price, len) =>
    a0 = math.exp(-math.pi * math.sqrt(2) / len)
    c2 = 2 * a0 * math.cos(math.sqrt(2) * math.pi / len)
    c3 = -a0 * a0
    c1 = 1 - c2 - c3
    f = float(na)
    f := na(price + price[1]) ? nz(f[1]) : c1 * (price + price[1]) / 2 + c2 * nz(f[1]) + c3 * nz(f[2])
    bar_index < len ? price : f
 
f_stoch(d, len) =>
    lo = ta.lowest(d, len)
    hi = ta.highest(d, len)
    hi == lo ? na : (d - lo) / (hi - lo)
 
f_rot(secClose, refClose) =>
    f_stoch(f_ess(f_beta(secClose, refClose, betaLength), essLength), stochLength)
 
f_clamp(v) => v < 0.15 ? 0.0 : v > 0.85 ? 1.0 : v
 
// ───────── Data ─────────
refC = request.security(refSym, timeframe.period, close)
cY = request.security(symY, timeframe.period, close)
cK = request.security(symK, timeframe.period, close)
cI = request.security(symI, timeframe.period, close)
cB = request.security(symB, timeframe.period, close)
cE = request.security(symE, timeframe.period, close)
cP = request.security(symP, timeframe.period, close)
cV = request.security(symV, timeframe.period, close)
cU = request.security(symU, timeframe.period, close)
cF = request.security(symF, timeframe.period, close)
 
// ───────── Colors (hex) ─────────
col1 = #EE82EE
col2 = #5AA078
col3 = #FF00FF
col4 = #00FFFF
col5 = #FFFF00
col6 = #50B446
col7 = #B450B4
col8 = #FFA500
col9 = #FFC0CB
 
// Optional raw betas (calculated every bar, plotted only when enabled)
rawBeta1 = f_beta(cY, refC, betaLength)
rawBeta2 = f_beta(cK, refC, betaLength)
plot(showBeta ? rawBeta1 : na, "Beta Cyclicals",  #EE82EE99)
plot(showBeta ? rawBeta2 : na, "Beta Technology", #5AA07899)
 
// Rotation stochastics
stoch1 = f_rot(cY, refC)
stoch2 = f_rot(cK, refC)
stoch3 = f_rot(cI, refC)
stoch4 = f_rot(cB, refC)
stoch5 = f_rot(cE, refC)
stoch6 = f_rot(cP, refC)
stoch7 = f_rot(cV, refC)
stoch8 = f_rot(cU, refC)
stoch9 = f_rot(cF, refC)
 
plot(stoch1, "Cyclicals",   col1, 2)
plot(stoch2, "Technology",  col2, 4)
plot(stoch3, "Industrials", col3, 4)
plot(stoch4, "Materials",   col4, 2)
plot(stoch5, "Energy",      col5, 1)
plot(stoch6, "Staples",     col6, 2)
plot(stoch7, "HealthCare",  col7, 4)
plot(stoch8, "Utilities",   col8, 2)
plot(stoch9, "Financials",  col9, 2)
 
hline(0, "Zero", #800000, hline.style_dashed, 2)
hline(1, "One",  #006400, hline.style_dashed, 2)
 
// ───────── Labels + dashboard (last bar only) ─────────
var array<label> sectorLbls = array.new<label>(9, na)
var array<label> flowLbls   = array.new<label>(4, na)
 
var table info = table.new(position.top_left, 1, 1)
var table dash = table.new(position.top_right, 4, 10, border_width = 1)
 
if barstate.islast
    // clear old labels
    for a = 0 to 8
        oldSec = array.get(sectorLbls, a)
        if not na(oldSec)
            label.delete(oldSec)
    for b = 0 to 3
        oldFlow = array.get(flowLbls, b)
        if not na(oldFlow)
            label.delete(oldFlow)
 
    vals  = array.from(stoch1, stoch2, stoch3, stoch4, stoch5, stoch6, stoch7, stoch8, stoch9)
    names = array.from("Cyclicals", "Technology", "Industrials", "Materials", "Energy", "Staples", "HealthCare", "Utilities", "Financials")
    cols  = array.from(col1, col2, col3, col4, col5, col6, col7, col8, col9)
 
    // right-edge sector labels (clamped like ToS bubbles)
    if showOverlay
        for c = 0 to 8
            lv = array.get(vals, c)
            if not na(lv)
                lblStyle = label.style_label_up
                if lv > 0.5
                    lblStyle := label.style_label_down
                array.set(sectorLbls, c, label.new(bar_index, f_clamp(lv), array.get(names, c), xloc.bar_index, yloc.price, array.get(cols, c), lblStyle, #000000, size.small))
 
    // MONEY FLOWS IN / OUT banners
    array.set(flowLbls, 0, label.new(bar_index - flowLabelStep,     1.01,  "M O N E Y   F L O W S   I N",  xloc.bar_index, yloc.price, #5A8C05, label.style_label_down, #FFFFFF, size.small))
    array.set(flowLbls, 1, label.new(bar_index - 2 * flowLabelStep, 1.01,  "M O N E Y   F L O W S   I N",  xloc.bar_index, yloc.price, #5A8C05, label.style_label_down, #FFFFFF, size.small))
    array.set(flowLbls, 2, label.new(bar_index - flowLabelStep,     -0.01, "M O N E Y   F L O W S   O U T", xloc.bar_index, yloc.price, #C80A28, label.style_label_up,   #FFFFFF, size.small))
    array.set(flowLbls, 3, label.new(bar_index - 2 * flowLabelStep, -0.01, "M O N E Y   F L O W S   O U T", xloc.bar_index, yloc.price, #C80A28, label.style_label_up,   #FFFFFF, size.small))
 
    // title / timeframe
    table.cell(info, 0, 0, "Rotation Beta/Stochastic (" + str.tostring(betaLength) + "," + str.tostring(stochLength) + ")  |  TF: " + timeframe.period, text_color=#C0C0C0, text_size=size.small)
 
    // ranked dashboard: highest stochastic on top
    if showDash
        sortVals = array.new<float>()
        for d = 0 to 8
            sv = array.get(vals, d)
            float sortKey = -1.0
            if not na(sv)
                sortKey := sv
            array.push(sortVals, sortKey)
        rankIdx = array.sort_indices(sortVals, order.descending)
 
        table.cell(dash, 0, 0, "#",      text_color=#FFFFFF, bgcolor=#2A2E39, text_size=size.small)
        table.cell(dash, 1, 0, "Sector", text_color=#FFFFFF, bgcolor=#2A2E39, text_size=size.small)
        table.cell(dash, 2, 0, "Stoch",  text_color=#FFFFFF, bgcolor=#2A2E39, text_size=size.small)
        table.cell(dash, 3, 0, "Flow",   text_color=#FFFFFF, bgcolor=#2A2E39, text_size=size.small)
 
        for e = 0 to 8
            idx = array.get(rankIdx, e)
            dv  = array.get(vals, idx)
 
            string flowTxt = ""
            color  flowCol = #787B86
            string stochTxt = "n/a"
            if not na(dv)
                stochTxt := str.tostring(dv * 100, "#.0")
                flowTxt := "-"
                if dv > 0.85
                    flowTxt := "IN"
                    flowCol := #26A69A
                if dv < 0.15
                    flowTxt := "OUT"
                    flowCol := #EF5350
 
            table.cell(dash, 0, e + 1, str.tostring(e + 1), text_color=#D1D4DC, bgcolor=#131722, text_size=size.small)
            table.cell(dash, 1, e + 1, array.get(names, idx), text_color=#000000, bgcolor=array.get(cols, idx), text_size=size.small)
            table.cell(dash, 2, e + 1, stochTxt, text_color=#D1D4DC, bgcolor=#131722, text_size=size.small)
            table.cell(dash, 3, e + 1, flowTxt, text_color=flowCol, bgcolor=#131722, text_size=size.small)

← 返回列表