OPEN-SOURCE SCRIPT
تم تحديثه

Kalman + CUSUM Segmentation

205
This indicator segments price with a model-based online change detector. A Kalman local-level filter estimates a drifting mean, shown as the orange line, and each bar it produces the one-step innovation, the gap between price and what the filter expected. That innovation is standardized by its own recursively estimated variance, and two CUSUM detectors watch it: one for a shift in the mean, one for a shift in dispersion, meaning volatility. When either crosses the threshold h the mean has structurally changed, so a new segment is cut and the accumulators reset. After a cut the Kalman covariance is briefly inflated so the mean re-adapts faster to the new level. The shaded background alternates per segment so boundaries are easy to read.
Around the mean is a Bollinger-style channel, except the center is the adaptive Kalman mean rather than a moving average, so it tracks trends with less lag. The z value in the panel is simply how many standard deviations price sits from that mean. The panel also shows both CUSUM values against their threshold and the length of the current segment in bars.
Inputs. Smoothness Q/R sets how tightly the Kalman mean follows price; only the ratio matters, so it behaves the same across instruments and price scales, and it is the knob for mean responsiveness. CUSUM threshold h is the main sensitivity knob and behaves like the penalty in change-point methods: raise it for fewer, larger cuts, lower it for more frequent cuts. CUSUM slack k is the standard allowance value, set to target a one-sigma shift. The dispersion CUSUM can be switched off for mean-only segmentation. The EWMA decay lambda controls the variance memory, with 0.94 being the RiskMetrics daily standard.
Scope. This is an online, causal detector: it only sees the past. It is a distinct model-based detector, not a substitute for globally optimal offline methods such as PELT run in Python or R, which place breakpoints more accurately in hindsight. Treat the segments and the z value as context, not as trade signals.
The method follows standard Kalman-residual CUSUM change detection (Kalman 1960; Page 1954; Mehra and Peschon 1971; Severo and Gama 2010; RiskMetrics 1996).
ملاحظات الأخبار
An online, model-based change detector that cuts price into structural segments as they form, with an adaptive channel around a Kalman mean.
Engine. A Kalman local-level filter tracks a drifting mean of price and outputs a one-step innovation (the prediction error) each bar. That innovation is standardized by its own recursively estimated variance, so under a correct model it is white with known variance. This is what lets a CUSUM threshold be statistically meaningful without an external lookback window.
Two CUSUM accumulators then watch the standardized innovation: one for a shift in the mean, one for a shift in dispersion (volatility). When either crosses the threshold h, the bar is marked as a structural change-point, a new segment begins, and the accumulators reset. On a cut the Kalman covariance is inflated so the mean re-adapts faster to the new level.
Channel. Around the Kalman mean is a Bollinger-style channel, but centered on the adaptive Kalman mean rather than an SMA, with a half-width set by the EWMA standard deviation of price about that mean. The z-score in the panel is how many sigma price sits from the mean.
Inputs. Q/R sets how closely the Kalman mean follows price; only the ratio matters, so it is independent of price scale. CUSUM slack k and threshold h set sensitivity: a higher h cuts only larger shifts, giving fewer segments. The dispersion CUSUM can be switched off for mean-only behavior. The EWMA decay lambda controls variance memory (0.94 is the RiskMetrics daily standard). A status panel shows the two CUSUM levels, the z-score, and the current segment length.
Scope and limits. This is a causal, online detector: it only sees the past and does not repaint. It is a distinct model-based detector, not a substitute for globally optimal offline methods such as PELT in Python or R, which place breakpoints more accurately in hindsight. Because segmentation reacts as structure forms, cuts land shortly after a regime actually changes, not exactly on the turn. Treat the segments, channel, and z-score as structural context, not as trade signals. This is a study tool and not financial advice.
References: Kalman (1960); Page (1954) for CUSUM; Mehra and Peschon (1971) for the Kalman-innovation approach to change detection; Severo and Gama (2010) for the mean-plus-dispersion CUSUM on Kalman residuals; RiskMetrics (1996) for the EWMA variance.
ملاحظات الأخبار
This indicator segments price with a model-based online change detector. A Kalman local linear trend filter estimates a drifting level and a drifting slope; the level is shown as the orange line. Because the slope is part of the state, a steady trend is what the model expects, so trend drift is not mistaken for structural change — only genuine breaks in the trend accumulate evidence. Each bar the filter produces the one-step innovation, the gap between price and what it expected, standardized by its own recursively estimated variance. Two CUSUM detectors watch that standardized innovation: one for a shift in the mean, one for a shift in dispersion, meaning volatility. When the mean CUSUM crosses the threshold the trend has structurally changed and a segment is cut. The cut is backdated to where the winning CUSUM run started, so the boundary lands where the change began rather than where it was detected. Cuts that would close a segment shorter than the minimum length are discarded and merged into the neighbor, so tiny fragments cannot exist. After an accepted cut the Kalman covariance is briefly inflated so the filter re-adapts faster to the new regime. The dispersion CUSUM always runs and fires an alert on volatility shifts; by default it does not cut, and a switch lets it split segments too.

The threshold h is derived from the data by default. Instead of guessing a sensitivity number, you state the average segment length you want, and a feedback controller nudges h bar by bar until the realized average matches it — segments running short push h up, segments running long pull it down. The panel shows the current h and the realized average length so you can watch it converge; early history runs at the starting h, and the value is most trustworthy near the right edge. A fixed-h mode remains available; for reference, with the standard allowance k = 0.5 a fixed h of 4 corresponds to an average false-alarm interval of roughly 168 bars, and h of 5 to roughly 465.

Each backdated cut draws a dashed vertical divider — the one authoritative segment-boundary marker. Between two dividers there is exactly one segment. Around the Kalman level is a Bollinger-style channel, except the center is the adaptive filter level rather than a moving average, so it tracks trends with less lag; the z value in the panel is how many standard deviations price sits from that level. The panel also shows both CUSUM values against the working threshold and the length of the current segment in bars. All decisions run on confirmed bars only: nothing repaints, dividers are drawn once and never moved, and the forming bar displays the last confirmed values.

Inputs. The level and slope noise ratios replace a single smoothness knob: the level ratio sets how tightly the level hugs price, the slope ratio sets how freely the trend may drift — lower makes the detector more sensitive to trend turns. Only the ratios matter, so behavior is independent of price scale. CUSUM allowance k is the standard value, 0.5 targeting a one-sigma shift. Target average segment length is the main knob in auto mode; minimum segment length is the direct lever against small segments and does not affect detection sensitivity. The EWMA decay lambda controls the variance memory and feeds both the cut decision and the band width; the default 0.97 is kept in sync with the companion script, while 0.94 is the RiskMetrics daily standard if you prefer snappier bands.

Scope. This is an online, causal detector: it only sees the past, and detection delay is irreducible for any causal method. It is not a substitute for globally optimal offline methods such as PELT run in Python or R, which place breakpoints more accurately in hindsight. Treat the segments and the z value as context, not as trade signals. The detection core is shared with the companion indicator "SegLR + VP + Regime (six-state)"; keep the constants in sync if you run both. The method follows standard Kalman-residual CUSUM change detection (Kalman 1960; Harvey 1989; Page 1954; Moustakides 1986; Hinkley 1971; Lorden 1971; Mehra and Peschon 1971; Severo and Gama 2010; RiskMetrics 1996).

إخلاء المسؤولية

لا يُقصد بالمعلومات والمنشورات أن تكون، أو تشكل، أي نصيحة مالية أو استثمارية أو تجارية أو أنواع أخرى من النصائح أو التوصيات المقدمة أو المعتمدة من TradingView. اقرأ المزيد في شروط الاستخدام.