Back to Projects

Statistical Arbitrage — Pair Trading with Ornstein-Uhlenbeck Modelling

July 2025
Python Statistical Testing Cointegration Ornstein-Uhlenbeck Pair Trading Backtesting Monte Carlo
View on GitHub

Project Overview

This project implements a complete statistical arbitrage pipeline based on pair trading. The core hypothesis is that certain pairs of equities share a long-run equilibrium relationship (cointegration), and that temporary deviations from this equilibrium — captured by the spread — can be modelled as a mean-reverting stochastic process (Ornstein-Uhlenbeck). Trading signals are generated when the spread deviates significantly from its long-term mean, and positions are closed when it reverts.

The pipeline covers: economic pre-filtering of candidate pairs, battery of statistical tests for cointegration validation, spread construction via the Johansen procedure, OU parameter estimation by OLS regression, signal generation through a state-machine architecture, and out-of-sample backtesting with capital simulation.

Data Acquisition and Universe Definition

Candidate Pair Selection

The universe of candidate pairs is defined in pairs_universe.csv, a manually curated list of 30+ equity pairs selected on economic grounds. Each pair is justified by a fundamental relationship: direct competitors (KO/PEP, HD/LOW), same macro driver (CAT/DE, XOM/CVX), payment networks (V/MA), or sector exposure (LMT/RTX, UNH/ELV). This economic pre-filter ensures that any statistical relationship detected has a plausible structural explanation, reducing the risk of spurious cointegration.

Historical Data

Price data is downloaded from Yahoo Finance via the yfinance library. The training period spans January 2010 to January 2024 (approximately 14 years of daily close prices). Data is cached locally in financial_datas.csv to avoid repeated downloads. A separate out-of-sample dataset covering January 2024 to July 2026 is stored in backtest_datas.csv for backtesting purposes. Missing values between tickers are handled by aligning on the intersection of available dates (dropna on the concatenated DataFrame).

Statistical Testing Pipeline

The cointegration verification is implemented in test_coint.py as a class Coint_verif that runs a battery of five sequential tests. Each test acts as a filter: if a pair fails any test, it is immediately rejected via a custom CointError exception. The method test_batterie() chains all tests in order.

Step 1: Integration Order Verification (ADF)

The first requirement for cointegration is that both price series are individually integrated of order 1, denoted I(1). This means the raw series is non-stationary, but its first difference is stationary. The implementation uses the Augmented Dickey-Fuller test from statsmodels:

  • Test that the raw series fails to reject H₀ (unit root present) at the 5% level — confirming non-stationarity.
  • Test that the first-differenced series rejects H₀ at the 5% level — confirming stationarity of returns.

Both conditions must hold for both assets in the pair. If either series is already stationary in levels, or if the first difference is not stationary, the pair is discarded.

Step 2: Spread Construction via Johansen

The hedge ratio and spread are estimated using the Johansen cointegration procedure (coint_johansen from statsmodels). This method solves a generalized eigenvalue problem on the VECM representation of the bivariate system. The implementation extracts the eigenvector associated with the largest eigenvalue, normalizes it so that the coefficient on the first asset equals 1, and constructs the spread as:

spread(t) = price_A(t) + v[1] × price_B(t)

where v[1] is the normalized second component (typically negative, yielding spread = A − β·B). The Johansen approach is preferred over OLS because it is symmetric — the result does not depend on which variable is designated as dependent — and because it simultaneously provides a test of cointegration rank.

Step 3: Spread Stationarity Verification

Once the spread is constructed, its stationarity is verified through three independent tests, each with different null hypotheses and power characteristics:

TestH₀Rejection conditionRationale
ADFUnit root (non-stationary)stat < critical valueStandard unit root test
KPSSStationarystat > critical valueComplementary: tests opposite hypothesis
Phillips-PerronUnit root (non-stationary)stat < critical valueRobust to heteroscedasticity and serial correlation

Using both ADF/PP (H₀: non-stationary) and KPSS (H₀: stationary) provides a confirmatory approach: the spread must simultaneously reject non-stationarity under ADF/PP and fail to reject stationarity under KPSS. This reduces the probability of Type I errors from any single test.

Step 4: Formal Cointegration Tests

Two formal cointegration tests validate the relationship:

  • Engle-Granger: tests whether the residuals of the cointegrating regression have a unit root. The pair is rejected if the test statistic exceeds the critical value at 5%, or if the p-value exceeds 0.05.
  • Johansen trace test: the trace statistic for rank r=0 must exceed the 95% critical value, rejecting the null of no cointegration relationship.

Step 5: Hurst Exponent

As a final confirmation of mean-reversion, the Hurst exponent is computed on the spread using the R/S (rescaled range) method via the hurst library. A Hurst exponent H < 0.5 indicates mean-reverting behaviour. H = 0.5 corresponds to a random walk, and H > 0.5 indicates trending behaviour. Pairs with H ≥ 0.5 are rejected.

Results of the Screening

From the initial universe of 30+ candidate pairs, the statistical pipeline identifies 8 cointegrated pairs:

PairSector
UNH – ELVHealth Insurance
TMO – DHRLife Sciences
ALL – TRVInsurance
DE – AGCOAgricultural Equipment
SNPS – CDNSEDA Software
ADP – PAYXPayroll Services
EMR – ROKIndustrial Automation
VRSK – MCOData Analytics / Risk

Ornstein-Uhlenbeck Parameter Estimation

Model Definition

The spread is modelled as a continuous-time Ornstein-Uhlenbeck process:

dX(t) = θ(μ − X(t))dt + σ dW(t)

where θ is the mean-reversion speed, μ is the long-run mean, and σ is the diffusion coefficient. The exact discretization for observations at uniform intervals Δt yields an AR(1) process:

X(t+1) = a·X(t) + b + ε(t),  a = e^(−θΔt),  b = μ(1−a)

Estimation Method (OLS)

The OUEstimator class in fit_ou_model.py implements estimation by OLS regression on the discretized form. The procedure:

  • Regress X(t+1) on [1, X(t)] to obtain the intercept b̂ and slope â.
  • Verify that 0 < â < 1 (necessary condition for mean-reversion). If violated, the model raises a ValueError.
  • Convert back to continuous-time parameters: θ = −ln(â)/Δt, μ = b̂/(1−â).
  • Estimate σ from the residual variance: σ² = σ²(ε)·(−2ln(â)) / (Δt·(1−â²)).

Derived Quantities

The estimator computes several quantities used downstream:

  • Half-life: t½ = ln(2)/θ — the expected time for the spread to revert halfway to μ. This determines the holding horizon and influences the choice of trading parameters.
  • Stationary variance: σ²/(2θ) — the long-run variance of the spread under the OU model.
  • Stationary standard deviation: used to normalize the z-score for signal generation.

Diagnostic Tests

The estimator provides model diagnostics on the standardized residuals:

  • Jarque-Bera: tests for normality of residuals (OU assumes Gaussian noise).
  • Ljung-Box: tests for remaining autocorrelation (AR(1) residuals should be white noise).
  • ARCH-LM: tests for conditional heteroscedasticity (OU assumes constant volatility).

Confidence intervals for θ and μ are computed via asymptotic standard errors and delta-method propagation from the AR(1) coefficients.

Pair Filtering by Half-Life and Volatility

After OU estimation on all 8 cointegrated pairs, a second filter is applied based on tradability criteria. Pairs are retained if they exhibit a half-life short enough for practical trading and sufficient spread volatility to generate profit after transaction costs. The final selection retains 4 pairs:

PairHalf-life (days)θσ
UNH – ELV550.01262.70
TMO – DHR690.01013.11
DE – AGCO490.01433.61
SNPS – CDNS250.02741.72

Pairs with half-lives exceeding 80 days (ALL–TRV, ADP–PAYX, EMR–ROK, VRSK–MCO) or insufficient volatility are discarded, as they would require excessively long holding periods relative to the risk of regime change.

Signal Generation

Z-Score Based State Machine

The trading logic is implemented in Pair_trading_strat.py as a class Strategie. Signal generation is modelled as a finite state machine with three states: flat (0), long spread (+1), and short spread (−1). The z-score is computed as:

z(t) = (spread(t) − μ) / σ_stationary

where μ and σ_stationary are the OU parameters estimated on the training period.

Entry and Exit Rules

ConditionActionDefault threshold
z > k_entry (from flat)Short the spreadk_entry = 2.0
z < −k_entry (from flat)Long the spreadk_entry = 2.0
z crosses −k_exit (from long)Close long positionk_exit = 0.2
z crosses k_exit (from short)Close short positionk_exit = 0.2
|z| > stop_loss (from any position)Close position (stop-loss)stop_loss = 3.0
Holding days > max_holdingClose position (time stop)Optional (None)

The state machine ensures that transitions are well-defined: entry only occurs from the flat state, and exit conditions are checked only when a position is active. The stop-loss protects against structural breaks in the cointegration relationship (the spread may diverge permanently if the regime changes).

Backtesting

Methodology

The backtest uses an out-of-sample period (January 2024 – July 2026) that is strictly posterior to the training data (2010–2024). The hedge ratio and OU parameters are estimated on the training period and held fixed throughout the backtest — no re-estimation or look-ahead occurs.

Two backtesting modes are implemented:

Mode 1: Spread-Level PnL

The backtest() method computes the PnL directly from the spread movements. At each time step, the position (long, short, or flat) multiplies the daily change in spread value. Transaction costs (default: 30 bps) are applied proportionally to the absolute spread value at each trade. The method returns:

  • Cumulative PnL: running sum of daily net returns.
  • Sharpe ratio: annualized (×√252), computed only on active days.
  • Maximum drawdown: largest peak-to-trough decline in cumulative PnL.
  • Number of trades: round-trip count.
  • Win rate: proportion of positive daily returns on active days.

Mode 2: Capital Simulation

The simulate_capital() method implements a more realistic simulation with explicit capital allocation. Given an initial capital (default: $10,000) and a risk fraction per trade (parameter f), the method tracks:

  • The number of shares of asset A and B held at each time step.
  • Available liquidity after position entries and exits.
  • Total portfolio value (patrimoine) accounting for mark-to-market positions.

When going long the spread (buy A, short B), the system allocates f×liquidity to asset A and hedge×f×liquidity to the short position in B. The reverse allocation applies for short spread positions. Position closing rebalances back to fully liquid.

Cumulative PnL for UNH-ELV pair
Figure 1. Cumulative PnL (spread-level) for the UNH–ELV pair over the out-of-sample period (Jan 2024 – Jul 2026). The strategy uses default parameters (k_entry=2, k_exit=0.2, stop_loss=3) with OU parameters estimated on 2010–2024 data. The upward trend indicates that mean-reversion signals on this pair generated positive returns in the backtest period.
Capital simulation for UNH-ELV pair with $10,000 initial
Figure 2. Capital evolution for the UNH–ELV pair with $10,000 initial capital and 50% risk per trade. The simulation tracks explicit share quantities and mark-to-market portfolio value. The staircase pattern reflects periods of active positions (where capital fluctuates with prices) separated by flat periods (cash-only, waiting for entry signals).
Cumulative PnL for a pair showing negative performance
Figure 3. Cumulative PnL for another pair over the same out-of-sample period. Unlike UNH–ELV, this pair generates a negative cumulative PnL, suggesting that the cointegration relationship estimated on historical data broke down during the backtest period. This illustrates the regime-change risk inherent to pair trading strategies.

Architecture and Code Organization

FileRole
pairs_universe.csvEconomic pre-filter: curated list of candidate pairs with fundamental justification
test_coint.pyStatistical testing module: Coint_verif class implementing the 5-test battery
fit_ou_model.pyOU estimation module: OUEstimator class with OLS fit, diagnostics, and confidence intervals
Pair_trading_strat.pyStrategy module: Strategie class with signal generation, backtest, and capital simulation; returns BacktestResult objects containing equity curve, returns, and trade log
metrics.pyBacktest evaluation: drawdowns, CAGR, Calmar, Sharpe/Sortino, trade statistics (win rate, payoff ratio, profit factor, expectancy), significance testing, streak analysis, Deflated Sharpe Ratio
costs.pyCost modelling: commission structures, fixed/random/square-root impact slippage (Almgren-Chriss), borrow and funding costs, breakeven cost analysis
robustness.pyRobustness testing: Monte Carlo simulations (shuffle/bootstrap/block), walk-forward optimization, stress tests (gap injection, volatility scaling), parameter sensitivity, regime analysis
report.pyReport generation: aggregates all metrics into structured output with console display and multi-panel equity figures
test_pair.ipynbOrchestration notebook: runs the full pipeline from data loading to backtest visualization
financial_datas.csvCached training data (2010–2024)
backtest_datas.csvCached out-of-sample data (2024–2026)
validation_stat.ipynbEducational notebook: step-by-step implementation of each statistical test with synthetic data
prise_en_main_ou.ipynbOU process exploration: simulation, convergence to stationary distribution, empirical vs theoretical ACF

The modular architecture separates concerns cleanly: statistical testing, OU estimation, and strategy logic are independent classes that can be composed. The evaluation layer (metrics, costs, robustness, report) operates on three standardized objects produced by the backtest engine — an equity curve (pd.Series), a returns series, and a trade log (pd.DataFrame) — making it reusable across strategies.

Backtest Evaluation

Evaluation Framework

To rigorously assess the strategy beyond raw PnL, a comprehensive evaluation framework was built covering: drawdown analysis, risk-adjusted performance (Sharpe, Sortino, Calmar), trade-level statistics (win rate, payoff ratio, profit factor, expectancy), statistical significance testing (t-test, bootstrap confidence intervals), Monte Carlo simulation (block bootstrap, 2000+ paths), and outlier sensitivity analysis. Each metric is computed on the capital simulation output (real dollar PnL), not on spread-level returns.

The backtest runs on the out-of-sample period (January 2024 – July 2026, ~2.5 years) with $10,000 initial capital and 50% risk per trade. Strategy parameters (k_entry=2, k_exit=0.2, stop_loss=3, transaction costs=30 bps) are fixed — no optimization was performed.

Comparative Results

MetricUNH–ELVTMO–DHRDE–AGCOSNPS–CDNS
Final Capital$14,054$9,678$6,858$10,740
Total Return+40.5%−3.2%−31.4%+7.4%
CAGR+14.6%−1.3%−14.1%+2.9%
Max Drawdown−13.1%−18.7%−47.6%−22.0%
Sharpe Ratio1.17−0.02−0.140.25
Sortino Ratio2.44−0.02−0.200.36
Calmar Ratio1.12−0.07−0.300.13
Win Rate46.5%29.6%46.7%48.5%
Payoff Ratio2.081.671.031.11
Profit Factor1.810.700.911.05
Number of Trades14427244229
t-stat (significance)1.61−0.66−0.550.23
MC Prob. of Ruin (50%)0%0.56%46.1%4.6%
Equity curves for all four pairs
Figure 4. Equity curves for the four backtested pairs ($10,000 initial, f=50%). Only UNH–ELV shows a sustained upward trajectory. DE–AGCO loses nearly a third of its capital. TMO–DHR and SNPS–CDNS remain close to the starting capital.
Drawdown time series for all four pairs
Figure 5. Drawdown series for each pair. UNH–ELV stays within −13%, while DE–AGCO reaches −47.6% — close to complete capital destruction. The TMO–DHR drawdown lasts 517 days, meaning the pair never fully recovered during the test window.

Deep Dive: UNH–ELV (Best Pair)

UNH–ELV is the only pair that passes the majority of the evaluation criteria: Sharpe above 1, drawdown under 15%, and a positive profit factor (1.81). However, a closer examination reveals significant fragilities.

UNH-ELV three-panel report: equity, drawdown, and per-trade equity
Figure 6. UNH–ELV three-panel report. Top: mark-to-market equity with the characteristic staircase pattern of active/flat periods. Middle: drawdown percentage over time. Bottom: equity indexed by trade number, showing a long flat period (trades 20–100) before the performance materializes.
UNH-ELV trade PnL distribution and cumulative PnL
Figure 7. Trade-level analysis. Left: PnL distribution showing 77 losing trades vs. 67 winning trades, with a positive expectancy of $28.2 per trade. The distribution is right-skewed — a few large winners drive the overall result. Right: individual trade PnL (bars) overlaid with cumulative PnL (line), showing that almost all gains come from the last third of the backtest period.
Monte Carlo simulation for UNH-ELV
Figure 8. Monte Carlo block bootstrap (2,000 simulations). Left: 100 simulated equity paths (blue) vs. the historical path (red). The historical outcome is within the upper range but not exceptional. Right: distribution of maximum drawdown across simulations — the historical DD (−13.1%) sits near the median, while the 5th percentile worst case reaches −20.8%. This yields a capital requirement of ~$4,650 at the 2× safety margin.
UNH-ELV rolling Sharpe ratio
Figure 9. Rolling Sharpe ratio (63-day window) for UNH–ELV. The strategy alternates between periods of strongly positive Sharpe (mid-2024, mid-2025) and deeply negative Sharpe (late 2024, early 2026), highlighting the instability of the edge over time. The strategy is far from consistently profitable on a quarter-by-quarter basis.
Outlier sensitivity analysis for all four pairs
Figure 10. Outlier sensitivity: total PnL after removing the k best trades. UNH–ELV turns negative after removing just 3–5 best trades, revealing that the entire profit depends on a handful of large winners. The other three pairs start negative and deteriorate further. This is a critical fragility — missing even a few entry signals can erase the strategy's edge entirely.

Statistical Significance

None of the four pairs achieves statistical significance at the 95% level (t-stat > 2). UNH–ELV comes closest with a t-stat of 1.61 (p = 0.054), but would require approximately 222 trades to reach significance at the current effect size — 78 more than the 144 observed. The 2.5-year out-of-sample window is too short for swing trading strategies, which typically require 5–10 years of data to produce reliable conclusions.

CriterionThresholdUNH–ELVTMO–DHRDE–AGCOSNPS–CDNS
Max Drawdown< 15%✓ 13.1%✗ 18.7%✗ 47.6%✗ 22.0%
Sharpe Ratio> 0.75✓ 1.17✗ −0.02✗ −0.14✗ 0.25
Profit Factor> 1.2✓ 1.81✗ 0.70✗ 0.91✗ 1.05
t-stat> 2.0~ 1.61✗ −0.66✗ −0.55✗ 0.23
Trade Count≥ 200✗ 144✗ 27✓ 244✓ 229
Backtest Length≥ 5 years✗ 2.5y✗ 2.5y✗ 2.5y✗ 2.5y
MC Prob. of Ruin≈ 0%✓ 0%~ 0.56%✗ 46.1%✗ 4.6%

Conclusion

The evaluation framework reveals a significant gap between in-sample cointegration and live tradability. Out of four cointegrated pairs, only UNH–ELV produces a Sharpe ratio above 1, and even this result does not reach statistical significance on the available data. The profit is concentrated in a single year (2025 accounts for 88% of total return) and depends on a handful of outlier trades (removing the top 5 trades turns the strategy negative). DE–AGCO is outright dangerous with a 46% probability of ruin. TMO–DHR generates too few trades (27) for any meaningful evaluation. SNPS–CDNS is marginally positive but without a demonstrable edge.

The honest takeaway is that a statistically valid OU mean-reversion signal on historical data does not guarantee tradable alpha out of sample. The evaluation tools built for this project — significance testing, Monte Carlo simulation, outlier sensitivity, rolling Sharpe analysis — are precisely what allowed these conclusions to surface rather than being masked by a single equity curve.

Limitations

  • Insufficient backtest length: 2.5 years of out-of-sample data is too short for swing trading strategies. None of the pairs reaches statistical significance, which means the observed results — positive or negative — could plausibly be due to chance.
  • Performance concentration: for UNH–ELV, 88% of the return comes from a single year (2025) and 140% of the PnL comes from the top 5% of trades. This "lottery ticket" profile means a few missed entries or an unfavourable year can erase all gains.
  • Static parameters: the hedge ratio, μ, and σ are estimated once on the training set and never updated. In practice, cointegration relationships evolve, and parameters should be re-estimated on a rolling window.
  • No parameter optimization: k_entry, k_exit, and stop_loss are set to fixed defaults. No walk-forward optimization was performed to adapt them per pair (though the framework for it is implemented in robustness.py).
  • Constant volatility assumption: the OU model assumes σ is constant. Financial spreads exhibit time-varying volatility, which the ARCH-LM diagnostic would likely reject on real data.
  • No regime detection: the strategy has no mechanism to detect when cointegration has broken down (beyond the stop-loss). A structural break in the relationship leads to systematic losses until the stop-loss triggers.
  • Simplified cost model: costs are modelled as a flat 30 bps on the spread. For a two-legged strategy, real costs include per-leg slippage, commissions, borrow costs for shorts, and funding. The costs.py module provides more realistic models but they have not yet been applied to the main backtest.

Potential Improvements

  • Longer out-of-sample data: extend the test window to 5+ years, or use temporal cross-validation (rolling in-sample/out-of-sample windows) to increase statistical power.
  • Walk-forward optimization: use the implemented walk_forward() function to adaptively select parameters per pair and per regime, with Deflated Sharpe Ratio to correct for multiple testing.
  • Rolling estimation: re-estimate the hedge ratio and OU parameters on a sliding window (e.g., 2 years) to adapt to evolving relationships.
  • Kalman filter for dynamic hedge ratio: replace the static Johansen estimate with a state-space model that continuously updates β.
  • Realistic cost scenarios: apply the square-root impact model and borrow costs from costs.py to assess whether the edge survives under realistic execution assumptions.
  • Regime detection: implement a cointegration stability monitor (e.g., CUSUM test on residuals) or use the regime segmentation from robustness.py to disable trading during unfavourable regimes.
  • Portfolio construction: trade multiple pairs simultaneously with capital allocation proportional to signal strength or half-life.
  • Maximum likelihood estimation: replace OLS with exact MLE for OU parameters, which provides more efficient estimates on small samples.

Technical Stack

  • Core: Python, NumPy, pandas
  • Statistical Testing: statsmodels (ADF, KPSS, Engle-Granger, Johansen), arch (Phillips-Perron), hurst (Hurst exponent)
  • Data: yfinance (Yahoo Finance API), CSV persistence
  • Visualization: matplotlib
  • Numerical: scipy (optimization, statistics)