本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Konscio
// ETF Rotation (momentum / volatility) – educational, open-source indicator.
// Each month, ranks up to 4 ETFs by a composite momentum (average of 1, 3, 6 and 12-month returns)
// divided by 252-day annualised volatility, shows the top-ranked ETF in a table and plots a
// hypothetical equity curve rescaled onto the chart price. Optional regime filter (off by default). Not financial advice; hypothetical results only.
//@version=6
indicator("ETF Rotation - Momentum / Volatility", shorttitle="ETF Rotation", overlay=true)
// ——— Inputs ———
string etf1 = input.symbol("EURONEXT:ESE", "ETF 1", group="ETF universe")
string etf2 = input.symbol("EURONEXT:PUST", "ETF 2", group="ETF universe")
string etf3 = input.symbol("EURONEXT:MEUD", "ETF 3", group="ETF universe")
string etf4 = input.symbol("EURONEXT:PAEEM", "ETF 4", group="ETF universe")
int volLen = input.int(252, "Volatility lookback (days)", minval=20, group="Scoring")
bool useRegime = input.bool(false, "Enable regime filter (benchmark below its moving average -> benchmark)", group="Regime filter (optional)", tooltip="Off by default. When on, if the benchmark closes below its moving average at the monthly rotation, the strategy holds the benchmark instead of the best-scored ETF.")
string benchSym = input.symbol("EURONEXT:CW8", "Benchmark ETF (e.g. MSCI World)", group="Regime filter (optional)")
int regimeLen = input.int(200, "Benchmark moving average length (days)", minval=20, group="Regime filter (optional)")
int anchorTime = input.time(timestamp("10 Jun 2019 00:00 +0000"), "Equity curve anchor date", group="Equity curve", tooltip="The curve is rescaled to match the chart price on this date.")
string table1PosInput = input.string("Top right", "ETF of the month table - position", options=["Top left", "Top center", "Top right", "Middle left", "Middle center", "Middle right", "Bottom left", "Bottom center", "Bottom right"], group="Tables")
string table2PosInput = input.string("Bottom center", "Legend table - position", options=["Top left", "Top center", "Top right", "Middle left", "Middle center", "Middle right", "Bottom left", "Bottom center", "Bottom right"], group="Tables")
string tableSizeInput = input.string("Small", "Table size", options=["Tiny", "Small", "Medium", "Large", "Extra-large"], group="Tables")
// Needs a Daily chart (252 trading days/year annualisation, daily compounding)
bool isDaily = timeframe.isdaily and timeframe.multiplier == 1
bool doShow = isDaily
getPos(s) => s == "Top left" ? position.top_left : s == "Top center" ? position.top_center : s == "Top right" ? position.top_right : s == "Middle left" ? position.middle_left : s == "Middle center" ? position.middle_center : s == "Middle right" ? position.middle_right : s == "Bottom left" ? position.bottom_left : s == "Bottom center" ? position.bottom_center : position.bottom_right
tableTextSize = tableSizeInput == "Tiny" ? size.tiny : tableSizeInput == "Small" ? size.small : tableSizeInput == "Medium" ? size.normal : tableSizeInput == "Large" ? size.large : size.huge
// ——— Month-end closes (0, 1, 3, 6, 12 months back) for each ETF ———
fwdM(id, n) => request.security(id, "M", close[n], lookahead=barmerge.lookahead_off)
fwdM0(id) => request.security(id, "M", close, lookahead=barmerge.lookahead_off)
float m0_1 = fwdM0(etf1)
float m1_1 = fwdM(etf1, 1)
float m3_1 = fwdM(etf1, 3)
float m6_1 = fwdM(etf1, 6)
float m12_1 = fwdM(etf1, 12)
float m0_2 = fwdM0(etf2)
float m1_2 = fwdM(etf2, 1)
float m3_2 = fwdM(etf2, 3)
float m6_2 = fwdM(etf2, 6)
float m12_2 = fwdM(etf2, 12)
float m0_3 = fwdM0(etf3)
float m1_3 = fwdM(etf3, 1)
float m3_3 = fwdM(etf3, 3)
float m6_3 = fwdM(etf3, 6)
float m12_3 = fwdM(etf3, 12)
float m0_4 = fwdM0(etf4)
float m1_4 = fwdM(etf4, 1)
float m3_4 = fwdM(etf4, 3)
float m6_4 = fwdM(etf4, 6)
float m12_4 = fwdM(etf4, 12)
retM(c, cLag) => (math.abs(cLag) > 1e-10) ? (c / cLag - 1.0) : 0.0
// Composite momentum = average of the 1, 3, 6 and 12-month returns
float mom1 = 0.25 * (retM(m0_1, m1_1) + retM(m0_1, m3_1) + retM(m0_1, m6_1) + retM(m0_1, m12_1))
float mom2 = 0.25 * (retM(m0_2, m1_2) + retM(m0_2, m3_2) + retM(m0_2, m6_2) + retM(m0_2, m12_2))
float mom3 = 0.25 * (retM(m0_3, m1_3) + retM(m0_3, m3_3) + retM(m0_3, m6_3) + retM(m0_3, m12_3))
float mom4 = 0.25 * (retM(m0_4, m1_4) + retM(m0_4, m3_4) + retM(m0_4, m6_4) + retM(m0_4, m12_4))
// Annualised volatility
float vol1 = request.security(etf1, timeframe.period, ta.stdev(ta.change(close) / math.max(close[1], 1e-10), volLen) * math.sqrt(252), lookahead=barmerge.lookahead_off)
float vol2 = request.security(etf2, timeframe.period, ta.stdev(ta.change(close) / math.max(close[1], 1e-10), volLen) * math.sqrt(252), lookahead=barmerge.lookahead_off)
float vol3 = request.security(etf3, timeframe.period, ta.stdev(ta.change(close) / math.max(close[1], 1e-10), volLen) * math.sqrt(252), lookahead=barmerge.lookahead_off)
float vol4 = request.security(etf4, timeframe.period, ta.stdev(ta.change(close) / math.max(close[1], 1e-10), volLen) * math.sqrt(252), lookahead=barmerge.lookahead_off)
// Score = momentum / volatility
safeVol(v) => math.max(v, 1e-6)
float score1 = mom1 / safeVol(vol1)
float score2 = mom2 / safeVol(vol2)
float score3 = mom3 / safeVol(vol3)
float score4 = mom4 / safeVol(vol4)
bool newMonth = ta.change(month(time)) != 0
// Optional regime filter: benchmark close vs its simple moving average (previous day values)
float benchClose = request.security(benchSym, timeframe.period, close, lookahead=barmerge.lookahead_off)
float benchMa = request.security(benchSym, timeframe.period, ta.sma(close, regimeLen), lookahead=barmerge.lookahead_off)
bool riskOff = useRegime and not na(benchMa[1]) and benchClose[1] < benchMa[1]
// Selection: best score, held until next month (or the benchmark when the optional filter is risk-off)
var int selectedIdx = 0
var string selectedName = "-"
if newMonth
float best = math.max(math.max(score1, score2), math.max(score3, score4))
if riskOff
selectedIdx := 5
selectedName := syminfo.ticker(benchSym)
else if best == score1
selectedIdx := 1
selectedName := syminfo.ticker(etf1)
else if best == score2
selectedIdx := 2
selectedName := syminfo.ticker(etf2)
else if best == score3
selectedIdx := 3
selectedName := syminfo.ticker(etf3)
else
selectedIdx := 4
selectedName := syminfo.ticker(etf4)
// ========== EQUITY CURVE ==========
// Compounded from the first bar, then rescaled so the curve passes through the chart price at the anchor date.
float c1 = request.security(etf1, timeframe.period, close, lookahead=barmerge.lookahead_off)
float c2 = request.security(etf2, timeframe.period, close, lookahead=barmerge.lookahead_off)
float c3 = request.security(etf3, timeframe.period, close, lookahead=barmerge.lookahead_off)
float c4 = request.security(etf4, timeframe.period, close, lookahead=barmerge.lookahead_off)
float closeToday = selectedIdx == 1 ? c1 : selectedIdx == 2 ? c2 : selectedIdx == 3 ? c3 : selectedIdx == 4 ? c4 : selectedIdx == 5 ? benchClose : close
float closeYesterday = selectedIdx == 1 ? c1[1] : selectedIdx == 2 ? c2[1] : selectedIdx == 3 ? c3[1] : selectedIdx == 4 ? c4[1] : selectedIdx == 5 ? benchClose[1] : close[1]
bool anchorBar = (time >= anchorTime) and (bar_index == 0 or na(time[1]) or time[1] < anchorTime)
var float equity = 1.0
if math.abs(closeYesterday) > 1e-10 and not na(closeToday)
equity := equity * (closeToday / closeYesterday)
float anchorEquityVal = ta.valuewhen(anchorBar, equity, 0)
float anchorPriceVal = ta.valuewhen(anchorBar, close, 0)
float equityPlot = (not na(anchorEquityVal) and math.abs(anchorEquityVal) > 1e-10) ? (anchorPriceVal * equity / anchorEquityVal) : float(na)
color colorEtf1 = color.new(#ee2525, 0)
color colorEtf2 = color.new(#FF6D00, 0)
color colorEtf3 = color.new(#00C853, 0)
color colorEtf4 = color.new(#AA00FF, 0)
color colorBench = color.new(color.teal, 0)
color colorBase = color.new(color.gray, 30)
color equityColor = selectedIdx == 1 ? colorEtf1 : selectedIdx == 2 ? colorEtf2 : selectedIdx == 3 ? colorEtf3 : selectedIdx == 4 ? colorEtf4 : selectedIdx == 5 ? colorBench : colorBase
// ——— Display ———
var label errLabel = na
if not doShow and barstate.islast
if not na(errLabel)
label.delete(errLabel)
errLabel := label.new(bar_index, high, "Indicator unavailable\nSwitch the chart to the Daily timeframe.", style=label.style_label_down, color=color.new(color.red, 20), textcolor=color.white, size=size.normal)
else if doShow and not na(errLabel)
label.delete(errLabel)
errLabel := na
var table tbl = table.new(getPos(table1PosInput), 2, 2, bgcolor=color.new(color.black, 85), border_width=1)
if doShow
table.cell(tbl, 0, 0, "ETF of the month", text_color=color.white, text_size=tableTextSize)
table.cell(tbl, 1, 0, selectedName, text_color=color.lime, text_size=tableTextSize)
table.cell(tbl, 0, 1, "Ticker", text_color=color.gray, text_size=tableTextSize)
string tickerStr = selectedIdx == 1 ? etf1 : selectedIdx == 2 ? etf2 : selectedIdx == 3 ? etf3 : selectedIdx == 4 ? etf4 : selectedIdx == 5 ? benchSym : "-"
table.cell(tbl, 1, 1, tickerStr, text_color=color.gray, text_size=tableTextSize)
var table legendTbl = table.new(getPos(table2PosInput), 7, 1, bgcolor=color.new(color.black, 85), border_width=1)
if doShow
table.cell(legendTbl, 0, 0, "Legend", text_color=color.white, text_size=tableTextSize)
table.cell(legendTbl, 1, 0, syminfo.ticker(etf1), bgcolor=colorEtf1, text_color=color.white, text_size=tableTextSize)
table.cell(legendTbl, 2, 0, syminfo.ticker(etf2), bgcolor=colorEtf2, text_color=color.white, text_size=tableTextSize)
table.cell(legendTbl, 3, 0, syminfo.ticker(etf3), bgcolor=colorEtf3, text_color=color.white, text_size=tableTextSize)
table.cell(legendTbl, 4, 0, syminfo.ticker(etf4), bgcolor=colorEtf4, text_color=color.white, text_size=tableTextSize)
table.cell(legendTbl, 5, 0, "Benchmark", bgcolor=colorBench, text_color=color.white, text_size=tableTextSize)
table.cell(legendTbl, 6, 0, "Chart price", bgcolor=colorBase, text_color=color.white, text_size=tableTextSize)
plot(doShow ? equityPlot : na, "Equity curve", color=equityColor, linewidth=2)