OPEN-SOURCE SCRIPT

CUSUM Structural Break Detector

700
Description
This indicator implements the symmetric CUSUM (Cumulative Sum) filter from Marcos López de Prado's Advances in Financial Machine Learning (Chapter 2) as an overlay on any chart. It detects structural breaks in the price process by accumulating log-return deviations against a dynamic, volatility-adaptive threshold.

What it does
Most chart indicators sample market data at fixed time intervals. The CUSUM filter takes a different approach: it only flags an event when the price process has accumulated enough cumulative deviation from its baseline to indicate that something structurally meaningful has changed. This is the event-based sampling method used in quantitative finance before applying machine learning models to market data.

The filter maintains two accumulators:

S⁺ = max(0, S⁺_prev + log_return)
S⁻ = min(0, S⁻_prev + log_return)

An upward structural break is flagged when S⁺ ≥ h. A downward break is flagged when S⁻ ≤ −h. Both accumulators reset to zero on trigger — this prevents consecutive events clustering in the same trend. The threshold h is adaptive:

h = multiplier × realized_volatility

where realized volatility is estimated as a rolling standard deviation of log returns. This makes the filter regime-aware: in high-volatility periods the threshold widens automatically, requiring larger price moves before flagging an event.

Visual output
▲ (teal, below bar) — upward structural break. The positive accumulator has crossed h.
▼ (amber, above bar) — downward structural break. The negative accumulator has crossed −h.
Volatility bands — ±h expressed in price units around close. Shows the live threshold.
Background shading (faint red) — appears when realized σ exceeds 1.5× its rolling median, indicating a high-volatility regime.
Info table (bottom right) — shows current σ, current h, regime state, and cumulative event count.

How to use it
These markers are not buy or sell signals. They are sampling points — moments where the price process has undergone a statistically meaningful shift. In the AFML pipeline they serve as the input to triple-barrier labeling: for each flagged event, you define a forward price window with a profit-take barrier, a stop-loss barrier, and a timeout horizon, and record which barrier is hit first. That outcome becomes the training label for a supervised ML model.
Use the markers to identify which historical moments would have been worth labeling and studying. Use the alerts (JSON format, compatible with any webhook receiver) to log events in real time as they occur.

Parameters
Volatility lookback (default 20): Rolling window for realized volatility estimation. Shorter values react faster to volatility changes; longer values produce a smoother threshold.
Threshold multiplier k (default 1.0): Controls sensitivity. Higher values produce fewer, higher-confidence events. For daily equity bars, 1.5–2.0 is recommended. For intraday data, 0.7–0.8. For crypto, 1.5 or higher given baseline volatility.
Min bar gap (default 5): Minimum number of bars required between consecutive events. Prevents clustering on noisy instruments.
Show volatility bands (default on): Toggles the ±h overlay.

Alert format
Each event triggers a TradingView alert with a structured message containing the ticker, direction, close price, realized volatility, threshold value, and bar timestamp. Configure alert conditions in the TradingView alert manager after adding the indicator to your chart.

Reference
López de Prado, M. (2018). Advances in Financial Machine Learning. Wiley. Chapter 2: Financial Data Structures.
Page, E.S. (1954). Continuous inspection schemes. Biometrika, 41(1/2), 100–115.

Disclaimer

The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.