BLOG

Behind the numbers.

Code examples, market analysis, and data quality deep-dives.

Is AI Capex Paying Back Fast Enough? Revenue Hurdle Forecasting in Python
Could Shorter AI Asset Lives Hit Earnings? Depreciation Stress Test in Python
How Much AI Capex Risk Can a Portfolio Remove? Constrained Optimization in Python
Is the AI Capex Trade Crowded? Rolling Volatility and Sector Rotation in Python
Did the AI Boom Come From Existing S&P 500 Members? Point-in-Time Momentum Test in Python
Is AI Revenue Circular? Customer-Vendor Capex Loop Analysis in Python
Is the AI Trade Connected to Private Credit? Rolling Correlation Network in Python
Is Apollo More Balance-Sheet Sensitive Than Peers? Leverage Screen in Python
Are AI Earnings Supported by Cash Flow? Accrual and Capex Screen in Python
Can Defensive Stocks Hedge AI Drawdowns? Basket Regime Test in Python
How Fast Does the Market Price In Fed Decisions? FOMC Event Study in Python
How Much Are Options Sellers Overpaid? The Variance Risk Premium in Python
Which Companies Have the Worst Earnings Quality? Sloan Accrual Screen with Geographic Revenue Data in Python
Does the Oil-to-Gold Ratio Signal Recessions? XLE/GLD Backtest in Python
Is AI Spending Crowding Out Free Cash Flow? Capex Sustainability Across the Mag 7 in Python
Does a Long Energy / Short Bonds Portfolio Capture Inflation Surprises? Factor Construction in Python
Can a Hidden Markov Model Detect Oil Market Regimes? HMM Analysis in Python
Do Grain Prices Predict Food Inflation? Granger Causality Test in Python
Does the Corporate Credit Spread Predict Stock Market Crashes? BAA-AAA Spread Analysis in Python
Do Oil Stocks Hedge Inflation? Rolling Beta Analysis in Python
Which Stocks Are Most Rate-Sensitive? Equity Duration via Bond Beta in Python
Which Companies Have the Highest Accrual Ratios? Earnings Quality Screening in Python
Is Alpha Persistent or Decaying? Rolling Sharpe Ratio Analysis in Python
Are Markets Trending or Mean-Reverting? Hurst Exponent Analysis in Python
Is Consumer Discretionary vs Staples a Leading Indicator? XLY/XLP Ratio Analysis in Python
Does Heavy Capex Predict Future Stock Returns? Capital Expenditure Analysis in Python
How to Estimate Cost of Equity Using CAPM in Python
Is Volatility Predictable? Testing for Volatility Clustering in Python
Which Industrials Are Overleveraged? Net Debt to EBITDA Screening in Python
GM Before and After Bankruptcy: Why Entity Resolution Matters for Financial Data
What Is Adjusted Beta? Merrill Lynch Beta Shrinkage in Python
How Good Is a Stock Pick? Information Ratio and Tracking Error in Python
Do Stock Returns Follow a Normal Distribution? Testing for Fat Tails in Python
Which Large Caps Have the Highest Free Cash Flow Yield? FCF Screening in Python
Which Sectors Won Over 5 Years? Sector Rotation Analysis in Python
How to Forecast Stock Volatility with GARCH Models in Python
Are Stock Prices Mean-Reverting? Augmented Dickey-Fuller Test in Python
How to Calculate CAPM Alpha and Beta with Regression in Python
How to Compare Sector Sharpe Ratios and Sortino Ratios in Python
DELL: Why Stitching Historical Price Data Together Is Wrong
How to Analyze Drawdown and Recovery for Bank Stocks in Python
How to Screen SaaS Stocks by Revenue Growth and Cash Flow in Python
How to Screen REITs by Dividend Yield and Valuation in Python
How Correlated Are the Magnificent 7? Intra-Group Correlation in Python
AAPL vs XOM: Do Individual Stocks Have Seasonal Patterns?
How to Rank Large-Cap Stocks by Momentum in Python
How to Build a Multi-Endpoint Financial Dashboard in Python
How to Compare Volatility Across Energy Stocks in Python
How to Screen Healthcare Stocks by Valuation in Python
How to Build a Sector Correlation Matrix for Portfolio Diversification in Python
How to Find Oversold and Overbought Stocks Using Z-Scores in Python
How to Measure Earnings Quality: Cash Flow vs Net Income in Python
How to Build a Multi-Factor Stock Screen in Python (Value + Momentum + Quality)
How to Build a Simple DCF Model for Any Stock in Python
How to Screen Tech Stocks by Revenue Growth in Python
How to Screen Stocks by Balance Sheet Health in Python
Is "Sell in May" Real? SPY Monthly Seasonality Over 10 Years
How to Compare Sector Performance YTD Using Python
How to Track S&P 500 Additions and Removals Over Time in Python
How to Screen Dividend Stocks by Yield and Quality in Python
How to Calculate Max Drawdown and Recovery Time for Any Stock in Python
How to Compare Profitability Across Mega-Cap Tech Stocks in Python
Why Ticker Symbols Are Unreliable: The Recycling Problem Every Quant Should Know
How to Calculate and Compare Stock Volatility in Python
How to Screen Blue-Chip Stocks by P/E Ratio in Python
How to Track Companies Through Ticker Changes, Bankruptcies, and Renames in Python
S&P 500 Turnover: How Much the Index Has Changed Since 2010
How to Calculate Stock Beta and Correlation in Python
← All articles

Can a Hidden Markov Model Detect Oil Market Regimes? HMM Analysis in Python

What’s the question?

Oil markets alternate between periods of relative stability and sudden violent moves. A Hidden Markov Model (HMM) assumes the market switches between unobservable “hidden” states, each with its own return distribution. The model estimates how many states exist, what each state’s return characteristics are, and the probability of transitioning between them. If the model can reliably detect regime changes, it provides a framework for time-varying risk management — tightening positions when the model signals crisis and loosening them in calm periods.

The approach

Fit a 2-state Gaussian HMM to 5 years of XLE daily returns using the Baum-Welch (EM) algorithm. Extract regime means, volatilities, transition matrix, and map regime states to the price chart.

import xfinlink as xfl
import pandas as pd
import numpy as np
from hmmlearn.hmm import GaussianHMM

xfl.api_key = "YOUR_API_KEY"  # free at https://xfinlink.com/signup

# XLE daily returns
df = xfl.prices("XLE", period="5y", fields=["close", "return_daily"])
df = df.sort_values("date").dropna(subset=["return_daily"])
returns = df["return_daily"].values.reshape(-1, 1)

# Fit 2-state Gaussian HMM
model = GaussianHMM(n_components=2, covariance_type="full", n_iter=200, random_state=42)
model.fit(returns)
states = model.predict(returns)

# Identify calm vs crisis by volatility
vols = [np.sqrt(model.covars_[i][0, 0]) for i in range(2)]
calm_idx = np.argmin(vols)
crisis_idx = np.argmax(vols)

for label, idx in [("CALM", calm_idx), ("CRISIS", crisis_idx)]:
    mu = model.means_[idx][0] * 100
    vol = vols[idx] * 100
    ann_vol = vol * np.sqrt(252)
    print(f"State ({label}): mean={mu:+.3f}%/day  vol={vol:.3f}%/day  ann_vol={ann_vol:.1f}%")

print(f"Transition: CALM->CALM={model.transmat_[calm_idx, calm_idx]:.3f}  "
      f"CRISIS->CALM={model.transmat_[crisis_idx, calm_idx]:.3f}")

Full script with formatting and visualisation: oil-hmm-regime-detection-python.py

Output:

XLE price chart with HMM crisis regime days highlighted in red
State 0 (CALM):  mean=+0.108%/day  vol=1.596%/day  ann_vol=25.3%
State 1 (CRISIS): mean=-10.190%/day  vol=17.620%/day  ann_vol=279.7%

Transition: CALM→CALM=0.995  CALM→CRISIS=0.005  CRISIS→CALM=1.000
Time in regime: CALM=100%  CRISIS=0%
Current regime: CALM

Recent switches: 2025-04-04→CRISIS, 2025-04-07→CALM, 2025-04-09→CRISIS, 2025-04-10→CALM

What this tells us

The HMM identifies two sharply distinct states. The calm regime has 25.3% annualized volatility — typical for an energy ETF. The crisis regime has 279.7% annualized volatility — an order of magnitude higher. Crucially, the crisis state has zero persistence (transition probability of 1.000 back to calm), meaning it identifies single-day extreme events rather than sustained multi-day crises. The April 2025 tariff shock produced the most recent cluster of crisis-day detections. At the daily frequency, oil “regimes” are better described as isolated volatility spikes within a persistent calm state, not as sustained bear markets.

So what?

The HMM result has a direct implication for risk models: oil energy volatility is not well-described by two sustained regimes at the daily frequency. The “crisis” state is a single-day spike phenomenon — the market does not stay in crisis, it enters and exits within 1-2 days. For practical regime detection in oil, weekly or monthly return data would produce more persistent regime states. At the daily level, a GARCH model may be more appropriate than an HMM because GARCH directly models volatility persistence rather than discrete regime switches.

Built with xfinlink — free financial data API for Python. pip install xfinlink
← All articles