Ehlers Roofing Filter [RC Tools]

RC-Tools · study · 185 行 · 点赞 12 · 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/
// © RAC97
 
//@version=6
indicator("Ehlers Roofing Filter [RC Tools]", shorttitle="RCT Roofing Filter", overlay=false, precision=2)
 
// ─────────────────────────────────────────────────────────────────────────────
// ABOUT
// ─────────────────────────────────────────────────────────────────────────────
// Roofing Filter — John Ehlers ("Cycle Analytics for Traders," 2013). A public,
// well-documented technique. Independent implementation, built from the
// public filter descriptions.
//
// Price contains three things stacked together: a slow trend drift, a band of
// cyclical swings, and high-frequency noise. The Roofing Filter cascades two
// filters to keep only the middle band:
//   1. A two-pole HIGH-PASS filter removes slow drift (spectral dilation),
//      leaving oscillation around zero with no trend baked in.
//   2. A two-pole SUPER SMOOTHER (low-pass) filter then removes the
//      bar-to-bar noise from what is left.
// The output is a zero-centred oscillator that isolates the market's
// cyclical component. It is shown here in units of its own recent RMS so it
// is comparable across assets and price levels.
//
// Classification updates ONLY on confirmed bar close, so nothing here repaints.
// ─────────────────────────────────────────────────────────────────────────────
 
 
// ─────────────────────────────────────────────────────────────────────────────
// INPUTS
// ─────────────────────────────────────────────────────────────────────────────
float src = input.source(close, "Source", group="Roofing Filter")
int hpLen = input.int(48, "High-Pass Cutoff (bars)", minval=10, maxval=500, group="Roofing Filter",
     tooltip="Cycles LONGER than this are filtered out as trend drift. Shorter = more aggressive trend removal. Ehlers' classical default: 48.")
int lpLen = input.int(10, "Low-Pass Cutoff (bars)", minval=3, maxval=100, group="Roofing Filter",
     tooltip="Cycles SHORTER than this are filtered out as noise. Longer = smoother but slower. Ehlers' classical default: 10. Must be shorter than the high-pass cutoff; if not, it is capped just below it.")
int normLen = input.int(100, "RMS Normalisation Window", minval=20, maxval=1000, group="Roofing Filter",
     tooltip="The filter output is divided by its own root-mean-square over this many bars, so the plot is in comparable units (about -2 to +2 normally) on any asset.")
 
bool   showTable = input.bool(true, "Show Stats Table", group="Table")
string tablePos  = input.string("Top Right", "Table Position", options=["Top Right","Top Left","Bottom Right","Bottom Left"], group="Table")
 
color colPosRise = input.color(color.new(color.lime, 60), "Positive & Rising",     group="Colours")
color colPosFade = input.color(color.new(color.lime, 85), "Positive & Fading",     group="Colours")
color colNegFall = input.color(color.new(color.red,  60), "Negative & Falling",    group="Colours")
color colNegRec  = input.color(color.new(color.red,  85), "Negative & Recovering", group="Colours")
bool  paintPane  = input.bool(true,  "Paint Pane Background", group="Colours")
bool  paintMainChart = input.bool(false, "Paint Main Chart Background", group="Colours",
     tooltip="Uses force_overlay so the background also shows on the main price chart, even though this script lives in its own pane.")
 
 
// ─────────────────────────────────────────────────────────────────────────────
// ROOFING FILTER
// ─────────────────────────────────────────────────────────────────────────────
// Two-pole high-pass:
//   a  = (cos(w) + sin(w) - 1) / cos(w),   w = 0.707 * 2*pi / hpLen
//   HP = (1 - a/2)^2 * (x - 2x[1] + x[2]) + 2(1 - a)*HP[1] - (1 - a)^2 * HP[2]
// Two-pole Super Smoother (low-pass):
//   g  = exp(-1.414*pi / lp),  c2 = 2g*cos(1.414*pi / lp),  c3 = -g^2,  c1 = 1 - c2 - c3
//   F  = c1*(HP + HP[1])/2 + c2*F[1] + c3*F[2]
int   lpEff = math.min(lpLen, hpLen - 1)
 
float w  = 0.707 * 2.0 * math.pi / hpLen
float a1 = (math.cos(w) + math.sin(w) - 1.0) / math.cos(w)
 
float g  = math.exp(-1.414 * math.pi / lpEff)
float c2 = 2.0 * g * math.cos(1.414 * math.pi / lpEff)
float c3 = -g * g
float c1 = 1.0 - c2 - c3
 
var float hp   = 0.0
var float filt = 0.0
hp   := math.pow(1.0 - a1 / 2.0, 2) * (src - 2.0 * nz(src[1], src) + nz(src[2], src))
     + 2.0 * (1.0 - a1) * nz(hp[1]) - math.pow(1.0 - a1, 2) * nz(hp[2])
filt := c1 * (hp + nz(hp[1])) / 2.0 + c2 * nz(filt[1]) + c3 * nz(filt[2])
 
// ── Normalise by rolling RMS so the scale is comparable across assets ────────
float rms  = math.sqrt(ta.sma(filt * filt, normLen))
float norm = rms > 0.0 ? filt / rms : na
 
// Recursive filters need time to settle before the output is trustworthy.
bool warmedUp = bar_index >= math.max(hpLen, normLen) and not na(norm)
 
// ── Confirmed-close-only display (non-repainting) ─────────────────────────────
// State codes: 0 = Positive & Rising, 1 = Positive & Fading,
//              2 = Negative & Falling, 3 = Negative & Recovering, 4 = Warming up
var float dispNorm     = na
var float prevNorm     = na
var int   currentState = 4
if barstate.isconfirmed
    prevNorm := dispNorm
    dispNorm := warmedUp ? norm : na
    bool rising = na(prevNorm) ? true : dispNorm > prevNorm
    currentState := na(dispNorm) ? 4 : (dispNorm >= 0.0 ? (rising ? 0 : 1) : (rising ? 3 : 2))
 
 
// ─────────────────────────────────────────────────────────────────────────────
// LABELS & COLOURS
// ─────────────────────────────────────────────────────────────────────────────
stateName(s) =>
    s == 0 ? "Positive & Rising" :
     s == 1 ? "Positive & Fading" :
     s == 2 ? "Negative & Falling" :
     s == 3 ? "Negative & Recovering" : "Warming up…"
 
stateColor(s) =>
    s == 0 ? colPosRise :
     s == 1 ? colPosFade :
     s == 2 ? colNegFall :
     s == 3 ? colNegRec : na
 
 
// ─────────────────────────────────────────────────────────────────────────────
// STATE STREAK
// ─────────────────────────────────────────────────────────────────────────────
var int lastState = na
var int streak    = 0
if barstate.isconfirmed
    if currentState == lastState
        streak := streak + 1
    else
        streak := 1
        lastState := currentState
 
 
// ─────────────────────────────────────────────────────────────────────────────
// PLOTS
// ─────────────────────────────────────────────────────────────────────────────
plot(dispNorm, "Roofing Filter (RMS units)", color=color.new(color.yellow, 0), linewidth=2)
hline(0,  "Zero",  color=color.gray, linestyle=hline.style_solid)
hline(1,  "+1 RMS", color=color.new(color.gray, 40), linestyle=hline.style_dashed)
hline(-1, "-1 RMS", color=color.new(color.gray, 40), linestyle=hline.style_dashed)
hline(2,  "+2 RMS", color=color.new(color.gray, 70), linestyle=hline.style_dotted)
hline(-2, "-2 RMS", color=color.new(color.gray, 70), linestyle=hline.style_dotted)
 
bgcolor(paintPane and warmedUp ? stateColor(currentState) : na, title="Roofing Background (pane)")
bgcolor(paintMainChart and warmedUp ? stateColor(currentState) : na, force_overlay=true, title="Roofing Background (main chart)")
 
 
// ─────────────────────────────────────────────────────────────────────────────
// STATS TABLE
// ─────────────────────────────────────────────────────────────────────────────
getPosition(p) =>
    p == "Top Left"     ? position.top_left :
     p == "Bottom Right" ? position.bottom_right :
     p == "Bottom Left"  ? position.bottom_left : position.top_right
 
if showTable and barstate.islast
    var table t = table.new(getPosition(tablePos), 2, 5,
         bgcolor=color.new(color.black, 15), border_width=1, border_color=color.gray,
         frame_color=color.gray, frame_width=1)
 
    table.cell(t, 0, 0, "Roofing Filter", text_color=color.white, text_size=size.small, bgcolor=color.new(color.black, 0))
    table.cell(t, 1, 0, "", bgcolor=color.new(color.black, 0))
 
    table.cell(t, 0, 1, "Current", text_color=color.white, text_size=size.small)
    table.cell(t, 1, 1, warmedUp ? stateName(currentState) : "Warming up…", text_color=warmedUp ? color.new(stateColor(currentState), 0) : color.gray, text_size=size.small)
 
    table.cell(t, 0, 2, "In state for", text_color=color.gray, text_size=size.small)
    table.cell(t, 1, 2, warmedUp ? str.tostring(streak) + " bars" : "—", text_color=color.gray, text_size=size.small)
 
    table.cell(t, 0, 3, "Reading (RMS units)", text_color=color.gray, text_size=size.small)
    table.cell(t, 1, 3, not na(dispNorm) ? str.tostring(dispNorm, "#.00") : "—", text_color=color.gray, text_size=size.small)
 
    table.cell(t, 0, 4, "Passband", text_color=color.gray, text_size=size.small)
    table.cell(t, 1, 4, str.tostring(lpEff) + " – " + str.tostring(hpLen) + " bars", text_color=color.gray, text_size=size.small)
 
 
// ─────────────────────────────────────────────────────────────────────────────
// LIMITATIONS (see published description for the full-length version)
// ─────────────────────────────────────────────────────────────────────────────
// - The Roofing Filter isolates a BAND of cycle lengths. It is not a trend
//   indicator: by design it removes the trend, so a long steady trend reads
//   as near zero.
// - It is a filter, not a forecast. Its output is a smoothed view of what
//   price has already done, with a small, unavoidable lag from the low-pass.
// - Passband choice matters: the cutoffs decide which cycles survive. There
//   is no single correct pair for every asset or timeframe.
// - Recursive filters need time to settle. Early bars on a new chart are
//   not reliable, which is why the plot starts after a warm-up period.
// - RMS normalisation puts readings in comparable units but is relative to
//   recent history, so the same absolute move reads smaller after a volatile
//   stretch than after a quiet one.
// - Score and state update on confirmed bar close only. Nothing repaints.
// ─────────────────────────────────────────────────────────────────────────────

← 返回列表