Changepoint Detection: Finding Regime Shifts in Financial Data

Detect volatility regime shifts in the S&P 500 with the PELT algorithm. Compare PELT vs Binary Segmentation and align changepoints with financial crises.

Cover Image for Changepoint Detection: Finding Regime Shifts in Financial Data

You're analysing years of market returns, and one set of assumptions may not describe the whole period well. Quiet stretches and more turbulent ones can have different statistical behaviour. Changepoint detection gives us a way to look for the boundaries between such periods in a historical series. Those boundaries can help us examine the data in segments instead of treating every observation as part of one regime.

Those boundaries change which observations a fitted model must explain. We compare penalties with Pruned Exact Linear Time (PELT), which finds 45 changepoints over 41 years at penalty 20. Their alignment with known events helps interpret the segmentation, while the penalty controls how many boundaries the fit supports.

By the end of this post, you'll detect volatility regime shifts in S&P 500 data using PELT, compare it with Binary Segmentation, understand how the penalty parameter controls the trade-off between sensitivity and false positives, and see how detected changepoints align with real financial crises. We use PELT here because it finds the globally optimal set of changepoints in linear time and works offline on historical data, which is ideal for retrospective analysis of decades of returns. For real-time, streaming applications, Bayesian online changepoint detection updates regime beliefs as each new observation arrives.

The Data: 41 Years of S&P 500 Returns

We use daily S&P 500 data from January 1985 to April 2026: over 10,000 trading days covering Black Monday, the dot-com bubble, the Global Financial Crisis, COVID, the 2022 rate hike sell-off, the 2025 Liberation Day tariffs, and the 2026 Iran war. This is the same index used in the original R analysis we're translating, extended to cover the full modern era.

S&P 500 price chart with colour-coded volatility regimes detected by PELT, showing green for calm periods and red for turbulent ones

The colour-coded background shows volatility regimes detected by PELT: green for calm periods, red/yellow for turbulent ones. The algorithm picks up every major crisis without being told when they occurred.

Quick Win: Detecting Regime Shifts

Click the badge to run this yourself:

Open In Colab

import numpy as np
import pandas as pd
import yfinance as yf
import ruptures as rpt

# Download 41 years of S&P 500 data
sp = yf.download("^GSPC", start="1984-12-25",
                 auto_adjust=True, progress=False)
sp = sp.loc["1985-01-02":]
close = sp["Close"].squeeze()

# Compute log returns
log_ret = np.log(close / close.shift(1)).dropna()
signal = log_ret.values.reshape(-1)
print(f"{len(signal)} trading days, {log_ret.index[0].date()} to {log_ret.index[-1].date()}")
10392 trading days, 1985-01-03 to 2026-04-02

Now the key part: fit PELT and detect changepoints.

# PELT with normal model (detects mean + variance shifts)
algo = rpt.Pelt(model="normal", min_size=10, jump=5).fit(signal)
breakpoints = algo.predict(pen=20)
n_changepoints = len(breakpoints) - 1
print(f"Detected {n_changepoints} changepoints")
Detected 45 changepoints

PELT found 45 points where the statistical character of daily returns shifted. Each one marks the boundary between two volatility regimes.

What Just Happened?

The Changepoint Problem

A changepoint is a point in time where the data-generating process changes. Before the changepoint, the data follows one distribution (say, low-volatility returns). After it, the data follows a different distribution (high-volatility returns). The goal is to find all such points, given only the data.

Formally, we're partitioning the time series y1,…,yny_1, \ldots, y_n into segments [tk−1+1,…,tk][t_{k-1}+1, \ldots, t_k] such that the data within each segment is statistically homogeneous, but adjacent segments differ.

The Cost Function Approach

Changepoint detection frames this as an optimisation problem. Define a cost function C(ya:b)C(y_{a:b}) that measures how well a single distribution fits the data from time aa to time bb. For the normal model, this is the negative log-likelihood:

C(ya:b)=(b−a)⋅log⁡σ^a:b2C(y_{a:b}) = (b - a) \cdot \log \hat{\sigma}^2_{a:b}

where σ^a:b2\hat{\sigma}^2_{a:b} is the sample variance of the segment. Low-variance segments have low cost; segments that mix two regimes have high cost because the combined variance is inflated.

The total cost for a segmentation with KK changepoints is:

∑k=0KC(ytk:tk+1)+K⋅β\sum_{k=0}^{K} C(y_{t_k:t_{k+1}}) + K \cdot \beta

where β\beta is the penalty per changepoint. Without the penalty, the optimal solution would put a changepoint at every observation. The penalty forces the algorithm to justify each additional changepoint by a sufficient reduction in cost.

Reading the Output

The predict() call returns a list of indices where the data shifts. Each index marks the end of a segment. The last element is always nn (the end of the series). So 45 changepoints means 46 segments, each with its own statistical character.

Daily log returns colour-coded by volatility regime, with high-volatility periods in red and calm periods in green

The regime colouring makes the structure visible at a glance. The 2008 financial crisis, COVID crash, and Black Monday are obvious high-volatility regimes (red). The long calm periods of the mid-1990s and 2013-2017 are green. The algorithm finds this structure purely from the data, with no knowledge of financial history.

Rolling Windows and Their Limits

A rolling standard deviation can show volatility trends, but it has two problems. First, it smears the boundary: the window gradually incorporates new-regime data, so the transition is blurred over the window length. Second, you have to choose the window size, which is itself a regime-dependent parameter. Changepoint detection gives you sharp boundaries and determines the regime structure from the data itself.

Going Deeper

PELT: Linear-Time Exact Changepoint Detection

The naive approach to finding optimal changepoints is O(Qn2)O(Qn^2) where QQ is the number of changepoints and nn is the series length. For 10,000 data points, this is impractical.

Killick, Fearnhead, and Eckley (2012) introduced PELT (Pruned Exact Linear Time), which achieves exact optimality with O(n)O(n) average complexity. The trick is a pruning rule: at each step, PELT checks whether a candidate changepoint can ever be part of the optimal solution. If not, it's discarded permanently. Under mild conditions (the penalty is at least logarithmic in nn), most candidates are pruned early, giving linear runtime.

# PELT is the default and best choice for most problems
algo = rpt.Pelt(model="normal", min_size=10, jump=5).fit(signal)
breakpoints = algo.predict(pen=20)

The jump=5 parameter means PELT considers every 5th index as a candidate changepoint. This trades a tiny amount of precision for a 5x speed improvement on long series. For 10,000+ points, this is a practical necessity.

Binary Segmentation: The Fast Approximation

Binary Segmentation (Scott and Knott, 1974) takes a different approach: find the single best changepoint, split the data there, then recursively find the best changepoint in each half. It's O(nlog⁡n)O(n \log n) but only approximate: it can miss changepoints that are only visible when nearby changepoints are already accounted for.

algo_bs = rpt.Binseg(model="normal", min_size=10, jump=5).fit(signal)
bkps_bs = algo_bs.predict(n_bkps=45)  # fix the number of changepoints

Comparison of PELT and Binary Segmentation on the same data, both with 45 changepoints, showing similar but not identical regime boundaries

With the same number of changepoints, PELT and Binary Segmentation produce similar but not identical segmentations. The key differences show up in transition periods (like 2001-2003) where PELT, being globally optimal, finds the true boundaries while BinSeg may misplace them by a few weeks.

The Penalty: Balancing Sensitivity and Specificity

The penalty parameter β\beta is the single most important choice. Too low, and you detect hundreds of spurious changepoints (noise). Too high, and you miss real regime shifts.

Penalty sensitivity curve showing how the number of changepoints drops from over 700 to near zero as the penalty increases from 1 to 1000 on a log scale

At β=1\beta = 1, PELT finds over 700 changepoints (roughly one every two weeks). At β=200\beta = 200, it finds only 8. Our choice of β=20\beta = 20 gives 45 changepoints, which aligns well with known financial events.

Common penalty selection methods:

MethodFormulaWhen to use
BICβ=p⋅log⁡n\beta = p \cdot \log nDefault for most problems; pp is the number of parameters per segment
AICβ=2p\beta = 2pMore liberal (more changepoints)
ManualDomain-specificWhen you know roughly how many regimes to expect

For 10,392 data points with a normal model (p=2p = 2), BIC gives β=2×log⁡(10392)≈18.5\beta = 2 \times \log(10392) \approx 18.5, which is close to our β=20\beta = 20.

Regime Duration

The distribution of regime durations tells us something about market microstructure:

Histogram of regime durations showing a right-skewed distribution with median 152 days and mean 221 days

The median regime lasts about 158 trading days (~7 months), but the distribution is heavily right-skewed: a few calm regimes persist for years (the longest is 1,000 trading days, roughly 4 years), while crisis regimes tend to be short and sharp. The mean (226 days) exceeds the median because of these long calm tails.

Changepoints Aligned with Financial Events

The real test of a changepoint method is whether it finds meaningful structure. Here's PELT with a slightly higher penalty (β=50\beta = 50, 24 changepoints) overlaid with known financial events:

Dual-panel chart showing S&P 500 price with changepoint lines and annotated financial events in the top panel, and colour-coded absolute returns in the bottom panel

The algorithm detects Black Monday (7 days early), the Lehman collapse (11 days early), the COVID crash (3 days early), and the 2025 Liberation Day tariffs (on the exact day). It "detects" these events early because the volatility regime actually shifts before the headline event. Markets often become turbulent in the days before the crash itself, as informed participants reposition.

The Iran war (February 2026) is labelled on the chart but PELT does not flag it as a separate regime change. By that point, the market was already in the turbulent regime triggered by Liberation Day tariffs, and the additional volatility from the conflict did not constitute a statistically distinct shift. For an online, real-time approach to the same problem, see our Bayesian online changepoint detection post, which reaches the same conclusion.

The Exponential Distribution Connection

Squared returns are a natural proxy for variance. If log returns are normally distributed with variance σ2\sigma^2, then squared returns follow a scaled chi-squared distribution with one degree of freedom, which is well-approximated by an exponential. This means we can also frame changepoint detection as finding shifts in the rate parameter of an exponential distribution fitted to squared returns.

Histogram of squared daily returns overlaid with an exponential distribution fit, showing the characteristic L-shape

The exponential fit captures the overall shape. The histogram is dominated by near-zero values (calm days), with a long right tail of extreme moves (crises). Changepoints in the rate parameter of this exponential correspond to shifts between low-variance and high-variance regimes.

Changepoints vs HMMs: Hard Boundaries vs Soft Probabilities

Our HMM post tackled regime detection from a different angle: hidden Markov models assign each time step a probability of being in each regime, with smooth transitions. Changepoint detection gives hard boundaries with no transition period.

FeatureChangepoint (PELT)HMM
BoundariesHard (exact day)Soft (probability of each regime)
Regime countPenalty-controlledFixed by model specification
StationarityAssumes segments are stationaryAllows within-regime dynamics
SpeedO(n)O(n) with PELTO(nK2)O(nK^2) where KK = states
Best forPost-hoc analysis, segmentationOnline filtering, forecasting

Use PELT when you want to segment historical data into clean periods (for backtesting, risk measurement, or training separate models per regime). Use HMMs when you need real-time regime probabilities or when transitions are gradual.

Hyperparameter Choices

ParameterValueWhy
DataS&P 500, 1985-2026Original R code index; 41 years covering major crises
ReturnsLog returnsStandard in academic finance; continuous, symmetric
ModelnormalDetects changes in both mean and variance
Penalty20Close to BIC for n=10392; gives 45 changepoints aligned with events
min_size10Minimum 2 weeks between changepoints; avoids spurious detections
jump5Checks every 5th candidate; 5x speedup with negligible precision loss

Where This Comes From

Killick, Fearnhead, and Eckley (2012): The PELT Paper

Rebecca Killick, Paul Fearnhead, and Idris Eckley introduced PELT in their 2012 paper "Optimal Detection of Changepoints with a Linear Computational Cost", published in the Journal of the American Statistical Association.

The key insight is a pruning inequality. At time tt, if adding a changepoint at some earlier time ss can never improve on the best segmentation up to tt, then ss can be permanently removed from consideration. Formally, if:

F(s)+C(ys+1:t)+β≥F(t)F(s) + C(y_{s+1:t}) + \beta \geq F(t)

where F(t)F(t) is the optimal cost up to time tt, then ss can never be an optimal last changepoint for any future time t′>tt' > t. Under the condition that the cost function satisfies a "sufficient change" property, the number of candidates that survive pruning grows linearly with nn.

"The resulting method, which we call PELT, is shown through simulation studies to be substantially more accurate than existing methods while being computationally more efficient." -- Killick, Fearnhead & Eckley (2012)

The Broader Landscape

Changepoint detection has a long history. Scott and Knott (1974) introduced Binary Segmentation for grouping means in ANOVA. Bai and Perron (2003) developed efficient algorithms for multiple structural breaks in econometric models. Truong, Oudre, and Vayatis (2020) provide a comprehensive review of offline changepoint methods in their paper accompanying the ruptures library.

The field continues to evolve. Recent work includes Bayesian online changepoint detection (Adams and MacKay, 2007) for streaming data, and kernel-based methods that detect distributional changes beyond mean and variance.

Further Reading

Interactive Tools

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions