New observations arrive while you're watching a time series, and you want to know whether its behaviour has changed. Our earlier changepoint detector examined a complete history, which is useful for looking back. Monitoring as data arrives calls for a running estimate that can change with each observation. Bayesian online changepoint detection maintains probabilities for possible regime ages.
The COVID example tracks uncertainty as returns arrive. From 21 to 25 February 2020, probability shifts towards recent regime ages. The probability of an age under ten trading days rises from 0.4% to above 25%. We implement BOCD to read that changing distribution.
By the end of this post, you will implement BOCD from scratch in NumPy, run it on the same S&P 500 daily log returns from our PELT post, watch it detect the COVID crash in real time, and understand how to read the run-length posterior as a continuous probability rather than a binary signal.
The Algorithm at a Glance
BOCD tracks a run length: the number of observations since the last changepoint. At each time step, two things can happen: the current run continues (run length grows by 1), or a changepoint occurs (run length resets to 0). The algorithm maintains a probability over all possible run lengths and updates it as each observation arrives.
The key insight from Adams and MacKay (2007) is that you do not need to enumerate every possible changepoint history. The run-length posterior at time depends only on the run-length posterior at time and the new observation . This makes the algorithm online and recursive.
Quick Win: Detecting Regime Shifts in Real Time
Click the badge to run this yourself:

The animation shows BOCD processing S&P 500 returns day by day through 2019-2020. During the calm pre-COVID period, the MAP run length grows steadily (the algorithm is confident the same regime has been running for months). When the COVID crash hits in late February 2020, the run length collapses to zero and the posterior probability of a new regime rises from 0.4% to 99.9% within a week.
import numpy as np
import pandas as pd
import yfinance as yf
from scipy.special import gammaln
# Download 41 years of S&P 500 daily log returns (same as PELT post)
sp = yf.download("^GSPC", start="1984-12-25",
auto_adjust=True, progress=False)
sp = sp.loc["1985-01-02":]
close = sp["Close"].squeeze()
log_ret = np.log(close / close.shift(1)).dropna()
signal = log_ret.values.reshape(-1)
dates = log_ret.index
print(f"{len(signal)} trading days, {dates[0].date()} to {dates[-1].date()}")
10392 trading days, 1985-01-03 to 2026-04-02
Now the BOCD implementation. The core is surprisingly compact:
class StudentT:
"""Posterior predictive for Normal-Inverse-Gamma conjugate model."""
def __init__(self, mu0=0, kappa0=1, alpha0=0.01, beta0=0.01):
self.mu0 = mu0
self.kappa0 = kappa0
self.alpha0 = alpha0
self.beta0 = beta0
self.mu = np.array([mu0])
self.kappa = np.array([kappa0])
self.alpha = np.array([alpha0])
self.beta = np.array([beta0])
def log_pred_prob(self, x):
"""Log predictive probability under each run-length hypothesis."""
df = 2 * self.alpha
scale = self.beta * (self.kappa + 1) / (self.alpha * self.kappa)
return (
gammaln((df + 1) / 2) - gammaln(df / 2)
- 0.5 * np.log(np.pi * df * scale)
- ((df + 1) / 2) * np.log(1 + (x - self.mu)**2 / (df * scale))
)
def update(self, x):
"""Bayesian update of sufficient statistics."""
new_mu = (self.kappa * self.mu + x) / (self.kappa + 1)
new_kappa = self.kappa + 1
new_alpha = self.alpha + 0.5
new_beta = (self.beta
+ self.kappa * (x - self.mu)**2 / (2 * (self.kappa + 1)))
self.mu = np.concatenate([[self.mu0], new_mu])
self.kappa = np.concatenate([[self.kappa0], new_kappa])
self.alpha = np.concatenate([[self.alpha0], new_alpha])
self.beta = np.concatenate([[self.beta0], new_beta])
def bocd(data, hazard_rate=250, short_threshold=10):
"""Bayesian Online Changepoint Detection (Adams & MacKay 2007).
Returns R (full run-length matrix), maxes (MAP run length),
and p_short (probability that the current regime is younger
than short_threshold days).
"""
T = len(data)
R = np.zeros((T + 1, T + 1))
R[0, 0] = 1.0
model = StudentT()
h = 1.0 / hazard_rate
maxes = np.zeros(T)
p_short = np.zeros(T)
for t in range(T):
x = data[t]
pred = np.exp(model.log_pred_prob(x))
# Growth: extend each run length by 1
R[1:t+2, t+1] = R[:t+1, t] * pred * (1 - h)
# Changepoint: reset to run_length = 0
R[0, t+1] = np.sum(R[:t+1, t] * pred * h)
# Normalise
evidence = R[:t+2, t+1].sum()
if evidence > 0:
R[:t+2, t+1] /= evidence
model.update(x)
maxes[t] = np.argmax(R[:t+2, t+1])
p_short[t] = R[:min(short_threshold, t+2), t+1].sum()
return R, maxes, p_short
Run it:
R, maxes, p_short = bocd(signal, hazard_rate=250)

The bottom panel is the signature BOCD visualisation: the run-length posterior heatmap. Each column is a probability distribution over run lengths at that point in time. During calm periods, you see bright diagonal streaks rising from lower-left to upper-right as the run length grows steadily. At each crisis (Black Monday, dot-com bust, Lehman, COVID), the streak collapses back to run length 0 as the algorithm detects a new regime.
Not a Binary Signal: A Rising Probability
The heatmap gives you the full posterior, but for practical use you need a single number you can act on. We define : the probability that the current regime started fewer than 10 trading days ago. When this probability is low (near 0.4%, its baseline under a constant hazard of ), the algorithm is confident that the current regime has been running for a long time. When it rises sharply, evidence is accumulating that a new regime has begun.
This is the key advantage of the Bayesian approach: you do not get a binary "changepoint detected" flag. You get a probability that rises as evidence accumulates, and you choose the threshold at which to act. A 5% threshold gives you earlier signals with more false alarms. A 50% threshold waits for stronger evidence but reacts later.

The three panels above show how behaves around three events. During COVID, the probability rose from 0.4% on February 21 to 1.7% on February 24, crossed 25% on February 25, and reached 99.9% by February 27. For the Liberation Day tariffs, it jumped from 0.4% to 7.9% in a single day (April 3), then hit 99.99% the next day. For the Iran war, the probability never left its baseline: the market was already in a turbulent regime from tariffs, and the additional volatility did not register as a statistically distinct shift.

The full timeline shows across 41 years of S&P 500 data. Every major crisis produces a sharp spike. The 5% threshold (dashed orange) triggers first; the 50% threshold (dashed red) follows shortly after when the evidence is overwhelming.
What Just Happened?
The algorithm maintains a probability distribution over one integer: the run length , which counts how many observations have elapsed since the last changepoint. Think of it as a stopwatch that might reset at any moment. BOCD does not output a binary "changepoint detected" flag. It tells you how confident it is in the current regime's age, as a full probability distribution that you can summarise and threshold however you choose.
The Three Operations Per Observation
Every time a new return arrives, the algorithm performs three steps:
1. Growth. Each existing run-length hypothesis extends by one. If the algorithm thought "the current regime has been running for 100 days" with probability 0.3, it now considers "101 days" with that same probability, scaled by how well fits a regime of that length.
2. Changepoint. The algorithm computes the probability that a changepoint just occurred. This pools evidence from all existing run-length hypotheses, weighted by the hazard function , which encodes how likely a regime change is at any given moment.
3. Normalisation. The run-length distribution is renormalised so it sums to 1.
The Conjugate Model
We do not know the mean or variance of returns in the current regime. BOCD handles this with a conjugate prior: the Normal-Inverse-Gamma distribution. This is the natural prior for a Gaussian with unknown mean and unknown variance.
As observations accumulate within a regime, the posterior sharpens: the algorithm becomes increasingly confident about the regime's mean return and volatility. When a changepoint occurs and the run length resets, the prior resets too, and the algorithm starts learning the new regime's parameters from scratch.
The predictive distribution (what do we expect the next return to look like, given the current regime?) is a Student-t distribution. This is heavier-tailed than a Gaussian, which is appropriate for financial returns and provides natural robustness to outliers.
The Hazard Function
The hazard function answers: given that the current regime has lasted observations, what is the probability it ends now? If you have encountered hazard functions in survival analysis, the concept is the same: it is the instantaneous rate of "failure" (here, regime death) given survival to time . We use a constant hazard , which implies a geometric distribution on regime durations with expected length . You could also use a time-varying hazard if you believe regimes become more fragile as they age.
Setting means "on average, one regime change per trading year." This is the single most important hyperparameter, and it plays a role analogous to the penalty parameter in PELT.
Going Deeper
Hazard Rate Sensitivity
The hazard rate controls the balance between responsiveness and stability. Here is the same S&P 500 data processed with four different hazard rates:

At (expect a regime change every ~5 months), BOCD finds 15 changepoints and catches most events. At (expect one every ~4 years), it finds only 9 and misses smaller disruptions.
| Hazard Rate | Expected Regime Length | Changepoints Found |
|---|---|---|
| 100 | ~5 months | 15 |
| 250 | ~1 year | 12 |
| 500 | ~2 years | 9 |
| 1000 | ~4 years | 9 |
For financial data, (one trading year) is a sensible default. It captures major crises without flagging every minor correction.
BOCD vs PELT: Head to Head
Both methods process the same 41 years of S&P 500 daily log returns. The comparison reveals their fundamentally different philosophies:

BOCD (top, ) finds 12 changepoints. PELT (bottom, ) finds 45. This is not because BOCD is less sensitive; it reflects different assumptions. PELT sees the entire history and optimises a global segmentation, placing binary boundaries: the regime changed here, or it did not. BOCD processes each observation exactly once and outputs a continuous probability that you can threshold at whatever level suits your use case. If you have seen the hard vs soft clustering distinction between K-Means and GMMs, the same principle applies here: PELT is the hard assignment, BOCD is the soft one.
| Feature | BOCD | PELT |
|---|---|---|
| Processing | Online (one observation at a time) | Offline (needs full history) |
| Output | Posterior probability (continuous, thresholdable) | Hard boundaries |
| Optimality | Locally optimal (sequential Bayes) | Globally optimal (dynamic programming) |
| Complexity | per observation | total |
| Main tuning knob | Hazard rate | Penalty |
| Best for | Streaming, real-time monitoring | Retrospective segmentation, backtesting |
When to choose BOCD: You are processing live data and need regime probabilities as they arrive. You want a continuous signal like that you can threshold to match your risk tolerance, rather than a hard boundary. You cannot afford to reprocess your entire history when a new observation arrives.
When to choose PELT: You have the full dataset and want the globally optimal segmentation. You are comfortable with binary boundaries and need clean, non-overlapping segments for backtesting or risk measurement. You do not need to quantify how confident the algorithm is in each boundary.
Changepoints Aligned with Financial Events

The bottom panel shows the MAP (most likely) run length over time. The sawtooth pattern is characteristic: run length climbs steadily during calm periods, then drops sharply at crises. The height of each "tooth" tells you how long that regime lasted. The 1990s bull market produced the tallest tooth (over 2,500 trading days, roughly 10 years of uninterrupted calm).
Notice the final changepoint: April 4, 2025, two days after the "Liberation Day" tariff announcement. The posterior probability jumped from 0.4% to 7.9% in one day, then hit 99.99% the next. The algorithm had no knowledge of trade policy; it simply observed that the statistical character of returns had changed.
The Iran war (February 28, 2026) is also labelled on the chart. By that point, the market was already in the turbulent regime triggered by tariffs. The posterior probability stayed at its 0.4% baseline throughout, even at the most sensitive hazard rate (). This is a limitation of our univariate setup: we only feed in S&P 500 daily log returns. A multivariate model that also tracked oil futures, gold, defence equities, or emerging market indices (which were hit particularly hard) would almost certainly detect the Iran war as a distinct regime shift. We keep things univariate here for pedagogical clarity, but the framework generalises naturally to higher dimensions (see Beyond Univariate below).
Detection Timing: Thresholds and Trade-offs
BOCD does not produce a binary "detected" signal. It produces a probability, and the practitioner chooses a threshold. The table below shows when first crossed three thresholds (5%, 25%, 50%) for each historical crisis, alongside the MAP flip (the day the most likely run length dropped to zero) and PELT's retrospective detection ().
| Event | Sell-off Start | 5% Threshold | 25% Threshold | 50% Threshold | MAP Flip | PELT |
|---|---|---|---|---|---|---|
| Black Monday (1987) | Oct 14 | Oct 16 (+2d) | Oct 16 (+2d) | Oct 16 (+2d) | Oct 16 (+2d) | Oct 12 (-2d) |
| GFC (2008) | Mar 14 (Bear Stearns) | Mar 18 (+4d) | Mar 19 (+5d) | n/a | Mar 18 (+4d) | Sep 4 |
| US Downgrade (2011) | Aug 4 | Aug 8 (+4d) | Aug 8 (+4d) | Aug 8 (+4d) | Aug 8 (+4d) | Aug 4 (-1d) |
| China Devaluation (2015) | Aug 20 | Aug 24 (+4d) | Aug 26 (+6d) | n/a | Aug 26 (+6d) | Aug 18 (-2d) |
| Volmageddon (2018) | Feb 2 | Feb 5 (+3d) | Feb 5 (+3d) | Feb 5 (+3d) | Feb 5 (+3d) | Jan 26 (-7d) |
| COVID (2020) | Feb 20 | Feb 25 (+5d) | Feb 25 (+5d) | Feb 27 (+7d) | Feb 25 (+5d) | Feb 21 (+1d) |
| Liberation Day (2025) | Apr 2 | Apr 3 (+1d) | Apr 4 (+2d) | Apr 4 (+2d) | Apr 4 (+2d) | Apr 2 (0d) |
| Iran War (2026) | Feb 28 | n/a | n/a | n/a | n/a | n/a |
Several patterns emerge. The 5% threshold never fires later than the MAP flip and fires earlier on two of the seven events, giving an earlier signal at the cost of occasional false positives during smaller corrections. For Liberation Day, the 5% threshold fired on April 3, one day before the MAP run length collapsed. For COVID, the 5% and 25% thresholds triggered on the same day (February 25), with the 50% threshold following two days later.
The GFC and China devaluation never reached the 50% threshold. In both cases, the probability rose enough to cross 5% (and 25% for the GFC), but the evidence accumulated gradually rather than in a single dramatic spike. A practitioner using a 50% threshold would have missed these signals entirely.
PELT's negative lags (detecting "before" the event) are not clairvoyance. Because PELT sees the full dataset, it can retrospectively place the changepoint at the volatility uptick that preceded the headline event. BOCD, processing data as it arrives, can only react after the evidence has accumulated.
The Iran war row is empty across every column. As noted above, this reflects our univariate input (S&P 500 log returns only), not a failure of the algorithm. The S&P 500 was already volatile from tariffs, so the Iran war did not produce a statistically distinct shift in this single series. A multivariate model incorporating oil futures, gold, defence equities, or emerging market indices would tell a different story.
A Word on Using These Signals
The threshold table might suggest that a lower threshold is strictly better: you get earlier signals, so you can act sooner. In practice, the choice depends on how much you fear false positives versus late detection.
A 5% threshold on fires early, but it will also spike briefly during minor corrections that do not develop into full regime shifts. A 50% threshold waits for overwhelming evidence, but as the GFC and China devaluation show, some genuine regime shifts never reach 50% because the evidence accumulates gradually. There is no universally correct threshold; it depends on your cost of acting versus your cost of waiting.
More fundamentally, changepoint detection tells you that something changed. It does not tell you why, how long the new regime will last, or what the appropriate response is. The 2018 Volmageddon spike was over in weeks; the 2008 financial crisis lasted over a year. A system that mechanically de-risked whenever crossed a threshold would have whipsawed through short-lived volatility spikes while potentially missing the recovery. Markets are driven by earnings, policy, geopolitics, liquidity, and sentiment simultaneously, and no single statistical model captures all of these.
The right approach is to combine quantitative tools like PELT and BOCD with fundamental analysis: using the posterior probability to flag when your assumptions may have broken, then applying judgement about whether the shift is structural or transient. These algorithms are best understood as diagnostic instruments, not standalone decision-makers.
Hyperparameter Choices
| Parameter | Value | Why |
|---|---|---|
| Hazard rate | 250 | One trading year; standard for equity markets |
| Prior mean | 0 | No directional bias in returns |
| Prior precision | 1 | Weak prior; let data dominate quickly |
| Prior shape | 0.01 | Weakly informative on variance |
| Prior rate | 0.01 | Weakly informative on variance |
The algorithm is not sensitive to the prior hyperparameters (). After a few dozen observations in any regime, the data overwhelms the prior. The hazard rate is the only parameter that materially affects results.
Beyond Univariate: Multivariate BOCD
This tutorial intentionally feeds BOCD a single feature: the daily S&P 500 log return. This keeps the implementation simple and the conjugate math tractable, but it has a real cost. The Iran war result above is a direct consequence: a conflict that reshaped oil markets, defence spending, and regional equities did not register as a regime shift in S&P 500 returns alone, because the index was already volatile from tariffs.
The framework generalises naturally to higher dimensions. You could construct a 2D input of (daily log return, 21-day rolling volatility) to detect shifts in both the level and stability of returns simultaneously. A 3D or 4D input could combine short-window and long-window volatilities (say 5-day and 63-day), or include oil futures, gold, defence equities, and emerging market indices alongside S&P 500 returns, to capture events like the Iran war that a single domestic index misses.
The required change is in the conjugate model: you replace the Normal-Inverse-Gamma prior with a Normal-Inverse-Wishart prior, which jointly models a mean vector and covariance matrix. The predictive distribution becomes a multivariate Student-t. The message-passing loop in bocd() stays identical; only the sufficient statistics change. This is a natural direction for future work, and we may explore it in a follow-up post.
Where This Comes From
Adams and MacKay (2007): The BOCD Paper
Ryan Prescott Adams and David J.C. MacKay introduced BOCD in their 2007 paper "Bayesian Online Changepoint Detection", bridging the gap between frequentist online filtering methods (CUSUM, EWMA) and Bayesian retrospective segmentation.
The core insight is that the joint distribution over run length and data factorises recursively. At time , the run-length posterior is:
The transition is governed by the hazard function:
The predictive likelihood comes from the underlying predictive model (UPM). For conjugate-exponential models, this has a closed form. With the Normal-Inverse-Gamma prior, it is a Student-t distribution with degrees of freedom.
"The approach is modular so that the underlying predictive model can be chosen or developed independently from the changepoint model." -- Adams & MacKay (2007)
This modularity is a key strength. Our implementation uses a Gaussian model, but you could swap in a Poisson model for count data (as Adams and MacKay demonstrated on the coal mine disaster dataset) or a multinomial model for categorical sequences.
The Message-Passing Interpretation
Each time step, the algorithm passes two types of "messages" forward:
Growth messages: For each run-length hypothesis , extend by 1 and weight by how well fits that hypothesis (and by , the probability of no changepoint).
Reset messages: Sum over all run-length hypotheses the probability that they end now (weighted by ), producing the probability of .
This is exact inference, not an approximation. The run-length posterior at each step is the true Bayesian posterior given all data seen so far.
Extensions Since 2007
The original BOCD framework has been extended in several directions:
- Fearnhead and Liu (2007): Particle filtering for non-conjugate underlying models
- Turner, Saatci, and Rasmussen (2009): Gaussian process underlying models for capturing complex within-regime dynamics
- Knoblauch and Damoulas (2018): Robust BOCD using beta-divergences, replacing the log-likelihood with a divergence measure that downweights outliers
- Wilson, Nassar, and Gold (2010): Applied BOCD to model human changepoint detection in neuroscience experiments, finding that people approximate the optimal Bayesian strategy
Further Reading
- The BOCD paper: Adams & MacKay (2007), "Bayesian Online Changepoint Detection"
- The offline companion: Killick, Fearnhead & Eckley (2012), "Optimal Detection of Changepoints with a Linear Computational Cost" (PELT)
- GP extension: Turner, Saatci & Rasmussen (2009), "Gaussian Process Change Point Models"
- Comprehensive review: Truong, Oudre & Vayatis (2020), "Selective Review of Offline Change Point Detection Methods"
Interactive Tools
- Normal Distribution Calculator: The Gaussian observation model that sits inside each BOCD run-length hypothesis
- Bayes' Theorem Calculator: See the posterior update mechanics underlying each BOCD step
- Drawdown Calculator: Analyse portfolio drawdowns that BOCD can detect in real time
Related Posts
- Changepoint Detection: Finding Regime Shifts in Financial Data: The offline PELT companion to this online method, applied to the same S&P 500 data
- Hidden Markov Models: When Clusters Have Memory: Another online regime detection approach using state-space models with soft transitions
- MCMC for Mixture Models: Inferring Earthquake Regimes: Bayesian regime detection in count data (the coal mine disaster dataset also appears in Adams & MacKay)
- From MLE to Bayesian Inference: The Bayesian updating mechanics that power every step of BOCD
- Gaussian Process Regression from Scratch: GPs provide the underlying model in one of the most powerful BOCD extensions
- Cox Proportional Hazards in Python with lifelines: The hazard function concept in survival analysis is the same one that governs BOCD's changepoint prior
- Five Markets, 22 Years: Every Crisis from Price Data: The multivariate extension of this BOCD method across asset classes
- Anomaly Detection from Scratch: An anomaly in time is a changepoint; both ask when the data stops looking like it did before








