本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// 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("Autocorrelation Periodogram [RC Tools]", shorttitle="RCT Periodogram", overlay=false, precision=1, max_bars_back=500)
// ─────────────────────────────────────────────────────────────────────────────
// ABOUT
// ─────────────────────────────────────────────────────────────────────────────
// Autocorrelation Periodogram — John Ehlers ("Cycle Analytics for Traders,"
// 2013). A public, well-documented technique. Independent implementation,
// built from the public method description.
//
// It estimates the market's DOMINANT CYCLE LENGTH, in bars, in three steps:
// 1. Isolate the cyclical band of price with a roofing filter (high-pass
// then Super Smoother low-pass), so trend drift and noise do not
// dominate.
// 2. Measure how well the filtered series correlates with itself at each
// delay (lag) from 0 up to the longest cycle of interest.
// 3. Convert that autocorrelation function into spectral "power" at each
// candidate cycle length (a discrete Fourier transform of the
// autocorrelations), smooth it, normalise it, and take the
// power-weighted centre of gravity of the strongest periods.
// A cycle-strength reading says how much that dominant cycle stands out
// right now, because a cycle length is only meaningful when one exists.
//
// Everything updates ONLY on confirmed bar close, so nothing here repaints.
// ─────────────────────────────────────────────────────────────────────────────
// ─────────────────────────────────────────────────────────────────────────────
// INPUTS
// ─────────────────────────────────────────────────────────────────────────────
float src = input.source(close, "Source", group="Roofing Pre-Filter")
int hpLen = input.int(48, "High-Pass Cutoff (bars)", minval=10, maxval=500, group="Roofing Pre-Filter",
tooltip="Cycles LONGER than this are removed as trend drift before the cycle search. Ehlers' classical default: 48.")
int lpLen = input.int(10, "Low-Pass Cutoff (bars)", minval=3, maxval=100, group="Roofing Pre-Filter",
tooltip="Cycles SHORTER than this are removed as noise before the cycle search. Ehlers' classical default: 10.")
int minPeriodIn = input.int(10, "Shortest Cycle Searched (bars)", minval=6, maxval=30, group="Cycle Search",
tooltip="Shortest cycle length the search will report.")
int maxPeriodIn = input.int(48, "Longest Cycle Searched (bars)", minval=20, maxval=80, group="Cycle Search",
tooltip="Longest cycle length the search will report. Also sets how many lags are correlated, so larger values cost more computation.")
int avgLen = input.int(3, "Correlation Averaging (bars)", minval=2, maxval=10, group="Cycle Search",
tooltip="Number of bars averaged in each autocorrelation reading. Ehlers' classical default: 3. Higher = smoother but slower to respond.")
float domThresh = input.float(0.5, "Dominance Threshold", minval=0.1, maxval=0.95, step=0.05, group="Cycle Search",
tooltip="Only cycle lengths whose normalised power is at or above this contribute to the dominant-cycle estimate (as a power-weighted average). Ehlers' classical default: 0.5.")
int outSmooth = input.int(3, "Output Smoothing (bars)", minval=1, maxval=20, group="Cycle Search",
tooltip="EMA smoothing on the reported dominant-cycle length. 1 = none.")
float strengthMin = input.float(0.6, "Clear-Cycle Strength", minval=0.05, maxval=0.99, step=0.05, group="Bands",
tooltip="Cycle strength (0-1) at or above this = a clear cycle. Below it, the dominant-cycle reading is flagged as 'No Clear Cycle' because the spectrum has no strong peak.")
float shortThresh = input.float(20.0, "Short / Medium Boundary (bars)", minval=8.0, maxval=60.0, group="Bands")
float longThresh = input.float(34.0, "Medium / Long Boundary (bars)", minval=10.0, maxval=79.0, group="Bands")
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 colShort = input.color(color.new(color.orange, 70), "Short Cycle", group="Colours")
color colMed = input.color(color.new(color.aqua, 70), "Medium Cycle", group="Colours")
color colLong = input.color(color.new(color.purple, 55), "Long Cycle", group="Colours")
color colNone = input.color(color.new(color.gray, 85), "No Clear Cycle", 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.")
// ─────────────────────────────────────────────────────────────────────────────
// STEP 1 — ROOFING PRE-FILTER
// Two-pole high-pass, then two-pole Super Smoother low-pass. See the
// Roofing Filter indicator for the full description of this stage.
// ─────────────────────────────────────────────────────────────────────────────
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])
// ─────────────────────────────────────────────────────────────────────────────
// STEPS 2-3 — AUTOCORRELATION, THEN SPECTRAL POWER
// Computed once per CONFIRMED bar only. The smoothed power spectrum is state
// carried from bar to bar, so it must not be advanced by intrabar ticks.
// ─────────────────────────────────────────────────────────────────────────────
int minP = math.min(minPeriodIn, maxPeriodIn - 5)
int maxP = maxPeriodIn
int warmBars = hpLen * 2 + maxP + avgLen
// Precomputed cosine/sine tables, index = (period - minP) * (maxP + 1) + lag
var float[] cosT = array.new_float()
var float[] sinT = array.new_float()
if barstate.isfirst
for p = minP to maxP
for k = 0 to maxP
float ang = 2.0 * math.pi * k / p
array.push(cosT, math.cos(ang))
array.push(sinT, math.sin(ang))
var float[] corrArr = array.new_float(maxP + 1, 0.0)
var float[] pwrArr = array.new_float(maxP + 1, 0.0)
var float maxPwr = 0.0
var float dcRaw = na
var float strength = na
if barstate.isconfirmed and bar_index >= warmBars
// 2. Pearson autocorrelation of the filtered series at each lag,
// averaged over `avgLen` bars.
for lag = 0 to maxP
float sx = 0.0
float sy = 0.0
float sxx = 0.0
float syy = 0.0
float sxy = 0.0
for m = 0 to avgLen - 1
float xv = filt[m]
float yv = filt[lag + m]
sx += xv
sy += yv
sxx += xv * xv
syy += yv * yv
sxy += xv * yv
float dd = (avgLen * sxx - sx * sx) * (avgLen * syy - sy * sy)
array.set(corrArr, lag, dd > 0.0 ? (avgLen * sxy - sx * sy) / math.sqrt(dd) : 0.0)
// 3. DFT of the autocorrelation function -> power at each candidate
// period; smoothed recursively (0.2 new / 0.8 old).
float pk = 0.0
for p = minP to maxP
float cs = 0.0
float sn = 0.0
int base = (p - minP) * (maxP + 1)
for k = avgLen to maxP
float ck = array.get(corrArr, k)
cs += ck * array.get(cosT, base + k)
sn += ck * array.get(sinT, base + k)
float sq = cs * cs + sn * sn
float r = 0.2 * sq * sq + 0.8 * array.get(pwrArr, p)
array.set(pwrArr, p, r)
pk := math.max(pk, r)
// Normalise against a slowly decaying running maximum.
maxPwr := math.max(0.995 * maxPwr, pk)
// Dominant cycle = power-weighted centre of gravity of the strong periods.
float spx = 0.0
float sp = 0.0
for p = minP to maxP
float pn = maxPwr > 0.0 ? array.get(pwrArr, p) / maxPwr : 0.0
if pn >= domThresh
spx += p * pn
sp += pn
if sp > 0.0
dcRaw := spx / sp
strength := maxPwr > 0.0 ? pk / maxPwr : 0.0
float dcSmooth = outSmooth > 1 ? ta.ema(dcRaw, outSmooth) : dcRaw
bool warmedUp = bar_index >= warmBars and not na(dcSmooth) and not na(strength)
// ── Confirmed-close-only display (non-repainting) ─────────────────────────────
var float dispDC = na
var float dispStrength = na
if barstate.isconfirmed
dispDC := warmedUp ? dcSmooth : na
dispStrength := warmedUp ? strength : na
// ─────────────────────────────────────────────────────────────────────────────
// BANDS
// Band codes: 0 = Short Cycle, 1 = Medium Cycle, 2 = Long Cycle,
// 3 = No Clear Cycle, 4 = Warming up
// ─────────────────────────────────────────────────────────────────────────────
bandOf(dc, st) =>
na(dc) or na(st) ? 4 :
st < strengthMin ? 3 :
dc < shortThresh ? 0 :
dc < longThresh ? 1 : 2
bandName(b) =>
b == 0 ? "Short Cycle" :
b == 1 ? "Medium Cycle" :
b == 2 ? "Long Cycle" :
b == 3 ? "No Clear Cycle" : "Warming up…"
bandColor(b) =>
b == 0 ? colShort :
b == 1 ? colMed :
b == 2 ? colLong :
b == 3 ? colNone : na
int currentBand = bandOf(dispDC, dispStrength)
// ─────────────────────────────────────────────────────────────────────────────
// BAND STREAK
// ─────────────────────────────────────────────────────────────────────────────
var int lastBand = na
var int streak = 0
if barstate.isconfirmed
if currentBand == lastBand
streak := streak + 1
else
streak := 1
lastBand := currentBand
// ─────────────────────────────────────────────────────────────────────────────
// PLOTS
// The dominant-cycle line dims when the spectrum has no clear peak, because
// a cycle length is only meaningful when a cycle is actually present.
// ─────────────────────────────────────────────────────────────────────────────
color lineCol = not na(dispStrength) and dispStrength >= strengthMin ? color.new(color.yellow, 0) : color.new(color.gray, 35)
plot(dispDC, "Dominant Cycle (bars)", color=lineCol, linewidth=2)
hline(shortThresh, "Short / Medium", color=color.new(color.gray, 50), linestyle=hline.style_dashed)
hline(longThresh, "Medium / Long", color=color.new(color.gray, 50), linestyle=hline.style_dashed)
bgcolor(paintPane and warmedUp ? bandColor(currentBand) : na, title="Cycle Background (pane)")
bgcolor(paintMainChart and warmedUp ? bandColor(currentBand) : na, force_overlay=true, title="Cycle 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, 6,
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, "Autocorr. Periodogram", 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 ? bandName(currentBand) : "Warming up…", text_color=warmedUp ? color.new(bandColor(currentBand), 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, "Dominant cycle", text_color=color.gray, text_size=size.small)
table.cell(t, 1, 3, not na(dispDC) ? str.tostring(dispDC, "#.0") + " bars" : "—", text_color=color.gray, text_size=size.small)
table.cell(t, 0, 4, "Cycle strength", text_color=color.gray, text_size=size.small)
table.cell(t, 1, 4, not na(dispStrength) ? str.tostring(dispStrength, "#.00") : "—", text_color=color.gray, text_size=size.small)
table.cell(t, 0, 5, "Search range", text_color=color.gray, text_size=size.small)
table.cell(t, 1, 5, str.tostring(minP) + " – " + str.tostring(maxP) + " bars", text_color=color.gray, text_size=size.small)
// ─────────────────────────────────────────────────────────────────────────────
// LIMITATIONS (see published description for the full-length version)
// ─────────────────────────────────────────────────────────────────────────────
// - A dominant-cycle estimate only means something when a cycle exists. In
// trending or random-looking stretches the spectrum has no clear peak and
// the reported length wanders; that is what the strength reading and the
// "No Clear Cycle" band are for.
// - Cycle length is an estimate of the market's recent rhythm, not a forecast
// of when the next turn will occur.
// - Resolution is coarser at longer periods: a 40-bar cycle is harder to pin
// to the exact bar than a 15-bar one.
// - Only cycles inside the search range can be reported. Cycles shorter than
// the minimum or longer than the maximum are invisible to it.
// - The roofing pre-filter adds a small, unavoidable lag.
// - Needs a long warm-up (about two high-pass cutoffs plus the longest cycle)
// before the reading is trustworthy.
// - Everything updates on confirmed bar close only. Nothing repaints.
// ─────────────────────────────────────────────────────────────────────────────