Segment Momentum (3 Votes)

andricechristian · strategy · 212 行 · 点赞 5 · TradingView 原页

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

Pine Script

//@version=6
strategy("Segment Momentum (3 Votes)", overlay=true,
     initial_capital=10000,
     commission_type=strategy.commission.percent, commission_value=0.1,
     slippage=0, margin_long=100, margin_short=100,
     process_orders_on_close=false)
// Costs: 0.1% per side covers fees + slippage as a PERCENT. Tick-based slippage is off on purpose:
// on early BTC prices ($0.05-$1) a 2-tick slippage at a 0.01 tick is 2-40% per fill.
 
//==================== INPUTS ====================//
barsPerMonth = input.int(21, "Bars per Month", minval=0, group="Horizons", tooltip="Sets the segment lengths only (3/6/12 x this). 21 = 63/126/252 bars. 0 = auto (30 on crypto, 21 otherwise), which makes crypto signals slower. Sharpe/Sortino annualisation is measured from the data, not from this input.")
mLen1        = input.int(3,  "Segment 1 End (months)", minval=1, group="Horizons", tooltip="Segment 1 = return from now back to this many months ago.")
mLen2        = input.int(6,  "Segment 2 End (months)", minval=2, group="Horizons", tooltip="Segment 2 = return from Segment 1 End back to this.")
mLen3        = input.int(12, "Segment 3 End (months)", minval=3, group="Horizons", tooltip="Segment 3 = return from Segment 2 End back to this.")
 
voteScale    = input.float(1.73, "Vote Scaling (FDM)", step=0.01, minval=1.0, maxval=3.0, group="Sizing", tooltip="Each positive segment = 33.3% x this. 1.73 = sqrt(3), assumes the 3 segments are uncorrelated: 0/3 = flat, 1/3 = 58%, 2/3 and 3/3 = capped. Set 1.0 for a plain 0/33/67/100 ladder. Note: no vol targeting here, so this only reshapes the vote-to-exposure mapping, it is not a full Carver FDM.")
maxExposure  = input.float(98.0, "Max Total Exposure (% equity)", step=1.0, minval=1, maxval=100, group="Sizing", tooltip="Hard cap. Kept below 100% because size is set on the close and filled at the next open: a gap up at 100% would cost more than the equity you have.")
 
useMaFilter  = input.bool(true, "Halve Exposure Below Daily MA", group="Trend Filter", tooltip="Below the daily MA, the whole vote ladder is multiplied by the scale below. Default: 0/58/98/98% above -> 0/29/49/49% below.")
maLen        = input.int(200, "Daily MA Length", minval=1, group="Trend Filter")
belowScale   = input.float(0.5, "Exposure Scale Below MA", step=0.05, minval=0.0, maxval=1.0, group="Trend Filter")
 
startDate    = input.time(timestamp("01 Jan 2006 00:00"), "Start Date", group="Backtest")
endDate      = input.time(timestamp("31 Dec 2170 23:59"), "End Date", group="Backtest")
 
showEquity   = input.bool(true, "Show Equity Multiple", group="Display")
eqCol        = input.color(color.black, "Equity Text Color", group="Display")
showStats    = input.bool(true, "Show Stats Table", group="Display")
 
// Stats colour thresholds (higher = better for all coloured rows)
SHARPE_GOOD  = 1.75
SHARPE_BAD   = 1.0
SORTINO_GOOD = 2.0
SORTINO_BAD  = 1.25
DD_GOOD      = -15.0
DD_BAD       = -35.0
 
//==================== VALIDATION ====================//
if barstate.isfirst and (mLen1 >= mLen2 or mLen2 >= mLen3)
    runtime.error("Segment ends must be increasing: Segment 1 < Segment 2 < Segment 3.")
 
//==================== SIGNALS ====================//
bpm  = barsPerMonth > 0 ? barsPerMonth : syminfo.type == "crypto" ? 30 : 21
len1 = mLen1 * bpm
len2 = mLen2 * bpm
len3 = mLen3 * bpm
 
// Non-overlapping segments: 0-3M, 3-6M, 6-12M (defaults)
seg1 = close / close[len1] - 1
seg2 = close[len1] / close[len2] - 1
seg3 = close[len2] / close[len3] - 1
 
// Daily MA (works on any chart timeframe; on a daily chart this is just ta.sma(close, maLen))
dailyMA = request.security(syminfo.tickerid, "D", ta.sma(close, maLen), lookahead=barmerge.lookahead_off)
belowMA = useMaFilter and close < dailyMA
 
// Warm-up gate: only trade once the longest segment (and the MA, if used) exists
ready = not na(close[len3]) and (not useMaFilter or not na(dailyMA))
score = (seg1 > 0 ? 1 : 0) + (seg2 > 0 ? 1 : 0) + (seg3 > 0 ? 1 : 0)
 
inDateRange = time >= startDate and time < endDate
active      = inDateRange and ready
 
//==================== SIZING ====================//
SLEEVE   = 100.0 / 3.0
allocPct = math.min(score * SLEEVE * voteScale, maxExposure) * (belowMA ? belowScale : 1.0)
 
//==================== ENTRIES & EXITS ====================//
// Target is recomputed only when the allocation changes (no drift rebalancing),
// and once on the first active bar (lastAlloc reset to -1 when inactive).
// Signals on the bar close, fills on the next bar's open.
var float targetQty  = 0.0
var float lastAlloc  = -1.0
var float rebalances = 0.0
 
if not active
    targetQty := 0.0
    lastAlloc := -1.0
else if allocPct != lastAlloc
    targetQty := allocPct > 0 ? strategy.equity * allocPct / 100.0 / close : 0.0
    lastAlloc := allocPct
 
delta    = targetQty - strategy.position_size
minTrade = strategy.equity * 0.001 / close   // ignore adjustments smaller than 0.1% of equity
 
if targetQty == 0 and strategy.position_size != 0
    strategy.close_all(comment="Flat " + str.tostring(score) + "/3")
    rebalances += 1
else if targetQty > 0 and math.abs(delta) >= minTrade
    strategy.order("Rebal", delta > 0 ? strategy.long : strategy.short, qty=math.abs(delta),
         comment=(delta > 0 ? "Buy " : "Sell ") + str.tostring(score) + "/3" + (belowMA ? " <MA" : ""))
    rebalances += 1
 
//==================== STATS TRACKING (every bar) ====================//
// Equity-curve stats only. TradingView's trade list splits partial
// rebalances into FIFO "trades", so win rate / profit factor are not meaningful here.
eq = strategy.equity
 
var float startEq     = na
var int   startTime   = na
var float peakEq      = na
var float maxDD       = 0.0
var float nRet        = 0.0
var float sumR        = 0.0
var float sumR2       = 0.0
var float sumDown2    = 0.0
var float barsActive  = 0.0
var float barsInMkt   = 0.0
var float sumExposure = 0.0
 
if active
    if na(startEq)
        startEq   := eq
        startTime := time
        peakEq    := eq
    else
        r = eq / eq[1] - 1
        nRet     += 1
        sumR     += r
        sumR2    += r * r
        sumDown2 += math.pow(math.min(r, 0.0), 2)   // downside deviation measured around 0, not demeaned
    peakEq      := math.max(peakEq, eq)
    maxDD       := math.min(maxDD, eq / peakEq - 1)
    barsActive  += 1
    barsInMkt   += strategy.position_size > 0 ? 1 : 0
    sumExposure += strategy.position_size * close / eq
 
// BUY & HOLD benchmark over the same period (from the first active bar, no costs)
var float bhStart  = na
var float bhPeak   = na
var float bhMaxDD  = 0.0
var float bhN      = 0.0
var float bhSumR   = 0.0
var float bhSumR2  = 0.0
var float bhDown2  = 0.0
if active
    if na(bhStart)
        bhStart := close
        bhPeak  := close
    else
        br = close / close[1] - 1
        bhN     += 1
        bhSumR  += br
        bhSumR2 += br * br
        bhDown2 += math.pow(math.min(br, 0.0), 2)
    bhPeak  := math.max(bhPeak, close)
    bhMaxDD := math.min(bhMaxDD, close / bhPeak - 1)
 
//==================== PLOTS ====================//
// Background shade = number of positive segments (darker = more invested)
bgcolor(not active ? na : score == 3 ? color.new(#43A047, 75) : score == 2 ? color.new(#43A047, 85) : score == 1 ? color.new(#43A047, 93) : na, title="Vote Score")
 
plot(useMaFilter ? dailyMA : na, "Daily MA", color=color.new(color.orange, 0), linewidth=2)
 
//==================== TABLES ====================//
// Drawn on every bar (cheap: stats are running sums, no trade loops).
// White / black scheme. Graded values (Sharpe, Sortino, Max DD) get green/red text.
TBL_BG   = color.white
TBL_TXT  = color.black
TBL_LINE = color.black
TXT_GOOD = color.new(#1B7F2A, 0)
TXT_BAD  = color.new(#C62828, 0)
 
gradeColor(val, good, bad) =>
    na(val) ? TBL_TXT : val >= good ? TXT_GOOD : val <= bad ? TXT_BAD : TBL_TXT
 
// Annualisation measured from the data: actual return bars per calendar year
// (~365 for crypto, ~252 for stocks on daily bars, ~52 on weekly)
years   = na(startTime) ? na : (time - startTime) / (365.25 * 24 * 60 * 60 * 1000)
annF    = years > 0 ? nRet / years : na
mean    = nRet > 0 ? sumR / nRet : na
sd      = nRet > 1 ? math.sqrt(math.max(sumR2 / nRet - mean * mean, 0.0)) : na
downDev = nRet > 0 ? math.sqrt(sumDown2 / nRet) : na
sharpe  = sd > 0 ? mean / sd * math.sqrt(annF) : na
sortino = downDev > 0 ? mean / downDev * math.sqrt(annF) : na
annVol  = sd * math.sqrt(annF)
cagr    = years > 0 ? math.pow(eq / startEq, 1.0 / years) - 1 : na
inMkt   = barsActive > 0 ? barsInMkt / barsActive : na
avgExp  = barsActive > 0 ? sumExposure / barsActive : na
ddPct   = maxDD * 100
 
bhMean    = bhN > 0 ? bhSumR / bhN : na
bhSd      = bhN > 1 ? math.sqrt(math.max(bhSumR2 / bhN - bhMean * bhMean, 0.0)) : na
bhDownDev = bhN > 0 ? math.sqrt(bhDown2 / bhN) : na
bhSharpe  = bhSd > 0 ? bhMean / bhSd * math.sqrt(annF) : na
bhSortino = bhDownDev > 0 ? bhMean / bhDownDev * math.sqrt(annF) : na
bhVol     = bhSd * math.sqrt(annF)
bhCagr    = years > 0 ? math.pow(close / bhStart, 1.0 / years) - 1 : na
bhDDPct   = bhMaxDD * 100
 
var table eqBox      = table.new(position.top_right, 2, 1, bgcolor=TBL_BG, frame_color=TBL_LINE, frame_width=1, border_color=TBL_LINE, border_width=1)
var table statsTable = table.new(position.middle_right, 3, 9, bgcolor=TBL_BG, frame_color=TBL_LINE, frame_width=1, border_color=TBL_LINE, border_width=1)
 
statRow(row, label, txt, col, bhTxt, bhCol) =>
    table.cell(statsTable, 0, row, label, bgcolor=TBL_BG, text_color=TBL_TXT, text_halign=text.align_left)
    table.cell(statsTable, 1, row, txt, bgcolor=TBL_BG, text_color=col, text_halign=text.align_right)
    table.cell(statsTable, 2, row, bhTxt, bgcolor=TBL_BG, text_color=bhCol, text_halign=text.align_right)
 
if showEquity
    table.cell(eqBox, 0, 0, "Equity", bgcolor=TBL_BG, text_color=TBL_TXT)
    table.cell(eqBox, 1, 0, str.tostring(eq / strategy.initial_capital, "#.##") + "x", bgcolor=TBL_BG, text_color=eqCol)
 
if showStats
    statRow(0, "Metric",         "Strategy",                               TBL_TXT, "Buy & Hold", TBL_TXT)
    statRow(1, "CAGR",           str.tostring(cagr * 100, "#.##") + "%",   TBL_TXT, str.tostring(bhCagr * 100, "#.##") + "%", TBL_TXT)
    statRow(2, "Ann. Vol",       str.tostring(annVol * 100, "#.##") + "%", TBL_TXT, str.tostring(bhVol * 100, "#.##") + "%",  TBL_TXT)
    statRow(3, "Sharpe",         str.tostring(sharpe, "#.##"),             gradeColor(sharpe, SHARPE_GOOD, SHARPE_BAD),    str.tostring(bhSharpe, "#.##"),  gradeColor(bhSharpe, SHARPE_GOOD, SHARPE_BAD))
    statRow(4, "Sortino",        str.tostring(sortino, "#.##"),            gradeColor(sortino, SORTINO_GOOD, SORTINO_BAD), str.tostring(bhSortino, "#.##"), gradeColor(bhSortino, SORTINO_GOOD, SORTINO_BAD))
    statRow(5, "Max DD",         str.tostring(ddPct, "#.##") + "%",        gradeColor(ddPct, DD_GOOD, DD_BAD),             str.tostring(bhDDPct, "#.##") + "%", gradeColor(bhDDPct, DD_GOOD, DD_BAD))
    statRow(6, "Time in Market", str.tostring(inMkt * 100, "#.#") + "%",   TBL_TXT, "100%", TBL_TXT)
    statRow(7, "Avg Exposure",   str.tostring(avgExp * 100, "#.#") + "%",  TBL_TXT, "100%", TBL_TXT)
    statRow(8, "Rebalances",     str.tostring(rebalances, "#"),            TBL_TXT, "1", TBL_TXT)

← 返回列表