Semi-Markov Trend [MiesOnCharts]

MiesOnCharts · study · 229 行 · 点赞 206 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MiesOnCharts
 
//   __  __ _
//  |  \/  (_) ___  ___
//  | |\/| | |/ _ \/ __|
//  | |  | | |  __/\__ \
//  |_|  |_|_|\___||___/
 
//@version=6
// ═══════════════════════════════════════════════════════════════════════════
//  SEMI-MARKOV TREND
//  A linear trend filter derived from a regime model: returns switch between a
//  bull and a bear regime, and a regime gets more likely to end as it ages.
//
//    score = sum(w[k] * r[k]) / (sigma * sqrt(sum(w[k]^2)))
//
//  r[k] is the log return k bars ago and sigma is the current volatility.
// ═══════════════════════════════════════════════════════════════════════════
indicator("Semi-Markov Trend [MiesOnCharts]", shorttitle = "SMT - Mies", overlay = false, precision = 2, max_bars_back = 600)
 
grpM = "Regime Model"
grpS = "States"
grpD = "Display"
 
src       = input.source(close, "Source", group = grpM, display = display.none)
lenB      = input.int(60, "Bull Length", minval = 5, maxval = 150, group = grpM, display = display.none,
     tooltip = "Average bars a bull regime lasts in the model, on the chart's own timeframe.")
lenR      = input.int(60, "Bear Length", minval = 5, maxval = 150, group = grpM, display = display.none,
     tooltip = "Average bars a bear regime lasts in the model.")
ageShape  = input.int(3, "Regime Aging", minval = 1, maxval = 8, group = grpM, display = display.none,
     tooltip = "How strongly a regime's age raises its chance of ending, as the number of hidden stages it walks through. One means age does not matter.")
regGap    = input.float(0.42, "Regime Strength", minval = 0.05, maxval = 1.5, step = 0.02, group = grpM, display = display.none,
     tooltip = "The gap between the average bull bar and the average bear bar, in bar standard deviations.")
smoothLen = input.int(10, "Smoothing", minval = 1, maxval = 50, group = grpM, display = display.none)
volLen    = input.int(60, "Volatility Window", minval = 5, maxval = 500, group = grpM, display = display.none,
     tooltip = "Bars in the average of squared returns that scales the line. This changes the scale only, not the weights.")
 
longThr  = input.float(0.25,  "Long Above",  step = 0.05, group = grpS, display = display.none,
     tooltip = "The score has to close above this to turn the state long.")
shortThr = input.float(-0.25, "Short Below", step = 0.05, group = grpS, display = display.none,
     tooltip = "The score has to close below this to turn the state short.")
 
paintBar = input.bool(true, "Paint Candles", group = grpD, display = display.none)
showTbl  = input.bool(false, "Readout", group = grpD, display = display.none,
     tooltip = "The score, the state and how long it has held, and where the filter's weights peak and turn negative for the current settings.")
colUp    = input.color(color.rgb(0, 255, 21),    "Long",    inline = "c", group = grpD)
colDn    = input.color(color.rgb(255, 0, 0),     "Short",   inline = "c", group = grpD)
colFlat  = input.color(color.rgb(120, 123, 134), "Neutral", inline = "c", group = grpD)
 
// ─────────────────────────────────────────────────────────────────
// Autocovariance of returns at lags 1 to lags, in units of the bar variance.
// The chain has n bull stages followed by n bear stages. A stage hands over to
// the next with chance q per bar, so a regime's mean length is n / q.
//
// v holds the expected regime drift h bars ahead, starting from each stage. The
// chain only ever stays or moves one stage on, so each step is one pass.
f_autocov(int lb, int lr, int n, float spread, int lags) =>
    int   nn = 2 * n
    float qB = math.min(1.0, float(n) / lb)
    float qR = math.min(1.0, float(n) / lr)
    array<float> q  = array.new_float(nn, qR)
    array<float> mu = array.new_float(nn, -spread / 2.0)
    for i = 0 to n - 1
        q.set(i, qB)
        mu.set(i, spread / 2.0)
    // Long run share of bars in each stage.
    array<float> pi = array.new_float(nn, 0.0)
    float tot = 0.0
    for i = 0 to nn - 1
        pi.set(i, 1.0 / q.get(i))
        tot += 1.0 / q.get(i)
    float mBar = 0.0
    for i = 0 to nn - 1
        pi.set(i, pi.get(i) / tot)
        mBar += pi.get(i) * mu.get(i)
    array<float> v = mu.copy()
    array<float> g = array.new_float(lags, 0.0)
    for h = 0 to lags - 1
        float first = v.get(0)
        for i = 0 to nn - 1
            float nxt = i == nn - 1 ? first : v.get(i + 1)
            v.set(i, (1.0 - q.get(i)) * v.get(i) + q.get(i) * nxt)
        float s = 0.0
        for i = 0 to nn - 1
            s += pi.get(i) * mu.get(i) * v.get(i)
        g.set(h, s - mBar * mBar)
    g
 
// Solves the normal equations by Levinson recursion. The matrix has a one on its
// diagonal and the autocovariances off it, and the right hand side is the same
// autocovariances one lag on. The inner loops are guarded because a Pine for loop
// counts down when its end is below its start.
f_solve(array<float> g, int lags) =>
    array<float> a = array.new_float(lags, 0.0)
    array<float> b = array.new_float(lags, 0.0)
    float err = 1.0
    for m = 0 to lags - 1
        float acc = g.get(m)
        if m > 0
            for j = 0 to m - 1
                acc -= a.get(j) * g.get(m - j - 1)
        float k = acc / err
        b.set(m, k)
        if m > 0
            for j = 0 to m - 1
                b.set(j, a.get(j) - k * a.get(m - 1 - j))
        for j = 0 to m
            a.set(j, b.get(j))
        err *= 1.0 - k * k
    a
 
// Runs an EMA along the weights, which is the same as running it along the line.
// The result is longer than the input so the EMA's tail is kept. A length of one
// leaves the weights as they are.
f_smooth(array<float> w, int total, int s) =>
    array<float> out = array.new_float(total, 0.0)
    float a = 2.0 / (s + 1)
    float prev = 0.0
    for k = 0 to total - 1
        float wk = k < w.size() ? w.get(k) : 0.0
        prev := a * wk + (1.0 - a) * prev
        out.set(k, prev)
    out
 
// Reach grows with the regime lengths and the smoothing. Past this the weights
// are close to 0.
int baseLag = math.round(2.5 * (lenB + lenR) / 2.0)
int maxLag  = baseLag + (smoothLen > 1 ? 3 * smoothLen : 0)
 
var array<float> wts = array.new_float(0)
var float wNorm      = na
var int   revLag     = na
var int   peakLag    = 0
if barstate.isfirst
    wts := f_smooth(f_solve(f_autocov(lenB, lenR, ageShape, regGap, baseLag), baseLag), maxLag, smoothLen)
    float s2   = 0.0
    float best = wts.get(0)
    for i = 0 to maxLag - 1
        float wi = wts.get(i)
        s2 += wi * wi
        if wi > best
            best    := wi
            peakLag := i
        if na(revLag) and wi < -1e-6
            revLag := i
    wNorm := math.sqrt(s2)
 
// ── Score ─────────────────────────────────────────────────────────────────
// Volatility is an EMA of squared returns, seeded with their simple average once
// the window is full. The line starts when the filter has its full reach.
float lnP   = math.log(src)
float r1    = lnP - lnP[1]
float r1sq  = r1 * r1
float seedV = ta.sma(r1sq, volLen)
float alpha = 2.0 / (volLen + 1)
var float ewVar = na
ewVar := na(ewVar) ? seedV : ewVar + alpha * (r1sq - ewVar)
 
float raw = na
if bar_index >= maxLag
    float total = 0.0
    for k = 0 to maxLag - 1
        total += wts.get(k) * r1[k]
    raw := total
float score = ewVar > 0 ? raw / (math.sqrt(ewVar) * wNorm) : na
 
// ── State ─────────────────────────────────────────────────────────────────
// The line reads the live bar. The state that paints and alerts only moves on a
// closed bar, and between the two levels it holds.
var int state  = 0
var int barsIn = 0
if barstate.isconfirmed and not na(score)
    int prev = state
    if score > longThr
        state := 1
    else if score < shortThr
        state := -1
    barsIn := state == prev ? barsIn + 1 : 1
 
bool  flipUp = state ==  1 and state[1] !=  1
bool  flipDn = state == -1 and state[1] != -1
color stCol  = state == 1 ? colUp : state == -1 ? colDn : colFlat
 
// ── Render ────────────────────────────────────────────────────────────────
pS = plot(score, "Score", color = stCol, linewidth = 2)
pZ = plot(0.0, "", color = na, editable = false, display = display.none)
fill(pS, pZ, color = color.new(stCol, 86), title = "Score Fill", editable = false)
 
hline( 0,       "Zero",        color = color.new(colFlat, 40))
hline(longThr,  "Long Level",  color = color.new(colUp, 60), linestyle = hline.style_dotted)
hline(shortThr, "Short Level", color = color.new(colDn, 60), linestyle = hline.style_dotted)
hline( 1,       "+1",          color = color.new(colFlat, 75), linestyle = hline.style_dashed)
hline(-1,       "-1",          color = color.new(colFlat, 75), linestyle = hline.style_dashed)
hline( 2,       "+2",          color = color.new(colFlat, 60), linestyle = hline.style_dashed)
hline(-2,       "-2",          color = color.new(colFlat, 60), linestyle = hline.style_dashed)
 
plotshape(flipUp ? score : na, "Long",  shape.triangleup,   location.absolute, colUp, size = size.tiny)
plotshape(flipDn ? score : na, "Short", shape.triangledown, location.absolute, colDn, size = size.tiny)
 
// Redrawn as candles so the body fills on any candle style. force_overlay
// because this is a pane and the bars live on price.
plotcandle(paintBar and state != 0 ? open  : na,
           paintBar and state != 0 ? high  : na,
           paintBar and state != 0 ? low   : na,
           paintBar and state != 0 ? close : na,
     title = "Trend Candles", color = stCol, wickcolor = stCol, bordercolor = stCol,
     display = display.all - display.status_line, force_overlay = true, editable = false)
 
plot(state,  "State",         color = color.blue, display = display.data_window)
plot(barsIn, "Bars In State", color = color.blue, display = display.data_window)
 
// ── Readout ───────────────────────────────────────────────────────────────
var table tbl = table.new(position.top_right, 2, 5, border_width = 1)
if barstate.islast and showTbl and not na(score)
    color txt = chart.fg_color
    table.cell(tbl, 0, 0, "Score", text_color = txt, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, 0, (score >= 0 ? "+" : "") + str.tostring(score, "0.00"), text_color = stCol, text_size = size.small)
    table.cell(tbl, 0, 1, "State", text_color = txt, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, 1, state == 1 ? "LONG" : state == -1 ? "SHORT" : "NEUTRAL", text_color = stCol, text_size = size.small)
    table.cell(tbl, 0, 2, "Bars in state", text_color = txt, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, 2, str.tostring(barsIn), text_color = txt, text_size = size.small)
    table.cell(tbl, 0, 3, "Weights peak", text_color = txt, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, 3, "lag " + str.tostring(peakLag), text_color = txt, text_size = size.small)
    table.cell(tbl, 0, 4, "Weights turn negative", text_color = txt, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, 4, na(revLag) ? "never" : "lag " + str.tostring(revLag), text_color = txt, text_size = size.small)
 
alertcondition(flipUp, "Semi-Markov Trend Long",  "Semi-Markov trend turned long on the close")
alertcondition(flipDn, "Semi-Markov Trend Short", "Semi-Markov trend turned short on the close")

← 返回列表