Directional Kernel Filter [BackQuant]

BackQuant · study · 123 行 · 点赞 564 · 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/
// © BackQuant
 
 
//@version=6
indicator("Directional Kernel Filter [BackQuant]", shorttitle="Directional Kernel [BackQuant]", overlay=true)
 
// Constants
const string calc = "Core Calculation Settings"
const string ui   = "Plotting and Coloring"
const color GREEN = #00ff00
const color RED   = #ff0000
 
// Inputs
float src = input.source(close, "Source", group=calc)
int fastLen = input.int(18, "Fast Kernel Length", minval=3, group=calc, inline="LEN")
int slowLen = input.int(35, "Slow", minval=5, group=calc, inline="LEN")
float kernelWidth = input.float(0.35, "Kernel Width", minval=0.05, maxval=1.0, step=0.05, group=calc, tooltip="Controls the Gaussian kernel bandwidth relative to the filter length. Lower values concentrate weight near the current bar.")
float directionStrength = input.float(3.5, "Directional Weight", minval=0.0, maxval=5.0, step=0.1, group=calc, tooltip="Controls how strongly observations agreeing with the previously estimated direction are favored. 0 disables directional weighting.")
int normLen = input.int(14, "Normalization Length", minval=2, group=calc, tooltip="ATR length used to normalize directional price movement across assets and volatility regimes.")
 
color longCol = input.color(GREEN, "Long Color", group=ui, inline="COL")
color shortCol = input.color(RED, "Short Color", group=ui, inline="COL")
int lineW = input.int(3, "Line Width", minval=1, maxval=6, group=ui)
bool showRibbon = input.bool(true, "Show Trend Ribbon?", group=ui)
bool showBase = input.bool(false, "Show Base Kernel?", group=ui)
bool paintCandles = input.bool(false, "Paint Candles to Trend?", group=ui)
bool bgCol = input.bool(false, "Background Color?", group=ui)
 
// Directional Kernel Filter
directionalKernel(float source, simple int length, float width, float strength, float norm) =>
    float bandwidth = math.max(1.0, length * width)
 
    float baseWeighted = 0.0
    float baseWeights = 0.0
 
    for i = 0 to length - 1
        if not na(source[i])
            float distance = i / bandwidth
            float kernelWeight = math.exp(-0.5 * distance * distance)
            baseWeighted += source[i] * kernelWeight
            baseWeights += kernelWeight
 
    float base = baseWeights > 0.0 ? baseWeighted / baseWeights : na
 
    float priorDirection = nz(base[1] - base[2])
    float priorNorm = priorDirection / math.max(nz(norm[1], norm), syminfo.mintick)
    priorNorm := math.max(-1.0, math.min(1.0, priorNorm))
 
    float weightedPrice = 0.0
    float totalWeight = 0.0
 
    for i = 0 to length - 1
        if not na(source[i])
            float distance = i / bandwidth
            float kernelWeight = math.exp(-0.5 * distance * distance)
 
            float localMove = i < length - 1 ? source[i] - source[i + 1] : 0.0
            float localNorm = localMove / math.max(nz(norm[i], norm), syminfo.mintick)
            localNorm := math.max(-1.0, math.min(1.0, localNorm))
 
            float alignment = priorNorm * localNorm
            float exponent = math.max(-3.0, math.min(3.0, strength * alignment))
            float directionWeight = math.exp(exponent)
 
            float weight = kernelWeight * directionWeight
 
            weightedPrice += source[i] * weight
            totalWeight += weight
 
    float filtered = totalWeight > 0.0 ? weightedPrice / totalWeight : base
 
    [filtered, base, priorNorm]
 
// Normalization
float atr = ta.atr(normLen)
 
// Fast + Slow Directional Kernels
[fastKernel, fastBase, fastDirection] = directionalKernel(src, fastLen, kernelWidth, directionStrength, atr)
[slowKernel, slowBase, slowDirection] = directionalKernel(src, slowLen, kernelWidth, directionStrength, atr)
 
// Trend State
bool bullish = fastKernel > slowKernel
bool bearish = fastKernel < slowKernel
 
var int trend = 0
 
if bullish
    trend := 1
else if bearish
    trend := -1
 
color col = trend == 1 ? longCol : shortCol
 
// Ribbon
pFast = plot(fastKernel, "Fast Directional Kernel", col, lineW)
pSlow = plot(showRibbon ? slowKernel : na, "Slow Directional Kernel", color.new(col, 60), 2)
 
fill(pFast, pSlow, showRibbon ? color.new(col, 82) : na, title="Directional Kernel Ribbon")
 
// Base Gaussian Kernel
plot(showBase ? fastBase : na, "Base Gaussian Kernel", color.new(chart.fg_color, 60), 1)
 
// Candles
plotcandle(open, high, low, close, "Trend Candles",
     col, col, true,
     bordercolor=col,
     display=paintCandles ? display.all : display.none)
 
bgcolor(bgCol ? color.new(col, 90) : na)
 
// Data Window
plot(fastDirection, "Fast Reference Direction", display=display.data_window)
plot(slowDirection, "Slow Reference Direction", display=display.data_window)
plot(fastKernel - fastBase, "Directional Adjustment", display=display.data_window)
plot(fastKernel - slowKernel, "Kernel Spread", display=display.data_window)
 
// Alerts
bool bullFlip = trend == 1 and trend[1] == -1
bool bearFlip = trend == -1 and trend[1] == 1
 
alertcondition(bullFlip, title="Directional Kernel Bullish", message="Directional Kernel Trend Filter turned bullish {{exchange}}:{{ticker}}")
alertcondition(bearFlip, title="Directional Kernel Bearish", message="Directional Kernel Trend Filter turned bearish {{exchange}}:{{ticker}}")

← 返回列表