Pairs Trading with Ornstein-Uhlenbeck: Python Implementation


Statistical arbitrage relies on the assumption that correlated assets will revert to their historical mean relationship. The most rigorous framework for modeling this behavior is the Ornstein-Uhlenbeck (OU) process, a mean-reverting stochastic differential equation. Unlike simple moving average crossovers, the OU process provides a probabilistic foundation for entry and exit signals, allowing traders to quantify the speed of reversion and the magnitude of deviation.

The Ornstein-Uhlenbeck Process

The OU process is defined by the following stochastic differential equation:

$$dX_t = \theta(\mu - X_t)dt + \sigma dW_t$$

Where:

  • $X_t$ is the spread between the two assets.
  • $\theta$ is the speed of reversion (higher values indicate faster mean reversion).
  • $\mu$ is the long-term mean of the spread.
  • $\sigma$ is the volatility of the spread.
  • $W_t$ is a Wiener process (Brownian motion).

The half-life of the process, representing the time it takes for the spread to revert halfway to its mean, is calculated as:

$$t_{1/2} = \frac{\ln(2)}{\theta}$$

A robust pairs trading strategy requires:

  1. Cointegration: The spread must be stationary.
  2. Significant Reversion Speed: $\theta$ must be large enough to overcome transaction costs.
  3. Stable Volatility: $\sigma$ should not exhibit explosive trends.

Data Preparation and Cointegration Check

Before applying the OU model, we must verify that the assets are cointegrated. We use the Johansen test or the Augmented Dickey-Fuller (ADF) test on the spread. For this implementation, we assume we have already identified a cointegrated pair (e.g., KO and PEP, two Coca-Cola products).

import numpy as np
import pandas as pd
import yfinance as yf
from statsmodels.tsa.stattools import adfuller
import statsmodels.api as sm
from scipy import stats

# 1. Fetch Data
# Use yfinance for demonstration; in production, use a low-latency data feed
assets = ['KO', 'PEP']
prices = yf.download(assets, start='2020-01-01', end='2023-01-01')['Adj Close']

# 2. Calculate Spread
# Use OLS to find the hedge ratio (beta)
X = prices[assets[1]].values
y = prices[assets[0]].values
X = sm.add_constant(X)
model = sm.OLS(y, X).fit()

# Calculate the spread: y - beta * x
spread = y - model.params[1] * X[:, 1]
spread = pd.Series(spread, index=prices.index)

# 3. Stationarity Check (ADF Test)
adf_stat, p_value, _, _, _, _ = adfuller(spread)
print(f"ADF Test p-value: {p_value}")
if p_value > 0.05:
    print("Warning: Spread is not stationary. Do not trade.")
else:
    print("Spread is stationary. Proceeding with OU estimation.")

Estimating OU Parameters

We estimate the OU parameters using Maximum Likelihood Estimation (MLE). The discrete-time approximation of the OU process is:

$$X_{t+1} - X_t = \theta(\mu - X_t)\Delta t + \sigma \sqrt{\Delta t} \epsilon_t$$

Rearranging for regression:

$$X_{t+1} = \alpha + \beta X_t + \epsilon_t$$

Where:

  • $\beta = e^{-\theta \Delta t}$
  • $\alpha = \mu(1 - \beta)$
  • $\sigma = \frac{\sqrt{\text{Var}(\epsilon_t)}}{\sqrt{1 - \beta^2}}$
def estimate_ou_params(spread, freq='D'):
    """
    Estimate OU parameters using linear regression.
    """
    # Create lagged variable
    X = spread.shift(1).dropna()
    y = spread.dropna()
    
    # Ensure indices align
    common_idx = X.index.intersection(y.index)
    X = X[common_idx]
    y = y[common_idx]
    
    # Add constant for intercept
    X = sm.add_constant(X)
    
    # Fit OLS
    model = sm.OLS(y, X).fit()
    
    # Extract parameters
    beta = model.params[1]  # Slope
    alpha = model.params[0] # Intercept
    
    # Calculate theta, mu, sigma
    if freq == 'D':
        dt = 1.0
    elif freq == 'H':
        dt = 1.0/24.0
    else:
        dt = 1.0
        
    theta = -np.log(beta) / dt
    mu = alpha / (1 - beta)
    
    # Residuals
    residuals = y - model.predict(X)
    sigma = np.std(residuals) / np.sqrt(1 - beta**2) * np.sqrt(dt)
    
    # Half-life
    half_life = np.log(2) / theta
    
    return {
        'theta': theta,
        'mu': mu,
        'sigma': sigma,
        'half_life': half_life,
        'r_squared': model.rsquared
    }

# Estimate parameters
ou_params = estimate_ou_params(spread)
print(f"Theta: {ou_params['theta']:.4f}")
print(f"Mean: {ou_params['mu']:.4f}")
print(f"Volatility: {ou_params['sigma']:.4f}")
print(f"Half-life: {ou_params['half_life']:.2f} days")
print(f"R-squared: {ou_params['r_squared']:.4f}")

Signal Generation

We generate trading signals based on the Z-score of the spread. The Z-score measures how many standard deviations the current spread is from its mean.

$$Z_t = \frac{X_t - \mu}{\sigma_{steady}}$$

Where $\sigma_{steady} = \frac{\sigma}{\sqrt{2\theta}}$ is the steady-state standard deviation.

We enter a long position on the spread when $Z_t < -2$ (spread is too low) and exit when $Z_t > 0$ (reverted to mean). Conversely, we enter short when $Z_t > 2$ and exit when $Z_t < 0$.

def generate_signals(spread, ou_params, entry_z=2.0, exit_z=0.0):
    """
    Generate trading signals based on Z-score.
    """
    mu = ou_params['mu']
    sigma_steady = ou_params['sigma'] / np.sqrt(2 * ou_params['theta'])
    
    # Calculate Z-score
    z_score = (spread - mu) / sigma_steady
    
    # Initialize signals
    signals = pd.Series(0, index=spread.index)
    
    # State machine for signals
    position = 0
    for i in range(len(z_score)):
        z = z_score.iloc[i]
        
        if position == 0:
            if z < -entry_z:
                position = 1  # Long spread (Buy KO, Sell PEP)
            elif z > entry_z:
                position = -1  # Short spread (Sell KO, Buy PEP)
        elif position == 1:
            if z > exit_z:
                position = 0  # Exit long
        elif position == -1:
            if z < -exit_z:
                position = 0  # Exit short
        
        signals.iloc[i] = position
    
    return signals, z_score

signals, z_score = generate_signals(spread, ou_params)

Backtesting with VectorBT

We use vectorbt for high-performance backtesting. This library allows for vectorized backtesting, which is crucial for optimizing parameters across thousands of asset pairs.

import vectorbt as vbt

# Calculate PnL
# Long spread: Buy KO, Sell PEP
# Short spread: Sell KO, Buy PEP

# We need to construct the portfolio PnL based on signals
# Signal 1: Long KO, Short PEP
# Signal -1: Short KO, Long PEP
# Signal 0: Flat

# Calculate returns
returns = prices.pct_change().dropna()

# Construct portfolio returns
# When signal is 1: Return = Return_KO - Return_PEP
# When signal is -1: Return = Return_PEP - Return_KO

portfolio_returns = pd.Series(0.0, index=returns.index)

for i in range(1, len(returns)):
    sig = signals.iloc[i-1]  # Use previous day's signal
    if sig == 1:
        portfolio_returns.iloc[i] = returns['KO'].iloc[i] - returns['PEP'].iloc[i]
    elif sig == -1:
        portfolio_returns.iloc[i] = returns['PEP'].iloc[i] - returns['KO'].iloc[i]
    else:
        portfolio_returns.iloc[i] = 0.0

# Calculate cumulative returns
cumulative_returns = (1 + portfolio_returns).cumprod()

# Performance Metrics
sharpe_ratio = portfolio_returns.mean() / portfolio_returns.std() * np.sqrt(252)
sortino_ratio = portfolio_returns.mean() / portfolio_returns[portfolio_returns < 0].std() * np.sqrt(252)
max_drawdown = (cumulative_returns - cumulative_returns.cummax()).min()

print(f"Sharpe Ratio: {sharpe_ratio:.2f}")
print(f"Sortino Ratio: {sortino_ratio:.2f}")
print(f"Max Drawdown: {max_drawdown:.2%}")

# Plotting
import matplotlib.pyplot as plt

plt.figure(figsize=(12, 6))
plt.plot(cumulative_returns, label='Strategy')
plt.plot((1 + returns['KO'] - returns['PEP']).cumprod(), label='Buy KO Sell PEP (Unhedged)')
plt.title('Pairs Trading Strategy Performance')
plt.legend()
plt.show()

Backtest Limitations and Real-World Constraints

The backtest above assumes ideal conditions. In production, you must account for:

  1. Slippage: Assume a 1-2 basis point slippage per trade. For highly liquid pairs like KO/PEP, this is minimal. For smaller caps, slippage can erode profits significantly.
  2. Transaction Costs: Include commission and spread. For Alpaca or Interactive Brokers, commissions are low, but the bid-ask spread is a real cost.
  3. Liquidity Limits: Ensure the position size does not exceed a certain percentage of the daily average volume (e.g., 5%).
  4. Regime Shifts: The OU parameters are estimated on historical data. If the market regime changes (e.g., a merger announcement), the cointegration may break down. Monitor the ADF test p-value continuously and exit if it exceeds 0.05.
  5. Look-Ahead Bias: Ensure that signals are generated using data available at the time of the trade. The code above uses signals.iloc[i-1] to avoid look-ahead bias.

Deployment Considerations

For 24/7 continuous execution, deploy your strategy on a low-latency Cloud VPS (e.g., AWS EC2 or DigitalOcean) located near your broker’s matching engine. Use a message queue (e.g., Redis or RabbitMQ) to decouple signal generation from order execution.

For order routing, integrate with Alpaca or Interactive Brokers APIs. Alpaca is ideal for US equities and crypto, offering a simple REST API. Interactive Brokers is better for global multi-asset trading.

Conclusion

The Ornstein-Uhlenbeck process provides a robust framework for pairs trading. By estimating the speed of reversion and volatility, you can generate statistically sound entry and exit signals. However, always backtest with realistic transaction costs and monitor for regime shifts. Use vectorized backtesting tools like vectorbt to optimize parameters across multiple asset pairs efficiently.

Next Steps:

  1. Expand the universe to include more cointegrated pairs.
  2. Implement dynamic hedge ratios using rolling windows.
  3. Add risk management rules based on maximum drawdown.
  4. Deploy on a VPS for live trading.
SEBI MANDATORY REGULATORY DISCLAIMER

Important Notice & Educational Purpose: XAlgoPro (xalgopro.com) and its authors/contributors are NOT SEBI registered Research Analysts (RA) or Investment Advisers (IA) under the SEBI (Research Analysts) Regulations, 2014, or SEBI (Investment Advisers) Regulations, 2013.

All content, algorithmic logic, indicators, Pine Script codes, Python scripts, statistical models, mathematical formulas, and backtest results presented on this platform are published strictly for educational, academic, and technological research purposes only. Nothing on this website constitutes investment advice, financial guidance, an offer, recommendation, or solicitation to buy or sell any security, derivative, contract, or financial instrument on the National Stock Exchange (NSE), Bombay Stock Exchange (BSE), or any other global exchange.

SEBI Statutory Risk Disclosure on Derivatives (F&O):As per SEBI study on Intraday & Derivatives trading, 9 out of 10 individual traders in the Equity Futures and Options (F&O) segment incurred net losses, with an average loss of over ₹50,000 per trader. Over and above net trading losses, loss-makers expended an additional 15% to 50% in transaction fees, brokerage, and statutory taxes (STT, GST, Stamp Duty). Trading options and futures involves substantial financial risk, leverage, and potential loss of entire invested capital.

Past algorithmic backtest performance or hypothetical simulations do not guarantee or represent future live trading results. Readers and users must perform their own independent due diligence, test thoroughly in simulated/paper trading environments, and consult an authorized SEBI Registered Financial Advisor before risking actual capital in Indian equity or derivatives markets. You are solely responsible for all trading decisions, capital allocations, and monetary risks undertaken.