Kalman Trend & Signal Filter

SoCallMeDeaconBlues · study · 176 行 · 点赞 17 · 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/
// © SoCallMeDeaconBlues
 
//@version=6
indicator("Kalman Trend & Signal Filter", shorttitle="KTSF", overlay=true)
 
// ============================================================
// Inputs
// ============================================================
string gFilter = "Filter Settings"
string gBand   = "Band / Cloud Settings"
string gSig    = "Signals"
string gStyle  = "Style"
 
src        = input.source(close, "Source", group=gFilter)
measNoise  = input.float(3000.0, "Measurement Noise", minval=0.0001, step=100, group=gFilter, tooltip="How much the filter distrusts each new price print. Higher = smoother, slower line. Only the ratio to the Acceleration Process Noise below matters -- raising both together changes almost nothing. Default re-tuned by backtesting a full year of CL 1-second data; this ratio held up as a genuine plateau (not a lucky single point) across a range of nearby settings.")
accelNoise = input.float(0.01, "Acceleration Process Noise", minval=0.000001, step=0.001, group=gFilter, tooltip="How freely the filter lets the trend's rate of change itself change. Higher = reacts faster to a genuine shift in momentum (less lag on big moves), but is more easily nudged by a single noisy bar. Lower = steadier, but slower to pick up on an accelerating move.")
 
bandLen  = input.int(20, "Band Lookback", minval=2, group=gBand, tooltip="Bars used to measure how far price typically deviates from the line.")
bandMult = input.float(1.0, "Band Multiplier", minval=0.0, step=0.1, group=gBand)
 
showSignals = input.bool(true, "Show Transition Markers on Line", group=gSig)
sigThresh   = input.float(0.6, "Slope Threshold (band-widths / bar)", minval=0.0, step=0.01, group=gSig, tooltip="How far the trend's slope must lean, as a multiple of the band width, before a long or short zone is entered. This deadband is what keeps the signal from flipping on every small wiggle. Raise it for fewer, higher-conviction signals; lower it for more, choppier ones. Default re-tuned by backtesting a full year of CL 1-second data: 0.6 gave a markedly more consistent split-half result than 0.5, with a smaller drawdown and fewer trades.")
markerShapeIn = input.string("Triangle", "Marker Shape", options=["Triangle", "Cross", "Circle", "Diamond", "Flag"], group=gSig)
markerSizeIn  = input.string("Auto", "Marker Size", options=["Auto", "Tiny", "Small", "Normal"], group=gSig, tooltip="Auto asks the chart to keep the marker proportional to its current visual density -- the closest thing Pine offers to a marker that scales with zoom. Tiny/Small pin it to a small, fixed size at any zoom level so it never dominates the chart when you zoom out.")
showBuySell = input.bool(true, "Show B / S Labels at Entries", group=gSig, tooltip="Places a small 'B' below the bar where a long is entered and an 'S' above the bar where a short is entered, as a quick visual cue separate from the on-line markers.")
 
longCol  = input.color(color.rgb(0, 200, 83),   "Up Trend / Long",   inline="trend", group=gStyle)
shortCol = input.color(color.rgb(255, 23, 68),  "Down Trend / Short", inline="trend", group=gStyle)
cloudCol = input.color(#91d5ff4d, "Cloud", group=gStyle)
 
// ============================================================
// 3-state Kalman filter: level, velocity, acceleration
// Constant-acceleration (discrete Wiener-process-acceleration) model.
// Written out in scalar form rather than with matrix.* calls -- six
// covariance terms and three state terms, updated explicitly each bar.
// ============================================================
type Kalman3
    float x0  = na    // level
    float x1  = 0.0   // velocity
    float x2  = 0.0   // acceleration
    float p00 = 1.0
    float p01 = 0.0
    float p02 = 0.0
    float p11 = 1.0
    float p12 = 0.0
    float p22 = 1.0
 
method step(Kalman3 s, float z, float q, float r) =>
    if not na(z) and not na(r)
        if na(s.x0)
            s.x0  := z
            s.x1  := 0.0
            s.x2  := 0.0
            s.p00 := 1.0
            s.p01 := 0.0
            s.p02 := 0.0
            s.p11 := 1.0
            s.p12 := 0.0
            s.p22 := 1.0
        else
            // Predict: x = F x, P = F P F' + Q, with
            //   F = [[1,1,0.5],[0,1,1],[0,0,1]]  (level/velocity advanced by acceleration)
            //   Q = q * [[0.25,0.5,0.5],[0.5,1,1],[0.5,1,1]]  (discrete Wiener-process-acceleration noise)
            float xp0 = s.x0 + s.x1 + 0.5 * s.x2
            float xp1 = s.x1 + s.x2
            float xp2 = s.x2
 
            float pp00 = s.p00 + 2.0 * s.p01 + s.p02 + s.p11 + s.p12 + 0.25 * s.p22 + 0.25 * q
            float pp01 = s.p01 + s.p02 + s.p11 + 1.5 * s.p12 + 0.5 * s.p22 + 0.5 * q
            float pp02 = s.p02 + s.p12 + 0.5 * s.p22 + 0.5 * q
            float pp11 = s.p11 + 2.0 * s.p12 + s.p22 + q
            float pp12 = s.p12 + s.p22 + q
            float pp22 = s.p22 + q
 
            // Update (H = [1,0,0]: only the level is observed)
            float S  = pp00 + r
            float k0 = pp00 / S
            float k1 = pp01 / S
            float k2 = pp02 / S
            float y  = z - xp0
 
            s.x0 := xp0 + k0 * y
            s.x1 := xp1 + k1 * y
            s.x2 := xp2 + k2 * y
 
            s.p00 := (1.0 - k0) * pp00
            s.p01 := (1.0 - k0) * pp01
            s.p02 := (1.0 - k0) * pp02
            s.p11 := pp11 - k1 * pp01
            s.p12 := pp12 - k1 * pp02
            s.p22 := pp22 - k2 * pp02
    s
 
var Kalman3 kf = Kalman3.new()
kf.step(src, accelNoise, measNoise)
 
float est   = kf.x0   // filtered price level
float slope = kf.x1   // filtered velocity (the trend-direction signal)
 
// ============================================================
// Band / cloud
// ============================================================
float devRms = math.sqrt(ta.sma(math.pow(src - est, 2), bandLen))
float halfW  = devRms * bandMult
float upper  = est + halfW
float lower  = est - halfW
 
color lineCol = slope > 0 ? longCol : shortCol
 
linePlot = plot(est,   "Kalman Trend Line", color=lineCol, linewidth=2, style=plot.style_linebr)
upPlot   = plot(upper, "Upper Band", color=na)
loPlot   = plot(lower, "Lower Band", color=na)
fill(upPlot, linePlot, upper, est, cloudCol, na)
fill(loPlot, linePlot, lower, est, cloudCol, na)
 
// ============================================================
// Entry/exit zone logic
// Slope normalized by the band's own RMS deviation so the threshold is
// scale-free (works the same whether price or volatility changes) instead
// of a fixed price-per-bar cutoff.
// ============================================================
float normSlope = na(devRms) or devRms <= 0 ? 0.0 : slope / devRms
int   zone      = normSlope > sigThresh ? 1 : normSlope < -sigThresh ? -1 : 0
 
var int posState = 0
bool enterLong  = zone == 1  and posState != 1
bool enterShort = zone == -1 and posState != -1
bool exitLong   = posState == 1  and zone != 1
bool exitShort  = posState == -1 and zone != -1
posState := zone
 
// ============================================================
// Markers
// ============================================================
longShape  = markerShapeIn == "Triangle" ? shape.triangleup   : markerShapeIn == "Cross" ? shape.xcross : markerShapeIn == "Circle" ? shape.circle : markerShapeIn == "Diamond" ? shape.diamond : shape.flag
shortShape = markerShapeIn == "Triangle" ? shape.triangledown : markerShapeIn == "Cross" ? shape.xcross : markerShapeIn == "Circle" ? shape.circle : markerShapeIn == "Diamond" ? shape.diamond : shape.flag
 
// Pine requires plotshape's size= argument to be a literal const value -- it
// can't be a variable computed from an input, even via ternary. So instead of
// one plotshape per marker with a dynamic size, we gate one plotshape per
// (marker, size option) pair on a boolean and hardcode that call's own size=.
bool sizeAuto   = markerSizeIn == "Auto"
bool sizeTiny   = markerSizeIn == "Tiny"
bool sizeSmall  = markerSizeIn == "Small"
bool sizeNormal = markerSizeIn == "Normal"
 
// On-the-line transition markers (placed at the filter's own price level, not the bar)
plotshape(showSignals and enterLong and sizeAuto   ? est : na, title="Enter Long (Auto)",   style=longShape,  location=location.absolute, color=longCol, size=size.auto)
plotshape(showSignals and enterLong and sizeTiny   ? est : na, title="Enter Long (Tiny)",   style=longShape,  location=location.absolute, color=longCol, size=size.tiny)
plotshape(showSignals and enterLong and sizeSmall  ? est : na, title="Enter Long (Small)",  style=longShape,  location=location.absolute, color=longCol, size=size.small)
plotshape(showSignals and enterLong and sizeNormal ? est : na, title="Enter Long (Normal)", style=longShape,  location=location.absolute, color=longCol, size=size.normal)
 
plotshape(showSignals and exitLong and sizeAuto   ? est : na, title="Exit Long (Auto)",   style=longShape,  location=location.absolute, color=color.new(longCol, 45), size=size.auto)
plotshape(showSignals and exitLong and sizeTiny   ? est : na, title="Exit Long (Tiny)",   style=longShape,  location=location.absolute, color=color.new(longCol, 45), size=size.tiny)
plotshape(showSignals and exitLong and sizeSmall  ? est : na, title="Exit Long (Small)",  style=longShape,  location=location.absolute, color=color.new(longCol, 45), size=size.small)
plotshape(showSignals and exitLong and sizeNormal ? est : na, title="Exit Long (Normal)", style=longShape,  location=location.absolute, color=color.new(longCol, 45), size=size.normal)
 
plotshape(showSignals and enterShort and sizeAuto   ? est : na, title="Enter Short (Auto)",   style=shortShape, location=location.absolute, color=shortCol, size=size.auto)
plotshape(showSignals and enterShort and sizeTiny   ? est : na, title="Enter Short (Tiny)",   style=shortShape, location=location.absolute, color=shortCol, size=size.tiny)
plotshape(showSignals and enterShort and sizeSmall  ? est : na, title="Enter Short (Small)",  style=shortShape, location=location.absolute, color=shortCol, size=size.small)
plotshape(showSignals and enterShort and sizeNormal ? est : na, title="Enter Short (Normal)", style=shortShape, location=location.absolute, color=shortCol, size=size.normal)
 
plotshape(showSignals and exitShort and sizeAuto   ? est : na, title="Exit Short (Auto)",   style=shortShape, location=location.absolute, color=color.new(shortCol, 45), size=size.auto)
plotshape(showSignals and exitShort and sizeTiny   ? est : na, title="Exit Short (Tiny)",   style=shortShape, location=location.absolute, color=color.new(shortCol, 45), size=size.tiny)
plotshape(showSignals and exitShort and sizeSmall  ? est : na, title="Exit Short (Small)",  style=shortShape, location=location.absolute, color=color.new(shortCol, 45), size=size.small)
plotshape(showSignals and exitShort and sizeNormal ? est : na, title="Exit Short (Normal)", style=shortShape, location=location.absolute, color=color.new(shortCol, 45), size=size.normal)
 
// B / S labels near the bars, for a quick at-a-glance read
plotshape(showBuySell and enterLong,  title="Buy Label",  style=shape.labelup,   location=location.belowbar, color=longCol,  textcolor=color.white, text="B", size=size.small)
plotshape(showBuySell and enterShort, title="Sell Label", style=shape.labeldown, location=location.abovebar, color=shortCol, textcolor=color.white, text="S", size=size.small)
 
alertcondition(enterLong,  title="Enter Long",  message="KTF3: Enter Long")
alertcondition(exitLong,   title="Exit Long",   message="KTF3: Exit Long")
alertcondition(enterShort, title="Enter Short", message="KTF3: Enter Short")
alertcondition(exitShort,  title="Exit Short",  message="KTF3: Exit Short")

← 返回列表