Kalman Z-Score & Value Bands [UkutaLabs]

UkutaLabs · study · 307 行 · 点赞 19 · 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/
// © UkutaLabs
 
 //   ██╗   ██╗██╗  ██╗██╗   ██╗████████╗ █████╗ ██╗      █████╗ ██████╗ ███████╗
 //   ██║   ██║██║ ██╔╝██║   ██║╚══██╔══╝██╔══██╗██║     ██╔══██╗██╔══██╗██╔════╝
 //   ██║   ██║█████╔╝ ██║   ██║   ██║   ███████║██║     ███████║██████╔╝███████╗
 //   ██║   ██║██╔═██╗ ██║   ██║   ██║   ██╔══██║██║     ██╔══██║██╔══██╗╚════██║
 //   ╚██████╔╝██║  ██╗╚██████╔╝   ██║   ██║  ██║███████╗██║  ██║██████╔╝███████║
 //    ╚═════╝ ╚═╝  ╚═╝ ╚═════╝    ╚═╝   ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═════╝ ╚══════╝
 
//@version=6
indicator("Kalman Z-Score & Value Bands [UkutaLabs]", overlay=false, precision=2)
 
// Port of the NinjaTrader trio UkutaLabsKalmanValueBands + UkutaLabsKalmanZScore +
// UkutaLabsKalmanDashboard - same filter, Smoothing mapping, z-score scale, flat rule and
// warm-up, so the same settings give the same numbers on both platforms. On TradingView it
// is one script: the z-score panel, plus the value line, bands and dashboard drawn on the
// price chart with force_overlay.
 
//---------------------
//USER VARIABLES
//---------------------
float Source = input.source(defval=close, title="Source", group="Configuration")
int Smoothing = input.int(defval=20, title="Smoothing", minval=2, maxval=500, group="Configuration", tooltip="How smooth the value line is, as an EMA length: 20 is about as smooth as a 20-bar EMA, but with less lag in trends. Higher is smoother.")
int Lookback = input.int(defval=50, title="Lookback", minval=2, group="Configuration", tooltip="Number of bars used to measure the typical distance between price and the value line (the z-score scale).")
float Threshold = input.float(defval=2.0, title="Threshold", minval=0.1, maxval=10, step=0.1, group="Configuration", tooltip="Z-score that counts as stretched. Z-score bars beyond it are drawn solid, and the bands on the price chart sit at this distance.")
float FlatZone = input.float(defval=1.0, title="Flat Zone", minval=0, maxval=10, step=0.1, group="Configuration", tooltip="How far the line must move over one Smoothing period, in z-score units, to count as rising or falling. Below this it is flat. 1 suits most markets; higher shows flat more often, 0 turns flat off.")
string BiasMode = input.string(defval="Slope + Price", title="Bias Mode", options=["Slope + Price", "Slope"], group="Configuration", tooltip="How the chart timeframe bias is read. Slope: from the line's slope alone - steady, but keeps the old direction for a while after a move stops. Slope + Price: also needs price to stay on the same side of the line, so it turns flat soon after a move stalls.")
string HtfBiasMode = input.string(defval="Slope", title="HTF Bias Mode", options=["Slope", "Slope + Price"], group="Configuration", tooltip="Bias Mode for a higher Bias Timeframe and the dashboard's higher timeframe rows. Slope (default) keeps a steady higher timeframe direction.")
 
string BiasTimeframe = input.timeframe(defval="", title="Bias Timeframe", group="Z-Score", tooltip="Timeframe the z-score bar colors take their rising / falling / flat bias from. Leave on Chart for this chart's own line. A higher timeframe updates only when its bar closes. Must be higher than the chart.")
color RisingColor = input.color(defval=color.rgb(30, 144, 255), title="Rising", inline="c", group="Colors")
color FallingColor = input.color(defval=color.rgb(255, 69, 0), title="Falling", inline="c", group="Colors")
color FlatColor = input.color(defval=color.gray, title="Flat", inline="c", group="Colors")
int InsideOpacity = input.int(defval=40, title="Inside Opacity %", minval=0, maxval=100, group="Z-Score", tooltip="Opacity of z-score bars inside the threshold. Bars beyond it are always solid.")
 
bool ShowValueLine = input.bool(defval=true, title="Show Value Line On Chart", group="Value Bands", tooltip="Draws the Kalman value line on the price chart, colored rising / falling / flat.")
bool ShowBands = input.bool(defval=true, title="Show Bands", group="Value Bands", tooltip="Draws bands at +/- Threshold z-scores around the value line. A close touching a band is exactly z = +/- Threshold.")
color BandColor = input.color(defval=color.gray, title="Band Color", group="Value Bands")
 
bool ShowDashboard = input.bool(defval=false, title="Show Dashboard", group="Dashboard", tooltip="A table of the reading on several timeframes at once: bias, z-score and state. Higher timeframes update only when their bar closes.")
bool ShowChartRow = input.bool(defval=true, title="Chart", inline="tf", group="Dashboard")
bool Show5 = input.bool(defval=true, title="5m", inline="tf", group="Dashboard")
bool Show15 = input.bool(defval=true, title="15m", inline="tf", group="Dashboard")
bool Show30 = input.bool(defval=true, title="30m", inline="tf", group="Dashboard")
bool Show60 = input.bool(defval=true, title="60m", inline="tf", group="Dashboard")
bool Show240 = input.bool(defval=true, title="240m", inline="tf", group="Dashboard")
string DashboardPosition = input.string(defval="Top Right", title="Position", options=["Top Right", "Top Left", "Bottom Right", "Bottom Left", "Middle Right"], group="Dashboard")
string DashboardFontSize = input.string(defval="Medium", title="Font Size", options=["Tiny", "Small", "Medium", "Large"], group="Dashboard", tooltip="Text size of the dashboard. The title is one size larger.")
color HeaderColor = input.color(defval=color.rgb(58, 66, 92), title="Header Color", group="Dashboard", tooltip="Background of the title bar; the column heading row uses a lighter shade of it.")
color StretchedColor = input.color(defval=color.rgb(255, 215, 0), title="Stretched Color", group="Dashboard", tooltip="Color of the z-score and state when price is beyond the threshold.")
 
//---------------------
//KALMAN FILTER
//---------------------
// Constant-velocity Kalman filter:
//   state      x = [level, slope]
//   transition F = [[1, 1], [0, 1]]   (level moves by slope each bar)
//   observation H = [1, 0]            (we only observe price)
//   process noise Q = q * [[1/3, 1/2], [1/2, 1]]  (random-acceleration model, dt = 1)
// Measurement noise is fixed at 1; only the ratio q/r changes the gain, so the
// instrument's price scale does not matter.
//
// var state is rolled back on every realtime update, so the open bar is always computed
// from the previous bar's finished state and closed bars never repaint. Each call site
// (the chart, and each request.security timeframe) keeps its own state.
float MeasurementNoise = 1.0
 
// Maps Smoothing to the noise ratio so the line is about as smooth as an EMA of that
// length (fitted by simulation: 5 -> 0.01, 20 -> 2.6e-5, 100 -> 2.5e-8).
float ProcessNoise = 0.01 * math.pow(5.0 / Smoothing, 4.3) * MeasurementNoise
 
kalman(float src, bool requirePriceAgreement) =>
    var float level = na
    var float slope = 0.0
    var float p00 = MeasurementNoise
    var float p01 = 0.0
    var float p11 = MeasurementNoise
 
    if not na(src)
        if na(level)
            // Start at the first price with no slope and an uncertain state.
            level := src
            slope := 0.0
            p00 := MeasurementNoise
            p01 := 0.0
            p11 := MeasurementNoise
        else
            float levelPred = level + slope
            float slopePred = slope
            float p00Pred = p00 + 2 * p01 + p11 + ProcessNoise / 3.0
            float p01Pred = p01 + p11 + ProcessNoise / 2.0
            float p11Pred = p11 + ProcessNoise
 
            float innovation = src - levelPred
            float s = p00Pred + MeasurementNoise
            float gainLevel = p00Pred / s
            float gainSlope = p01Pred / s
 
            level := levelPred + gainLevel * innovation
            slope := slopePred + gainSlope * innovation
            p00 := (1 - gainLevel) * p00Pred
            p01 := (1 - gainLevel) * p01Pred
            p11 := p11Pred - gainSlope * p01Pred
 
    // Scale is the root mean square of the residual, not a standard deviation around the
    // residual's own average: the value line IS the reference point, so a price that has
    // drifted above it for a while should read as stretched.
    float residual = src - level
    float scale = math.sqrt(math.sum(residual * residual, Lookback) / Lookback)
    float z = na(scale) ? na : scale > 0 ? residual / scale : 0.0
 
    // Slope as how far the line moves over one Smoothing period, in z-score units, so one
    // Flat Zone value works for every Smoothing and instrument (a trendless market reads
    // about 1.0 at any Smoothing, real trends 1.6-3+).
    float strength = na(scale) or scale == 0 ? 0.0 : slope * Smoothing / scale
    int slopeBias = strength > FlatZone ? 1 : strength < -FlatZone ? -1 : 0
 
    // Slope + Price: a line still sloping after the move has stopped (price holding on the
    // other side of it - average z of the last 5 bars more than 0.5 the wrong way) reads
    // flat instead. Without this the slope carries on for ~25-30 bars after a trend ends;
    // with it, ~10 (simulation, Smoothing 20).
    float averageZ = ta.sma(z, 5)
    bool disagrees = not na(averageZ) and ((slopeBias < 0 and averageZ > 0.5) or (slopeBias > 0 and averageZ < -0.5))
    int bias = requirePriceAgreement and disagrees ? 0 : slopeBias
 
    // Same warm-up as the NinjaTrader version (BarsRequiredToPlot = Lookback).
    bool ready = bar_index >= Lookback
    [level, scale, z, bias, ready]
 
// For request.security: the last CLOSED bar of that timeframe ([1] with lookahead on is
// the standard non-repainting form), plus the z-score before it for the Returning state.
closedValues() =>
    [kLevel, kScale, kz, kBias, kReady] = kalman(Source, HtfBiasMode == "Slope + Price")
    [kz[1], kBias[1], kz[2], kReady[1]]
 
// A timeframe row or bias needs a timeframe above the chart's. Anything else requests the
// chart's own timeframe (cheap) and is not shown.
bool chartIsTimeBased = timeframe.isseconds or timeframe.isminutes or timeframe.isdaily or timeframe.isweekly or timeframe.ismonthly
isHigher(string tf) =>
    tf != "" and (not chartIsTimeBased or timeframe.in_seconds(tf) > timeframe.in_seconds())
requestable(string tf) =>
    isHigher(tf) ? tf : timeframe.period
 
//---------------------
//CALCULATION
//---------------------
[valueLine, valueScale, z, chartBias, ready] = kalman(Source, BiasMode == "Slope + Price")
 
[biasZ, htfBias, biasPrevZ, biasReady] = request.security(syminfo.tickerid, requestable(BiasTimeframe), closedValues(), lookahead=barmerge.lookahead_on)
int barBias = isHigher(BiasTimeframe) ? (biasReady ? htfBias : 0) : chartBias
 
//---------------------
//PLOTS
//---------------------
biasColor(int b) =>
    b > 0 ? RisingColor : b < 0 ? FallingColor : FlatColor
 
// Pine transparency runs the other way to opacity.
color zBaseColor = biasColor(barBias)
color zColor = math.abs(z) > Threshold ? zBaseColor : color.new(zBaseColor, 100 - InsideOpacity)
plot(ready ? z : na, title="Z-Score", style=plot.style_columns, color=zColor)
 
hline(0, title="Zero Line", color=color.new(color.gray, 30), linestyle=hline.style_solid)
hline(Threshold, title="Upper Threshold", color=color.gray, linestyle=hline.style_dashed)
hline(-Threshold, title="Lower Threshold", color=color.gray, linestyle=hline.style_dashed)
 
bool drawValueLine = ready and ShowValueLine
bool drawBands = drawValueLine and ShowBands
plot(drawValueLine ? valueLine : na, title="Value Line", color=biasColor(chartBias), linewidth=2, force_overlay=true)
plot(drawBands ? valueLine + Threshold * valueScale : na, title="Upper Band", color=BandColor, linewidth=1, force_overlay=true)
plot(drawBands ? valueLine - Threshold * valueScale : na, title="Lower Band", color=BandColor, linewidth=1, force_overlay=true)
 
//---------------------
//DASHBOARD
//---------------------
[z5, b5, pz5, r5] = request.security(syminfo.tickerid, requestable(ShowDashboard and Show5 ? "5" : ""), closedValues(), lookahead=barmerge.lookahead_on)
[z15, b15, pz15, r15] = request.security(syminfo.tickerid, requestable(ShowDashboard and Show15 ? "15" : ""), closedValues(), lookahead=barmerge.lookahead_on)
[z30, b30, pz30, r30] = request.security(syminfo.tickerid, requestable(ShowDashboard and Show30 ? "30" : ""), closedValues(), lookahead=barmerge.lookahead_on)
[z60, b60, pz60, r60] = request.security(syminfo.tickerid, requestable(ShowDashboard and Show60 ? "60" : ""), closedValues(), lookahead=barmerge.lookahead_on)
[z240, b240, pz240, r240] = request.security(syminfo.tickerid, requestable(ShowDashboard and Show240 ? "240" : ""), closedValues(), lookahead=barmerge.lookahead_on)
 
tablePosition() =>
    switch DashboardPosition
        "Top Left" => position.top_left
        "Bottom Right" => position.bottom_right
        "Bottom Left" => position.bottom_left
        "Middle Right" => position.middle_right
        => position.top_right
 
tableTextSize() =>
    switch DashboardFontSize
        "Tiny" => size.tiny
        "Small" => size.small
        "Large" => size.large
        => size.normal
 
// The title is one size larger and bold, like the NinjaTrader dashboard.
titleTextSize() =>
    switch DashboardFontSize
        "Tiny" => size.small
        "Small" => size.normal
        "Large" => size.huge
        => size.large
 
chartLabel() =>
    int secs = timeframe.in_seconds()
    string tf = not chartIsTimeBased ? timeframe.period : secs < 60 ? str.tostring(secs) + "s" : secs < 86400 ? str.tostring(secs / 60) + "m" : timeframe.period
    "Chart (" + tf + ")"
 
var table dashboard = table.new(tablePosition(), 4, 9, bgcolor=color.new(color.black, 25), border_width=0, frame_width=0, force_overlay=true)
 
// One row: timeframe label, bias, z-score, state. Returns +1/-1/0 for the summary, or na
// while the timeframe is still warming up.
writeRow(int row, string label, float rz, int rb, float rpz, bool rready) =>
    color textColor = color.rgb(245, 245, 245)
    table.cell(dashboard, 0, row, label, text_color=textColor, text_size=tableTextSize(), text_halign=text.align_left)
    if not rready or na(rz)
        table.cell(dashboard, 1, row, "loading", text_color=FlatColor, text_size=tableTextSize(), text_halign=text.align_left)
        table.cell(dashboard, 2, row, "", text_size=tableTextSize())
        table.cell(dashboard, 3, row, "", text_size=tableTextSize())
        int(na)
    else
        string biasText = rb > 0 ? "▲ Up" : rb < 0 ? "▼ Down" : "– Flat"
        bool stretched = math.abs(rz) > Threshold
        bool returning = not stretched and not na(rpz) and math.abs(rpz) > Threshold
        table.cell(dashboard, 1, row, biasText, text_color=biasColor(rb), text_size=tableTextSize(), text_halign=text.align_left)
        table.cell(dashboard, 2, row, (rz >= 0 ? "+" : "") + str.tostring(rz, "0.0"), text_color=stretched ? StretchedColor : textColor, text_size=tableTextSize(), text_halign=text.align_right)
        table.cell(dashboard, 3, row, stretched ? "Stretched" : returning ? "Returning" : "–", text_color=stretched ? StretchedColor : textColor, text_size=tableTextSize(), text_halign=text.align_left)
        rb
 
if barstate.islast
    table.clear(dashboard, 0, 0, 3, 8)
    if ShowDashboard
        // Layout, top to bottom: title bar (name + symbol), column headings, one row per
        // timeframe, then the alignment summary in the majority bias color.
        color headingColor = color.new(HeaderColor, 55)
        table.cell(dashboard, 0, 0, "Kalman Value Bands", text_color=color.rgb(245, 245, 245), bgcolor=HeaderColor, text_size=titleTextSize(), text_halign=text.align_left, text_formatting=text.format_bold)
        table.merge_cells(dashboard, 0, 0, 2, 0)
        table.cell(dashboard, 3, 0, syminfo.ticker, text_color=color.rgb(245, 245, 245), bgcolor=HeaderColor, text_size=tableTextSize(), text_halign=text.align_right)
        table.cell(dashboard, 0, 1, "TF", text_color=FlatColor, bgcolor=headingColor, text_size=tableTextSize(), text_halign=text.align_left)
        table.cell(dashboard, 1, 1, "Bias", text_color=FlatColor, bgcolor=headingColor, text_size=tableTextSize(), text_halign=text.align_left)
        table.cell(dashboard, 2, 1, "Z", text_color=FlatColor, bgcolor=headingColor, text_size=tableTextSize(), text_halign=text.align_right)
        table.cell(dashboard, 3, 1, "State", text_color=FlatColor, bgcolor=headingColor, text_size=tableTextSize(), text_halign=text.align_left)
 
        int row = 2
        int up = 0
        int down = 0
        int flat = 0
 
        // The chart row shows the last closed bar: the previous one while a bar is still
        // forming, the latest one when the market is closed.
        bool forming = barstate.isrealtime and not barstate.isconfirmed
        array<int> results = array.new<int>()
        if ShowChartRow
            float rowZ = forming ? z[1] : z
            int rowBias = forming ? chartBias[1] : chartBias
            float rowPrevZ = forming ? z[2] : z[1]
            bool rowReady = forming ? ready[1] : ready
            results.push(writeRow(row, chartLabel(), rowZ, rowBias, rowPrevZ, rowReady))
            row += 1
        if Show5 and isHigher("5")
            results.push(writeRow(row, "5m", z5, b5, pz5, r5))
            row += 1
        if Show15 and isHigher("15")
            results.push(writeRow(row, "15m", z15, b15, pz15, r15))
            row += 1
        if Show30 and isHigher("30")
            results.push(writeRow(row, "30m", z30, b30, pz30, r30))
            row += 1
        if Show60 and isHigher("60")
            results.push(writeRow(row, "60m", z60, b60, pz60, r60))
            row += 1
        if Show240 and isHigher("240")
            results.push(writeRow(row, "240m", z240, b240, pz240, r240))
            row += 1
 
        for result in results
            if not na(result)
                if result > 0
                    up += 1
                else if result < 0
                    down += 1
                else
                    flat += 1
 
        color summaryColor = up > down and up > flat ? RisingColor : down > up and down > flat ? FallingColor : color.rgb(245, 245, 245)
        table.cell(dashboard, 0, row, str.format("{0} up · {1} flat · {2} down", up, flat, down), text_color=summaryColor, text_size=tableTextSize(), text_halign=text.align_left)
        table.merge_cells(dashboard, 0, row, 3, row)
 
//---------------------
//ALERTS
//---------------------
// Same as the NinjaTrader Signal value: the bar z returns back inside the threshold.
bool ReturnFromBelow = ready and z[1] < -Threshold and z >= -Threshold
bool ReturnFromAbove = ready and z[1] > Threshold and z <= Threshold
bool StretchedAbove = ready and z > Threshold and z[1] <= Threshold
bool StretchedBelow = ready and z < -Threshold and z[1] >= -Threshold
bool BiasTurnedUp = ready and barBias > 0 and barBias[1] <= 0
bool BiasTurnedDown = ready and barBias < 0 and barBias[1] >= 0
 
alertcondition(StretchedAbove, title="Stretched Above", message="{{ticker}} Kalman z-score moved above the upper threshold ({{close}})")
alertcondition(StretchedBelow, title="Stretched Below", message="{{ticker}} Kalman z-score moved below the lower threshold ({{close}})")
alertcondition(ReturnFromAbove, title="Return From Above", message="{{ticker}} Kalman z-score returned inside from above ({{close}})")
alertcondition(ReturnFromBelow, title="Return From Below", message="{{ticker}} Kalman z-score returned inside from below ({{close}})")
alertcondition(BiasTurnedUp, title="Bias Turned Up", message="{{ticker}} Kalman bias turned rising ({{close}})")
alertcondition(BiasTurnedDown, title="Bias Turned Down", message="{{ticker}} Kalman bias turned falling ({{close}})")

← 返回列表