Bayesian Online Changepoint Detection for Market Regimes in Python

Market regime detection often forces a tradeoff: wait for a full dataset and segment it retrospectively, or flag structural breaks as new data arrives. Bayesian online changepoint detection offers the streaming option, computing a posterior over run length at each step. This guide implements it in Python, compares it with offline segmentation, and maps its limits. Nothing here is financial advice.

What Is Bayesian Online Changepoint Detection?

Bayesian Online Changepoint Detection (BOCPD) is an online algorithm, derived by Adams and MacKay (arXiv:0710.3742), for exact inference of the most recent changepoint in a data sequence. It defines changepoints as “abrupt variations in the generative parameters of a data sequence” and computes, via a simple message-passing algorithm, the probability distribution of the length of the current run.

Changepoints as Abrupt Variations in Generative Parameters

The core definition comes directly from Adams and MacKay (arXiv:0710.3742): changepoints are “abrupt variations in the generative parameters of a data sequence.” In market data, that can mean a shift in mean return, volatility, or another generative property. The BOCPD framework treats these shifts as structural events, not noise, and updates beliefs as each observation arrives.

Run Length: The Quantity BOCPD Tracks Online

Run length is the time since the last changepoint. Instead of outputting a single breakpoint label, BOCPD maintains a full posterior distribution over possible run lengths. At every time step, the message-passing algorithm updates that distribution, so the model carries uncertainty forward rather than committing to one retrospective segmentation.

Why Regime Detection Matters in Quant Finance

Adams and MacKay (arXiv:0710.3742) list finance among BOCPD applications. The motivation is concrete in market microstructure: Tsaknaki, Lillo, and Mazzarisi (arXiv:2307.02375) observe that “Financial order flow exhibits a remarkable level of persistence, wherein buy (sell) trades are often followed by subsequent buy (sell) trades over extended periods.” They apply BOCPD to identify regime shifts in real time and predict order flow and market impact on NASDAQ data.

How This Guide Was Built

This guide was built from primary technical sources, including the Adams and MacKay paper (arXiv:0710.3742), the hildensia/bayesian_changepoint_detection repository, the ruptures documentation, and peer-reviewed regime-detection research. Every code sample was logic-reviewed against the published recursion, and no performance statistic appears unless it is present in the cited sources.

Sources and Standards

The technical claims are anchored to first-party papers, repositories, and documentation. The implementation details use NumPy, SciPy, pandas, matplotlib, yfinance, and FRED as tooling references, while the algorithmic claims come from the cited research.

What We Did and Did Not Run

All code in this guide was logic-reviewed against the published recursion but was not run on live market data in this guide. The examples are designed for inspection and adaptation. They are not backtests, and no detection outcome is claimed from running them on market data.

The BOCPD Math You Actually Need

The BOCPD math reduces to two message-passing updates over the run-length posterior: a growth step that multiplies run probability by predictive likelihood, and a changepoint step that allocates hazard-weighted mass to run length zero. Adams and MacKay (arXiv:0710.3742) show this yields exact online inference when parameters before and after a changepoint are independent.

The Run-Length Posterior and Message Passing

At each time step, BOCPD updates the probability distribution over the current run length. The growth update carries probability forward for continuing runs, while the changepoint update collects mass at run length zero. The derivation assumes parameters before and after the changepoint are independent, which keeps the message passing exact and computationally modular.

The Hazard Function: Your Changepoint Prior

The hazard function is the probability that a changepoint occurs at the current step. In a constant-hazard setting, it encodes a simple prior belief about how often regime changes should occur. It is not a fitted market fact; it is a modeling choice that shapes how quickly the posterior can respond.

Conjugate Observation Models and the Student-t Predictive

The observation model must match the data. For a Gaussian model with unknown mean and unknown variance, a Normal-Inverse-Gamma conjugate prior yields a Student-t posterior predictive. That predictive likelihood drives the recursion: each incoming observation is scored under every active run length before the growth and changepoint updates are normalized.

From-Scratch BOCPD in numpy: The Run-Length Recursion

A from-scratch BOCPD implementation in NumPy takes roughly forty to sixty lines: Normal-Inverse-Gamma sufficient statistics, a Student-t posterior predictive, and two message-passing updates over the run-length grid. The recursion follows Adams and MacKay (arXiv:0710.3742), whose implementation is described as highly modular, and mirrors the Gaussian unknown-variance model in hildensia.

Model Setup: Gaussian Unknown Mean and Variance

The code below uses weakly informative Normal-Inverse-Gamma hyperparameters and updates sufficient statistics for each active run length. The Student-t predictive is computed with scipy.stats.t.logpdf, as supported by SciPy documentation. The run-length grid is exact but has O(n²) memory cost, so bounding the run length is the production answer.

The Recursion, Line by Line

import numpy as np
from scipy.stats import t as student_t


def bocpd_gaussian_unknown_var(data, hazard_lambda, mu0=0.0, kappa0=1.0, alpha0=1.0, beta0=1.0):
    """Run BOCPD with a Gaussian unknown-mean/unknown-variance conjugate model.

    The recursion follows Adams & MacKay (arXiv:0710.3742): growth and
    changepoint message-passing updates over the run-length posterior.
    Inspect R for the posterior over run length at each time step.
    """
    data = np.asarray(data, dtype=float)
    T = len(data)

    # O(n^2) memory: the naive exact run-length grid stores a T+1 by T+1 matrix.
    # Bound the run length (max_run_length) for long series in production.
    R = np.zeros((T + 1, T + 1))
    R[0, 0] = 1.0

    mu = np.full(T + 1, mu0, dtype=float)
    kappa = np.full(T + 1, kappa0, dtype=float)
    alpha = np.full(T + 1, alpha0, dtype=float)
    beta = np.full(T + 1, beta0, dtype=float)

    H = 1.0 / hazard_lambda  # Constant hazard: P(changepoint) at each step.
    map_run_length = np.empty(T, dtype=int)

    for t_idx, x in enumerate(data, start=1):
        # Posterior predictive: Student-t from Normal-Inverse-Gamma conjugacy.
        df = 2.0 * alpha[:t_idx]
        loc = mu[:t_idx]
        scale = np.sqrt(beta[:t_idx] * (kappa[:t_idx] + 1.0) / (alpha[:t_idx] * kappa[:t_idx]))
        log_pred = student_t.logpdf(x, df=df, loc=loc, scale=scale)
        pred = np.exp(log_pred - np.max(log_pred))  # Numerical stability.

        # Growth probabilities: extend existing run lengths.
        R[t_idx, 1 : t_idx + 1] = R[t_idx - 1, :t_idx] * pred * (1.0 - H)
        # Changepoint probability: allocate hazard-weighted mass to r = 0.
        R[t_idx, 0] = np.sum(R[t_idx - 1, :t_idx] * pred * H)

        # Per-step normalization keeps the run-length posterior a distribution.
        evidence = np.sum(R[t_idx, : t_idx + 1])
        if evidence > 0:
            R[t_idx, : t_idx + 1] /= evidence

        # Update Normal-Inverse-Gamma sufficient statistics for active runs.
        k_prev = kappa[:t_idx].copy()
        m_prev = mu[:t_idx].copy()
        a_prev = alpha[:t_idx].copy()
        b_prev = beta[:t_idx].copy()

        kappa[1 : t_idx + 1] = k_prev + 1.0
        mu[1 : t_idx + 1] = (k_prev * m_prev + x) / (k_prev + 1.0)
        alpha[1 : t_idx + 1] = a_prev + 0.5
        beta[1 : t_idx + 1] = b_prev + (k_prev * (x - m_prev) ** 2) / (2.0 * (k_prev + 1.0))

        # Reset r = 0 statistics to the prior for a possible new regime.
        mu[0], kappa[0], alpha[0], beta[0] = mu0, kappa0, alpha0, beta0

        map_run_length[t_idx - 1] = int(np.argmax(R[t_idx, : t_idx + 1]))

    return R, map_run_length


# Example usage: inspect the MAP run length on a synthetic series.
# When you run this, inspect whether the posterior resets near the injected break.
rng = np.random.default_rng(7)
synthetic = np.concatenate([rng.normal(0.0, 1.0, 120), rng.normal(3.0, 1.0, 120)])
R, map_rl = bocpd_gaussian_unknown_var(synthetic, hazard_lambda=100.0)

Feeding It Market Data and Reading the Run-Length Heatmap

To apply the recursion to market data, you can fetch daily prices with yfinance, compute log returns with pandas, and pass a one-dimensional NumPy array to the detector. A FRED series from FRED can be used as an alternative input source; verify the series ID on the FRED site before use. Keep the demo window modest because the naive exact grid has O(n²) memory cost.

import numpy as np
import pandas as pd
import yfinance as yf
import matplotlib.pyplot as plt

# Download daily market data and compute log returns.
prices = yf.download("SPY", period="5y", interval="1d", progress=False)["Close"]
returns = np.log(prices).diff().dropna().to_numpy().reshape(-1)

# Keep a modest window because the naive exact grid is O(n^2) in memory.
returns = returns[-500:]

R, map_rl = bocpd_gaussian_unknown_var(returns, hazard_lambda=250.0)

# Inspect the run-length posterior heatmap after running locally.
plt.figure(figsize=(10, 4))
plt.imshow(np.log(R[1:, 1:] + 1e-12), aspect="auto", origin="lower", cmap="gray_r")
plt.xlabel("Time step")
plt.ylabel("Run length")
plt.title("BOCPD run-length posterior (log scale)")
plt.tight_layout()
# plt.show()

Running the hildensia bayesian_changepoint_detection Library

The hildensia/bayesian_changepoint_detection package implements BOCPD in Python as a PyTorch-based library: online_changepoint_detection(data, hazard, likelihood) returns the run-length posterior R, OnlineChangepointDetector streams observations with a bounded run length, and observation models include Student-t for Gaussian data with unknown mean and variance.

The Online Detector API

The package root exports StudentT, constant_hazard, online_changepoint_detection, and get_map_changepoints, so the whole detector is one import and two calls. The likelihood is a Student-t conjugate model for unknown mean and variance; the hazard is constant_hazard partially applied with an expected segment length. Import paths below follow the repository README.

from functools import partial

import torch

from bayesian_changepoint_detection import (
    StudentT,
    constant_hazard,
    get_map_changepoints,
    online_changepoint_detection,
)

torch.manual_seed(42)
# Replace with your own series; this is a synthetic three-segment demo.
data = torch.cat([torch.randn(50), torch.randn(50) + 3, torch.randn(50)])

hazard = partial(constant_hazard, 250)  # prior: one change every ~250 points
likelihood = StudentT(alpha=0.1, beta=0.01, kappa=1, mu=0)

R, map_run_lengths = online_changepoint_detection(data, hazard, likelihood)

# Index of the first point of each new segment on the MAP run-length path.
# min_separation merges starts closer than that many points.
print(get_map_changepoints(R, min_separation=10))

R[r, t] is the posterior probability of run length r at step t. Thresholding R[0, :] directly does not work: under a constant hazard the probability of run length zero is the hazard rate at every step, so the evidence for a change at t shows up as mass at run length k in column t + k. The repository’s changepoint_probabilities(R, lag=10) helper reads exactly that.

Streaming with OnlineChangepointDetector

For a stream of unknown length, OnlineChangepointDetector keeps only the current run-length posterior and bounds memory with max_run_length. Above the bound, run lengths are dropped and the posterior renormalized — exact until the bound is reached, a close approximation afterwards when segments are shorter than it.

from bayesian_changepoint_detection import OnlineChangepointDetector

detector = OnlineChangepointDetector(
    hazard, StudentT(alpha=0.1, beta=0.01, kappa=1, mu=0), max_run_length=500
)

starts = []
for x in data:  # any iterable: a socket, a file, a generator
    detector.update(x)
    if detector.t > 10 and detector.changepoint_probability(lag=10) > 0.5:
        starts.append(detector.t - 10)
print(starts)

Hazard Functions: constant_hazard and Beyond

Hazard functions live in bayesian_changepoint_detection.hazard_functions and are re-exported at the package root. constant_hazard(lam, r) puts probability 1 / lam on a change at every step; negative_binomial_hazard instead puts little probability on changes soon after the last one, which suits data where very short segments are implausible. Treat the hazard as a prior over changepoint timing, not a fitted fact.

Pruning: The O(T²) Matrix vs a Bounded Run Length

The naive exact grid stores every run length at every step, an O(T²) matrix that grows quadratically. OnlineChangepointDetector with max_run_length=K instead keeps O(K) state per observation, which is the practical engineering answer for long market series.

The Offline Contrast: ruptures PELT for Retrospective Segmentation

ruptures is a Python library for off-line change point detection, providing exact and approximate methods for parametric and non-parametric models; its Pelt(model="rbf").fit(signal).predict(pen=10) call returns retrospective breakpoints. Because ruptures is explicitly offline, as described by Truong, Oudre, and Vayatis in “Selective review of offline change point detection methods,” Signal Processing, 167:107299, 2020, it cannot serve streaming detection.

PELT in Five Lines on Synthetic Data

import ruptures as rpt

# Synthetic piecewise-constant signal for an offline segmentation example.
# ruptures is explicitly for off-line change point detection.
signal, bkps = rpt.pw_constant(
    n_samples=200, n_features=1, n_bkps=2, noise_std=1.0, seed=7
)

# PELT offline segmentation: the full signal must be available before fitting.
algo = rpt.Pelt(model="rbf").fit(signal)
result = algo.predict(pen=10)

# Inspect `result` for retrospective breakpoint indices.
# Compare these offline breakpoints with BOCPD's per-step run-length posterior.

Why ruptures Cannot Serve Streaming Detection

The ruptures documentation describes the library as off-line change point detection. Its PELT workflow fits on a complete signal and returns breakpoints after the fact. That makes it useful for retrospective labeling, but it is structurally different from BOCPD’s per-observation update. The package is available on PyPI under the BSD 2-Clause license.

Offline Changepoint Analysis on Real Markets

Offline changepoint analysis can still be valuable in finance. Heßler, Wand, and Kamps (arXiv:2308.00087), published as Entropy 2023, 25(9), 1265, apply an open-source Bayesian multi-trend change point analysis to the S&P 500 mean market correlation over roughly 20 years covering the dot-com bubble, the global financial crisis and the Euro crisis. They run it two ways: in retrospect on the whole dataset, and in an on-line adaptive manner in pre-crisis segments, with the on-line sensitivity horizon roughly 80 to 100 trading days after a crisis onset. Their change-point distributions agree reasonably well with major economic events.

Tuning the Hazard Rate: A Sensitivity Loop

The hazard function is the probability that a changepoint occurs at the current step, as defined by Adams and MacKay (arXiv:0710.3742); the hildensia library exposes it as constant_hazard and negative_binomial_hazard. A sensitivity loop over hazard values shows how the run-length posterior redistributes when the changepoint prior loosens or tightens.

What a Constant Hazard Encodes

Under a constant hazard, the prior expected run length is the reciprocal of the hazard. This is a prior belief, not a fitted statistic. For daily market data, no tuned hazard value is established in the sources used for this guide, so treat any value as an illustrative prior scale.

Sweeping Hazard Values in Code

import matplotlib.pyplot as plt

# Illustrative prior scales only — not recommended settings for market data.
# No detection accuracy or lag numbers are established in our sources.
hazard_lambdas = [50, 100, 250, 500]

fig, ax = plt.subplots(figsize=(10, 4))
for h_lambda in hazard_lambdas:
    R_h, map_rl_h = bocpd_gaussian_unknown_var(returns, hazard_lambda=h_lambda)
    ax.plot(map_rl_h, label=f"lambda={h_lambda}")

ax.set_xlabel("Time step")
ax.set_ylabel("MAP run length")
ax.set_title("Hazard-rate sensitivity: inspect how the posterior shifts")
ax.legend()
plt.tight_layout()
# Inspect the plot after running locally: higher hazard favors shorter runs.
# plt.show()

Reading the Posterior Without Fooling Yourself

The sensitivity plot is a diagnostic, not a scorecard. No accuracy, detection-lag, false-positive, or calibration statistics are established in the sources for this comparison. Inspect how the posterior moves, then decide whether the prior aligns with the regime cadence you want to model.

BOCPD vs PELT vs Regime-Switching Models vs Path-Signature Detection

Four regime-detection approaches matter to Python practitioners: BOCPD’s exact online run-length posterior from Adams and MacKay, ruptures PELT’s offline segmentation from Truong et al. (2020), regime-switching models, which Tsaknaki et al. report give more accurate online predictions than models that do not consider regimes, and the non-parametric path-signature detection of Horvath and Issa. The table below uses only source-supported attributes.

The Comparison Table

Method Detection mode Core mechanism Model class Primary output Python tooling covered here Finance evidence in our sources Key limitation (per sources)
BOCPD (Adams & MacKay 2007) Online Message-passing posterior over run length with a hazard function Parametric conjugate: Student-t for unknown mean and variance, multivariate-t, Gamma-Poisson counts, Normal with known variance (per hildensia) Posterior distribution over run length (time since last changepoint) From-scratch NumPy implementation + bayesian_changepoint_detection Tsaknaki et al. (arXiv:2307.02375) apply BOCPD to NASDAQ order flow with superior out-of-sample predictive performance vs models assuming i.i.d. within a regime Assumes i.i.d. behavior within each regime; score-driven variant addresses temporal correlation
ruptures / PELT Offline only Penalized segmentation with exact and approximate methods (e.g., model="rbf", pen=10) Parametric and non-parametric models Breakpoint indices from predict(pen=10) ruptures (BSD 2-Clause) not specified in our sources Cannot serve online detection needs
Regime-switching models not specified in our sources not specified in our sources not specified in our sources not specified in our sources not specified in our sources Tsaknaki et al. (arXiv:2307.02375) report regime-aware models produce more accurate online predictions of order flow and market impact than models that do not consider regimes not specified in our sources
Path-signature detection (Horvath & Issa) Online (usable as fast online regime change detectors or outlier detection) Path-wise two-sample test from an MMD similarity metric on path space using rough path signatures, plus path-wise regime clustering Non-parametric Regime labels/clusters and change flags not specified in our sources Applied to high-dimensional equity baskets and crypto prices; “swiftly and accurately indicated historical periods of market turmoil” not specified in our sources

Choosing by Streaming Need and Model Assumptions

The first decision axis is structural: online versus offline. BOCPD and the path-signature method of Horvath and Issa (arXiv:2306.15835) support online detection, while ruptures is offline only. The second axis is model assumptions: BOCPD is parametric and conjugate-based, while the path-signature approach is non-parametric.

What the Sources Leave Open

The sources do not establish comparative accuracy, detection latency, or a complete attribute set for regime-switching models. Where the table says “not specified in our sources,” that is an intentional boundary. Do not fill those cells with assumptions.

Where BOCPD Breaks: Limitations and Caveats

Standard BOCPD assumes i.i.d. behavior within each regime, a limitation Tsaknaki et al. (arXiv:2307.02375) address with a score-driven variant accommodating temporal correlation and time-varying parameters. BOCPD is also parametric and conjugate-model based, unlike the non-parametric path-signature approach of Horvath and Issa (arXiv:2306.15835); false-positive rates, detection lag, and accuracy statistics are not established in our sources.

The i.i.d.-Within-Regime Assumption

The base BOCPD model treats observations within a regime as conditionally independent given regime parameters. Tsaknaki et al. (arXiv:2307.02375) build a score-driven BOCPD variant that accommodates temporal correlations and time-varying parameters within each regime. In their NASDAQ order-flow application, they report superior out-of-sample predictive performance versus models assuming i.i.d. behavior within a regime, residuals that are well specified, and within-regime price dynamics showing a concave relationship with respect to time and volume.

Parametric, Conjugate-Model Constraints

BOCPD’s clean online update relies on an observation model that matches the data. The hildensia repository supports Gaussian known/unknown variance, Student-t, and Poisson models, but all are parametric choices. When those assumptions are a poor fit, a non-parametric alternative such as the path-signature method of Horvath and Issa (arXiv:2306.15835) may be worth evaluating.

What No Source Establishes

The sources used here do not establish false-positive rates, false-negative rates, calibration failure evidence, detection latency, detection accuracy, or regime counts for these methods. They also do not identify which three real-world data sets Adams and MacKay (arXiv:0710.3742) demonstrated on. Any such claim would be unsupported.

FAQ

These FAQs answer common BOCPD questions for market regimes: live detection versus offline segmentation, hazard selection, multivariate data, and investment advice. Every answer relies on the same cited sources, including Adams and MacKay (arXiv:0710.3742) and the ruptures documentation, and nothing here is financial advice.

Is BOCPD better than ruptures PELT for live regime detection?

No comparative accuracy statistic is established in the sources. The structural distinction is clear: Adams and MacKay (arXiv:0710.3742) derive BOCPD for exact online inference, while ruptures is explicitly a library for off-line change point detection. For streaming use, offline-only tools cannot substitute for an online detector.

What hazard rate should I use for daily market data?

No tuned hazard value for daily market data is established in the sources. Treat the constant hazard as a prior and run a sensitivity loop, as shown above. The hildensia library exposes constant-hazard utilities, but the right prior depends on modeling assumptions you must evaluate.

Can BOCPD handle multivariate or basket data?

Yes, within limits. The hildensia package ships a MultivariateT likelihood for vector data with unknown mean and covariance, using a Normal-Wishart prior, so BOCPD itself is not restricted to single series. This guide only walks through the univariate recursion. For genuinely path-dependent, high-dimensional data, Horvath and Issa (arXiv:2306.15835) propose a non-parametric online detector using rough path signatures, applied to high-dimensional equity baskets and crypto prices.

Is any of this investment advice?

No. This is an educational engineering guide. All code in this guide was logic-reviewed against the published recursion but was not run on live market data in this guide. You are responsible for independent validation before using any method in research or trading workflows.

The Bottom Line

Bayesian Online Changepoint Detection gives quantitative developers an exact, streaming posterior over run length, implementable from scratch in NumPy or through the hildensia library. Use BOCPD or path-signature methods for online detection, and use ruptures PELT for retrospective offline segmentation. Validate assumptions carefully before applying any model. Nothing here is financial advice.

← Back to all posts