Nonlinear TSMOM * Trend Persistence

mm_mitsuya · study · 144 行 · 点赞 2 · TradingView 原页

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

Pine Script

//@version=6
// ─────────────────────────────────────────────────────────────────────────────
//  Nonlinear TSMOM × Trend Persistence  (NLTSM×TP)
//
//  ① 非線形TSMOM … Moskowitz, Sabbatucci, Tamoni, Uhl (2025) "Nonlinear Time
//     Series Momentum" 式(3)(4)
//       s_t = Σ_{τ<T} r_{t-τ} / (σ̂_{t-1} · √T)      σ̂ = 1年(260本)ローリングボラ
//       f(s) = λ · s / (s² + 1)                       λ ≈ 2.535(s〜N(0,1)で var(f)≈1)
//     |s| = 1 で最大、それ以上は重みが下がる(Ferson & Siegel 2001 の最適ウェイト)
//
//  ② トレンド持続性 … Sepp & Lucic (2026) "The Science and Practice of
//     Trend-Following Systems" 式(2.14)(4.19)
//       z_t = r_t / σ_{t-1}                           σ = EWMA(r²) のボラ
//       期待エッジ ∝ (1-ν)/ν · Σ_{m≥1} ν^m ρ(m)  +  z̄²
//                    ↑自己相関の項                   ↑ドリフトの項
//       ν = 1 - 2/(span+1)
//     期待エッジ > 0 ならトレンドフォローが効く局面
//
//  最終ポジション強度 = f(s) × 持続性ゲート
// ─────────────────────────────────────────────────────────────────────────────
indicator("Nonlinear TSMOM × Trend Persistence", shorttitle = "NLTSM×TP", overlay = false, precision = 3)
 
// ── 入力 ─────────────────────────────────────────────────────────────────────
grpM = "1) Nonlinear TSMOM (Moskowitz et al.)"
momLen  = input.int(62, "Lookback T (paper: 21 / 62 / 260)", minval = 2, group = grpM)
volLenM = input.int(260, "Volatility window (paper: 260)", minval = 20, group = grpM)
curve   = input.string("Theory (λs/(s²+1))", "Weight function", options = ["Theory (λs/(s²+1))", "Linear", "Binary (sign)"], group = grpM,
     tooltip = "Theory: the theoretical optimal weight used in the paper. Peaks at |s| = 1 and discounts extreme values.\nLinear: classic linear TSMOM (for comparison).\nBinary: sign only (Moskowitz et al. 2012, for comparison).")
clipOut = input.bool(true, "Normalize output to ±1", group = grpM,
     tooltip = "On: Theory is divided by its maximum λ/2 ≈ 1.27 so it stays within ±1. Linear is clipped at ±1.")
 
grpP = "2) Trend persistence (Sepp & Lucic)"
volSpanP = input.int(33, "EWMA span for normalizing volatility (paper example: 33)", minval = 5, group = grpP)
kerSpan  = input.int(62, "Filter span (sets ν)", minval = 2, group = grpP,
     tooltip = "ν = 1 - 2/(span+1). As in the paper, match it to the trend horizon (default 62, same as T).")
acLen    = input.int(250, "Autocorrelation window N", minval = 60, group = grpP)
maxLag   = input.int(60, "Max lag K", minval = 1, maxval = 120, group = grpP,
     tooltip = "The sum of ν^m ρ(m) is truncated at m = 1..K. Choose K so that ν^K is small.")
useDrift = input.bool(true, "Include drift term", group = grpP)
eLow     = input.float(0.00, "Expected edge lower bound (gate = 0)", step = 0.005, group = grpP)
eHigh    = input.float(0.01, "Expected edge upper bound (gate = 1)", step = 0.001, group = grpP,
     tooltip = "On BTC daily the expected edge mostly ranges from about -0.01 to +0.015. Check the Data Window on your symbol.")
gateMin  = input.float(0.0, "Minimum gate", minval = 0.0, maxval = 1.0, step = 0.05, group = grpP,
     tooltip = "0: fully stand aside when the edge is negative. e.g. 0.3: always keep at least 30% of the weight.")
 
grpS = "Display & signals"
thr     = input.float(0.3, "Signal threshold |position|", minval = 0.0, maxval = 1.0, step = 0.05, group = grpS)
showRaw = input.bool(true, "Show raw weight f(s) (before gate)", group = grpS)
showTbl = input.bool(true, "Show value table", group = grpS)
 
// ── ① 非線形TSMOM ────────────────────────────────────────────────────────────
ret   = math.log(close / close[1])
sigM  = ta.stdev(ret, volLenM)[1]                                   // σ̂_{t-1}
sumR  = math.sum(ret, momLen)
s     = sigM > 0 ? sumR / (sigM * math.sqrt(momLen)) : na
 
LAMBDA = 2.535
float f = na
if curve == "Theory (λs/(s²+1))"
    f := LAMBDA * s / (s * s + 1.0)
    f := clipOut ? f / (LAMBDA / 2.0) : f
else if curve == "Linear"
    f := clipOut ? math.max(-1.0, math.min(1.0, s)) : s
else
    f := s > 0 ? 1.0 : s < 0 ? -1.0 : 0.0
 
// ── ② トレンド持続性 ─────────────────────────────────────────────────────────
sigP = math.sqrt(ta.ema(ret * ret, volSpanP))[1]                    // σ_{t-1}
z    = sigP > 0 ? ret / sigP : na
x    = nz(z)
 
// ローリングのラグ積和 Σ x_t·x_{t-m}(窓 N、差分更新)
var array<float> lagS = array.new_float(120, 0.0)
for m = 1 to maxLag
    addV = x * nz(x[m])
    subV = nz(x[acLen]) * nz(x[acLen + m])
    array.set(lagS, m - 1, array.get(lagS, m - 1) + addV - subV)
 
zbar = math.sum(x, acLen) / acLen
g0   = math.sum(x * x, acLen) / acLen - zbar * zbar                 // γ̂(0)
nu   = 1.0 - 2.0 / (kerSpan + 1.0)
 
float acSum = 0.0
float nuPow = nu
for m = 1 to maxLag
    gm     = array.get(lagS, m - 1) / acLen - zbar * zbar           // γ̂(m)(中心化)
    rho    = g0 > 0 ? gm / g0 : 0.0
    acSum += nuPow * rho
    nuPow *= nu
 
acTerm    = (1.0 - nu) / nu * acSum                                 // 自己相関の項
driftTerm = g0 > 0 ? zbar * zbar / g0 : 0.0                         // ドリフトの項
edge      = acTerm + (useDrift ? driftTerm : 0.0)                   // 期待エッジ
 
span = math.max(eHigh - eLow, 1e-9)
gate = math.max(gateMin, math.min(1.0, (edge - eLow) / span))
pos  = f * gate
 
ready = bar_index > math.max(volLenM, acLen + maxLag) + momLen
 
// ── 描画 ─────────────────────────────────────────────────────────────────────
posTr  = 100 - math.round(math.min(math.abs(nz(pos)), 1.0) * 80)
posCol = pos >= 0 ? color.new(color.teal, posTr) : color.new(color.red, posTr)
plot(ready ? pos : na, "Position strength", style = plot.style_columns, color = posCol)
plot(ready and showRaw ? f : na, "Raw weight f(s) (before gate)", color = color.new(color.gray, 20), linewidth = 1)
plot(ready ? gate : na, "Persistence gate (0-1)", color = color.new(color.orange, 0), linewidth = 2)
plot(ready ? s : na, "Trend s", display = display.data_window)
plot(ready ? edge : na, "Expected edge", display = display.data_window)
plot(ready ? acTerm : na, "Autocorrelation term", display = display.data_window)
plot(ready ? driftTerm : na, "Drift term", display = display.data_window)
hline(0, "Zero", color = color.new(color.gray, 50), linestyle = hline.style_solid)
hline(thr, "+Threshold", color = color.new(color.teal, 60), linestyle = hline.style_dotted)
hline(-thr, "-Threshold", color = color.new(color.red, 60), linestyle = hline.style_dotted)
bgcolor(ready and edge < eLow ? color.new(color.purple, 92) : na, title = "Negative expected edge")
 
xUp     = ta.crossover(pos, thr)
xDn     = ta.crossunder(pos, -thr)
longOn  = ready and xUp
shortOn = ready and xDn
flatOn  = ready and ((pos[1] >= thr and pos < thr) or (pos[1] <= -thr and pos > -thr))
plotshape(longOn,  "Long signal",  shape.triangleup,   location.bottom, color.teal, size = size.tiny)
plotshape(shortOn, "Short signal", shape.triangledown, location.top,    color.red,  size = size.tiny)
 
alertcondition(longOn,  "Long signal",  "NLTSM×TP: position strength crossed above +threshold")
alertcondition(shortOn, "Short signal", "NLTSM×TP: position strength crossed below -threshold")
alertcondition(flatOn,  "Exit",         "NLTSM×TP: position strength moved back inside the threshold")
 
// ── 数値テーブル ─────────────────────────────────────────────────────────────
var table tb = table.new(position.top_right, 2, 7, bgcolor = color.new(color.black, 30), border_width = 1)
if showTbl and barstate.islast
    table.cell(tb, 0, 0, "Trend s",           text_color = color.white, text_size = size.small)
    table.cell(tb, 1, 0, str.tostring(s, "#.##"), text_color = color.white, text_size = size.small)
    table.cell(tb, 0, 1, "Weight f(s)",       text_color = color.white, text_size = size.small)
    table.cell(tb, 1, 1, str.tostring(f, "#.###"), text_color = color.white, text_size = size.small)
    table.cell(tb, 0, 2, "Autocorr. term",    text_color = color.white, text_size = size.small)
    table.cell(tb, 1, 2, str.tostring(acTerm, "#.####"), text_color = acTerm >= 0 ? color.lime : color.fuchsia, text_size = size.small)
    table.cell(tb, 0, 3, "Drift term",        text_color = color.white, text_size = size.small)
    table.cell(tb, 1, 3, str.tostring(driftTerm, "#.####"), text_color = color.white, text_size = size.small)
    table.cell(tb, 0, 4, "Expected edge",     text_color = color.white, text_size = size.small)
    table.cell(tb, 1, 4, str.tostring(edge, "#.####"), text_color = edge >= eLow ? color.lime : color.fuchsia, text_size = size.small)
    table.cell(tb, 0, 5, "Gate",              text_color = color.white, text_size = size.small)
    table.cell(tb, 1, 5, str.tostring(gate, "#.##"), text_color = color.orange, text_size = size.small)
    table.cell(tb, 0, 6, "Position strength", text_color = color.white, text_size = size.small)
    table.cell(tb, 1, 6, str.tostring(pos, "#.###"), text_color = pos >= 0 ? color.teal : color.red, text_size = size.small)

← 返回列表