Skip to main content

🏛️ RegimeLab

Institutional-grade market regime detection, systemic risk telemetry, and walk-forward asset allocation engine in Python.

PyPI version Python 3.12+ License: MIT Type Checked with mypy Code style: ruff


⚡ Why RegimeLab?

Most open-source regime detection scripts fit a Hidden Markov Model (HMM) on the entire in-sample dataset and claim predictive power. In production quantitative finance, this fails due to three fatal flaws:

  1. Look-Ahead Bias: Training filters without strict point-in-time (asof) truncation leaks future distribution moments into past states.
  2. Label Switching: HMM/GMM state indices are mathematically interchangeable between refits. Without canonical sorting, "State 0" randomly alternates between Bull and Bear across rolling windows.
  3. Calendar Desynchronization: Multi-asset cross-sections suffer from holiday mismatches, halted assets, and survivorship bias.

RegimeLab solves these operational hurdles, providing a turnkey, causal quantitative engine for systematic asset allocation and macro risk monitoring.


📊 Feature Matrix: Raw Tooling vs. RegimeLab

Challenge Raw hmmlearn / statsmodels RegimeLab Framework
State Labeling Unordered integer states (permutes on refit) Deterministic Canonical Sorting ($\frac{\mu}{\sigma}$ / conditional vol ordering)
Temporal Clock In-sample full-sample fitting (Look-ahead) Strict Point-in-Time (asof) cursor & expanding-window walk-forward
Systemic Risk None Kritzman Absorption Ratio (PCA), VIX Term Spread & Sector Breadth
Execution Reality Pure theoretical classification Walk-Forward Backtester with transaction costs (bps) and confidence floors
Data Ingestion Expects clean 2D NumPy array Multi-Asset PIT Alignment, staleness budgets, synthetic & Parquet providers
Reporting Matplotlib static plot Interactive Plotly HTML reports + Textual TUI Terminal Dashboard

🚀 Quickstart

1. Installation

# Install from PyPI
pip install regimelab

# Or install with interactive TUI support
pip install "regimelab[tui]"

2. Python API Usage

Current Market Regime Detection (3 lines)

from regimelab import Settings
from regimelab.pipeline import run_single_asof

# Run point-in-time regime inference for any historical or current date
settings = Settings(data={"provider": "yfinance"})
payload = run_single_asof(settings, asof="2024-12-31")

print(f"Detected Regime: {payload.regime.value}")
print(f"Confidence: {payload.probabilities.confidence:.2%}")
print(f"Target Allocation: {payload.target_weights.weights if payload.target_weights else {}}")

Extract Causal Systemic Risk Features

from regimelab import Settings
from regimelab.data.fetcher import load_aligned_panel
from regimelab.features import build_feature_matrix

settings = Settings(data={"provider": "yfinance"})
panel = load_aligned_panel(settings)
features = build_feature_matrix(panel, settings)

# Inspect causal feature matrix
print(features[["absorption_ratio", "absorption_delta", "vix_term_spread", "breadth"]].tail())

Walk-Forward Backtesting Engine

from regimelab import Settings
from regimelab.pipeline import run_pipeline

settings = Settings(
    data={"provider": "synthetic"}, # Fully offline, reproducible dataset
    model={"classifier": "hmm", "n_states": 4},
    backtest={"transaction_cost_bps": 5.0, "confidence_floor": 0.5},
)

result = run_pipeline(settings, command="backtest_run")
metrics = result.backtest.metrics

print(f"Strategy CAGR: {metrics.cagr:.2%}")
print(f"Sharpe Ratio:  {metrics.sharpe:.2f}")
print(f"Max Drawdown:  {metrics.max_drawdown:.2%}")

3. CLI & Terminal Dashboard

RegimeLab ships with a powerful Typer CLI:

# 1. Run full walk-forward pipeline and generate interactive HTML report
regimelab run --report market_report.html

# 2. Inspect point-in-time telemetry for a specific date (JSON output)
regimelab asof 2023-10-15

# 3. Launch the full interactive Textual Terminal Dashboard
regimelab tui

Additional CLI commands include regimelab report OUTPUT for direct HTML generation and regimelab asof YYYY-MM-DD --output telemetry.json for persisted JSON payloads.


🧠 Core Methodology & Architecture

flowchart TD
    A["📦 Data Layer (PIT Alignment & Caching)"] --> B["⚡ Causal Features (PCA Absorption, VIX Spread, Breadth)"]
    B --> C["🧠 Models (Hamilton / HMM / GMM + Anti-Switch Ordering)"]
    C --> D["📈 Walk-Forward Engine (Dynamic Allocations)"]
    C --> E["📊 Telemetry, HTML Report & Textual TUI"]

1. Canonical State Labeling (regimelab.models.labeling)

To eliminate label switching, RegimeLab fits the underlying statistical model (Gaussian HMM, Hamilton Markov Switching, or GMM) and evaluates the conditional distribution parameters of each state. States are sorted by risk-adjusted return ($\frac{\mu}{\sigma}$) and mapped deterministically to:

  • BULL_TREND (High return, low volatility)
  • NEUTRAL_TRANSITION (Moderate return, mean-reverting)
  • HIGH_VOL_BEAR (Negative drift, elevated variance)
  • RISK_OFF (Severe drawdown regime)

2. Kritzman Absorption Ratio (regimelab.features.absorption)

Quantifies market fragility via Principal Component Analysis (PCA) over rolling multi-asset return covariance matrices:

$$ \text{Absorption Ratio} = \frac{\sum_{i=1}^{k} \sigma^2_{PC_i}}{\sum_{j=1}^{N} \sigma^2_j} $$

A rapid spike in the absorption ratio ($\Delta \text{AR} > 1.5$) indicates tightening cross-asset coupling, signaling systemic vulnerability prior to market crashes.


⚙️ Configuration (regimelab.toml)

Customize execution parameters via regimelab.toml, environment variables (REGIMELAB_DATA__PROVIDER=yfinance), or Python kwargs:

[data]
provider = "yfinance"          # "yfinance", "synthetic", or "parquet"
start = "2005-01-01"
benchmark = "SPY"
calendar_anchor = "SPY"

[model]
classifier = "hmm"             # "hmm", "gmm", or "hamilton"
n_states = 4
covariance_type = "diag"
min_train_observations = 756

[backtest]
transaction_cost_bps = 5.0
confidence_floor = 0.5
refit_frequency_days = 63

🧪 Testing & Formal Verification

RegimeLab is built with property-based testing (hypothesis) to mathematically guarantee absence of look-ahead leakage:

# Run test suite with causality property tests
uv run pytest -q

# Run strict mypy type checking
uv run mypy src/regimelab

# Lint with ruff
uv run ruff check .

📄 License

MIT License. Developed for quantitative researchers, portfolio managers, and systematic trading engineers.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

regimelab-0.1.1.tar.gz (85.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

regimelab-0.1.1-py3-none-any.whl (107.6 kB view details)

Uploaded Python 3

File details

Details for the file regimelab-0.1.1.tar.gz.

File metadata

  • Download URL: regimelab-0.1.1.tar.gz
  • Upload date:
  • Size: 85.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.12.7 {"installer":{"name":"uv","version":"0.12.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for regimelab-0.1.1.tar.gz
Algorithm Hash digest
SHA256 cd65a2dbb3d9da3d70151eb0c430c50d2bc65783f9e2148142b77e123fc34438
MD5 791f3960adc27124dbdb312f4011e1bf
BLAKE2b-256 5ac20f0a150a0bc08ab648e183078e89d6a4df3115094c728ec1e9cae295329b

See more details on using hashes here.

File details

Details for the file regimelab-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: regimelab-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 107.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.12.7 {"installer":{"name":"uv","version":"0.12.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for regimelab-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 d5fe3e9b1e958566b31ae9a2ad818a426d916dc7e8704c869afaa509afd2199e
MD5 35cbd2d75ffdd2e7116ac18bd18ae659
BLAKE2b-256 ba5b7dfa3f11b7cb749c4b8e96b98e4cb97ab8d325b785ffa6da344b94b240c3

See more details on using hashes here.

Release history Release notifications | RSS feed

0.1.5

2 files

0.1.4

2 files

0.1.3

2 files

0.1.2

2 files

This release

0.1.1 This release

2 files

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page