This is a comprehensive question about pairs trading using cointegration. Let me break this down systematically:
- What is pairs trading?
- Cointegration approach
- Why correlation is insufficient
- Regression of stocks
- ADF test for stationarity
- Z-score trading signals
Let me provide a detailed explanation:
1. Pairs Trading Overview
Pairs trading is a market-neutral strategy that involves taking a long position in one security and a short position in a related security, aiming to profit from the convergence of their prices.
2. The Cointegration Approach
A. Why Correlation is Insufficient
Correlation measures the linear relationship between two variables but has a critical flaw for pairs trading:
- Two series can be highly correlated but both trending (non-stationary)
- If two stocks move upward together with high correlation, both might be in uptrends driven by the overall market
- Correlation is not stable over time - it can change rapidly
- Correlation doesn't guarantee mean reversion - critical for pairs trading
- Spurious correlation: Two random walks can have high correlation by chance ("spurious regression")
Example: If Stock A and Stock B both trend upward together with correlation 0.95, a pairs trader expecting mean reversion would be disappointed if they both continue uptrending indefinitely.
B. Cointegration Concept
Cointegration is a stronger relationship than correlation:
- Two non-stationary series are cointegrated if a linear combination of them is stationary
- If Stock A and Stock B are cointegrated, their difference (or a weighted combination) will mean-revert
- This provides a theoretical basis for mean reversion in pairs trading
- Cointegrated pairs have a long-run equilibrium relationship
Mathematical definition:
-
Two I(1) series (integrated of order 1) are cointegrated if there exists a vector β such that the combination (Stock A - β × Stock B) is I(0) (stationary)
-
The coefficient β represents the hedge ratio, determining how many shares of Stock B to short for each share of Stock A held long
3. Regression of Stocks
To establish the cointegration relationship, I run an OLS regression: Stock_A_t = α + β × Stock_B_t + ε_t, where β is the hedge ratio derived from the regression coefficient. The residual ε_t represents the spread between the two stocks—this is what I'll monitor for trading signals. The regression essentially finds the optimal weighting to create a stationary spread from two non-stationary price series.
4. ADF Test for Stationarity
Once I have the spread, I need to verify it's stationary using the Augmented Dickey-Fuller test. The ADF test checks whether a time series has a unit root (non-stationary) or is mean-reverting (stationary). Individual stock prices typically fail this test since they're I(1) processes, but their cointegrated spread should be I(0)—this is the key requirement for pairs trading to work. If the p-value is below 0.05, I can reject the null hypothesis and confirm the spread is stationary.
5. Trading Signals: Z-Score Method
To generate trading signals, I calculate the z-score of the spread by standardizing it against its historical mean and standard deviation over a training window. This tells me how many standard deviations the current spread is from its equilibrium. When the z-score reaches extreme levels (typically ±2 or ±3), it signals a mean-reversion opportunity—I go long the underperforming stock and short the outperformer, betting that the spread will revert to zero.
I enter long positions when z_score drops below -2, indicating Stock A is cheap relative to Stock B and should bounce back. Conversely, I short when z_score exceeds +2, as Stock A appears overvalued. I exit when the spread returns to its mean (z_score = 0) or tighten my stop if the deviation worsens further, protecting against cases where the relationship breaks down.
The ±2 threshold works because values beyond this range occur in only about 5% of cases under normal conditions—rare enough to signal genuine mispricings but frequent enough to generate actionable trades. With a spread averaging 0 and standard deviation of 5, a current reading of 12 gives a z_score of 2.4, triggering a short since Stock A has drifted too far above its fair value relative to Stock B.
The workflow involves identifying cointegrated pairs, calculating the hedge ratio through regression, confirming the residuals are stationary via ADF testing, then computing the spread and monitoring its z_score for entry and exit opportunities.
The strategy's appeal lies in its market-neutral positioning and statistical foundation—it profits regardless of market direction. However, cointegration relationships can deteriorate, transaction costs bite into returns, and both securities must maintain adequate liquidity. The hedge ratio requires periodic recalibration, and extreme events can still inflict significant losses. Effective implementation demands rolling regressions to keep β current, vigilance around correlation shifts, out-of-sample validation, careful position sizing using methods like the Kelly Criterion, and continuous scanning for structural breaks in the relationship.
Cointegration in Pairs Trading: Complete Guide
Why Correlation Is Insufficient
Correlation measures linear co-movement but fails for pairs trading because:
| Issue | Problem |
|---|
| Non-stationarity | Two uptrending stocks can have ρ=0.95 but never revert—both just keep rising |
| Unstable over time | Correlation changes regime-to-regime; yesterday's 0.90 can become 0.40 |
| No mean reversion | High correlation doesn't guarantee convergence—fundamental requirement for profits |
| Spurious regression | Random walks can appear highly correlated by chance (Granger & Newbold, 1974) |
Critical insight: Pairs trading requires the spread to mean-revert, not just move together.
The Cointegration Framework
Core Concept
Two non-stationary price series are cointegrated if a linear combination of them is stationary:
Spreadt=PAt−β⋅
where the residual is I(0) (stationary) even though individual prices are I(1) (random walks).
Intuition: Prices move together in the long run but temporarily deviate—deviations are temporary and revert to equilibrium.
Step 1: Regression to Find Hedge Ratio
Run Ordinary Least Squares (OLS) on historical data:
PAt=α+β⋅PB
Example output:
Stock A = 2.15 + 1.32 × Stock B + residual
β (hedge ratio) = 1.32
α (intercept) = 2.15
The hedge ratio tells you the equilibrium relationship:
- For every 1moveinStockB,StockAmoves1.32
- This becomes your position sizing ratio
Step 2: ADF Test for Stationarity
The Augmented Dickey-Fuller (ADF) test checks if the residuals are stationary.
How the Test Works
Regress:
Δϵt=γ⋅ϵt−1
Hypotheses:
- H₀: γ = 0 (unit root exists → non-stationary)
- H₁: γ < 0 (stationary)
Typical Results
# Stock A alone
ADF statistic: -1.23, p-value: 0.68 → NOT stationary ❌
# Stock B alone
ADF statistic: -0.95, p-value: 0.72 → NOT stationary ❌
# Spread (residuals)
ADF statistic: -3.87, p-value: 0.002 → STATIONARY ✓
Decision rule:
- If p-value < 0.05: Reject null → residuals are stationary → VALID PAIR ✓
- If p-value > 0.05: Fail to reject → non-stationary → SKIP PAIR ✗
Why This Matters
Stationary residuals guarantee mean reversion—deviations eventually collapse back to zero.
Step 3: Trading with Z-Score Signals
Calculate the Spread
Using the regression results:
Spreadt=PAt−2.15−
Calculate rolling mean and rolling std (e.g., 60-day window):
z-scoret=σspread
Trading Rules (|z-score| > 2)
| Condition | Signal | Action | Rationale |
|---|
| z > +2 | Overextended | Short spread: Short A, Long B | Stock A overpriced; revert downward |
| z < -2 | Underextended | Long spread: Long A, Short B | Stock A underpriced; revert upward |
| z → 0 | Mean reversion | Close position | Profit taken; spread converged |
Why z-score > 2?
P(∥Z∥>2)≈0.05 in normal distribution
- Rare event (5% probability) suggests genuine mispricing
- Statistical significance without over-trading
- Threshold can be adjusted (2.5 is more conservative, 1.5 more aggressive)
Complete Example: XOM vs CVX (Energy Stocks)
Step 1: Run Regression (252 trading days)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
XOM = -0.45 + 0.92 × CVX + ε
(α = -0.45, β = 0.92, R² = 0.887)
Step 2: ADF Test Residuals
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ADF stat: -4.12, p-value: 0.001 ✓ COINTEGRATED
Step 3: Today's Signal
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
XOM Price: $107.50
CVX Price: $118.20
Spread = 107.50 - (-0.45) - 0.92(118.20) = 3.24
60-day mean spread: 0.00
60-day std: 1.50
z-score = (3.24 - 0.00) / 1.50 = 2.16 ✓ SIGNAL
ACTION: SHORT the spread
• Sell 1,000 shares XOM (short $107.5K)
• Buy 1,080 shares CVX (long $127.7K) [920 shares × 1/0.92]
This creates delta-neutral hedge waiting for GRR to mean-revert.
Critical Considerations
Assumptions to Monitor
| Risk | Mitigation |
|---|
| Cointegration breaks | Retest ADF quarterly; monitor correlation drift |
| Beta instability | Use 60-90 day rolling windows; recalibrate weekly |
| Transaction costs | Ensure spread > 4-5 basis points before entry |
| Liquidity dry-up | Both stocks must be highly liquid; avoid small-cap pairs |
| Structural breaks | M&A, sector divergence kills relationship |
Out-of-Sample Validation
- Estimate regression on data through Day T
- Test pair quality Days T+1 to T+60
- Trade only if z-score signal profitable in unseen data
Python Implementation Sketch
import statsmodels.api as sm
from statsmodels.tsa.stattools import adfuller
# 1. Regression
X = sm.add_constant(stockB_prices)
model = sm.OLS(stockA_prices, X)
results = model.fit()
beta, alpha = results.params
# 2. ADF Test
spread = stockA_prices - alpha - beta * stockB_prices
adf_stat, p_value, _, _, _ = adfuller(spread)
if p_value < 0.05:
print("✓ Pair is cointegrated")
# 3. Z-Score Trading
z_score = (spread - spread.rolling(60).mean()) / spread.rolling(60).std()
if z_score[-1] > 2:
print("SHORT the spread")
elif z_score[-1] < -2:
print("LONG the spread")
Key Takeaway
Cointegration > Correlation because it guarantees mean reversion of residuals. The ADF test validates this mathematically, and z-score extremes provide actionable signals—but only if proper backtesting and position sizing are applied.