6.1.6Algorithmic & Quant Trading

Learn pairs trading and cointegration

2,415 words11 min readdifficulty · medium1 backlinks

The Statistical Foundation

What Is Cointegration?

Why this definition matters:

  • Individual stock prices are random walks (non-stationary): Pt=Pt1+ϵtP_t = P_{t-1} + \epsilon_t. No mean reversion.
  • But if PAP_A and PBP_B are cointegrated, their spread St=PAβPBS_t = P_A - \beta P_B does mean-revert. We can trade that.

How to find β\beta? Run an ==Ordinary Least Squares (OLS) regression==:

Yt=α+βXt+ϵtY_t = \alpha + \beta X_t + \epsilon_t

The slope β\beta is the ==hedge ratio==—how many units of XX to trade per unit of YY to create a market-neutral position.

Deriving the Spread from First Principles

Start with two stock prices:

  • Stock A: PA(t)P_A(t)
  • Stock B: PB(t)P_B(t)

Step 1: Regress PAP_A on PBP_B

PA(t)=α+βPB(t)+ϵ(t)P_A(t) = \alpha + \beta P_B(t) + \epsilon(t)

Why? We're finding the linear relationship. β\beta tells us "for every 1moveinB,Amoves1 move in B, A moves \beta$ dollars on average."

Step 2: Construct the spread

S(t)=PA(t)βPB(t)αS(t) = P_A(t) - \beta P_B(t) - \alpha

Why subtract α\alpha? To center the spread around zero. Now S(t)S(t) represents the deviation from the long-run relationship.

Step 3: Test if S(t)S(t) is stationary
Use the ==Augmented Dickey-Fuller (ADF) test==. Null hypothesis: "S has a unit root (non-stationary)." If we reject (p-value < 0.05), SS is stationary → the pair is cointegrated.

Figure — Learn pairs trading and cointegration

Why Z-score? It's unit-agnostic (works whether stocks are 10or10 or 1000) and probabilistic: Z>2|Z| > 2 happens ~5% of the time if SS is Gaussian.

Step-by-Step: Building a Pairs Trade

Example 1: Coca-Cola (KO) vs. PepsiCo (PEP)

Context: Both are beverage giants. Similar business models, corelated with consumer spending.

Step 1: Collect daily prices for2 years
Suppose:

  • KO closes at 60today,PEPat60 today, PEP at 180.

Step 2: Regress KO on PEP
OLS gives β=0.32\beta = 0.32 (for every 1PEPmoves,KOmoves1 PEP moves, KO moves 0.32).

Step 3: Calculate the spread

S(t)=KO(t)0.32×PEP(t)S(t) = \text{KO}(t) - 0.32 \times \text{PEP}(t)

Today: S=600.32×180=6057.6=2.4S = 60 - 0.32 \times 180 = 60 - 57.6 = 2.4.

Step 4: Run ADF test on historical SS
Get p-value = 0.01 → Reject unit root → Cointegrated ✓

Step 5: Compute Z-score
Historical μS=1.0\mu_S = 1.0, σS=0.8\sigma_S = 0.8.

Z=2.41.00.8=1.75Z = \frac{2.4 - 1.0}{0.8} = 1.75

Interpretation: Spread is 1.75 standard deviations above mean. Not quite at our +2 threshold, so we wait.

Next day: KO jumps to 62,PEPstays62, PEP stays 180.

S=620.32×180=4.4,Z=4.41.00.8=4.25S = 62 - 0.32 \times 180 = 4.4, \quad Z = \frac{4.4 - 1.0}{0.8} = 4.25

Action: Short 100 shares of KO, long 32 shares of PEP (to match the β=0.32\beta = 0.32 ratio). Our exposure: neutral to market moves, only profits from spread converging.

Why this step? When the spread is abnormally wide, KO is overpriced relative to PEP. We expect mean reversion.

Exit: When ZZ drops below 0.5, close both legs. If it never happens (spread diverges forever), we eat a loss—hence the need for stop-losses.

Example 2: Gold Miners (GDX) vs. Gold (GLD)

Context: GDX holds gold mining stocks. GLD holds physical gold. Miners are leveraged bets on gold prices.

Regression: GDX(t)=α+1.8×GLD(t)+ϵ(t)\text{GDX}(t) = \alpha + 1.8 \times \text{GLD}(t) + \epsilon(t)β=1.8\beta = 1.8.

Scenario: Gold rallies, but miners lag.

  • GLD = 200,GDX=200, GDX = 350.
  • Expected GDX = 1.8×200+α=3651.8 \times 200 + \alpha = 365 (assuming α=5\alpha = 5).
  • Spread S=350365=15S = 350 - 365 = -15 → Miners underpriced relative to gold.

Z-score = -2.3 (assuming μS=0\mu_S = 0, σS=6.5\sigma_S = 6.5).

Trade: Long GDX, short GLD. Wait for catch-up.

Why this step? The negative spread means miners haven't followed gold's move yet. Historically, they do.

Common Mistakes (Steel-man Your Errors)

The Math Behind Cointegration Tests

Augmented Dickey-Fuller (ADF) Test

We test if the spread StS_t follows:

ΔSt=α+γSt1+i=1pβiΔSti+ϵt\Delta S_t = \alpha + \gamma S_{t-1} + \sum_{i=1}^{p} \beta_i \Delta S_{t-i} + \epsilon_t

Null hypothesis: γ=0\gamma = 0 (unit root → non-stationary).
Alternative: γ<0\gamma < 0 (mean-reverting).

Why this form? ΔSt=StSt1\Delta S_t = S_t - S_{t-1} is the first difference. If γ<0\gamma < 0, past values of SS negatively affect future changes → pull back to mean.

Decision rule: If ADF statistic < critical value (or p-value < 0.05), reject null → cointegrated.

Practical note: Use 1-year to 2-year daily data. Too short → false positives. Too long → miss regime changes.

The Johansen Test (Multiple Pairs)

For a basket of n>2n > 2 stocks, use the ==Johansen test==. It finds all cointegrating relationships simultaneously via eigenvalue decomposition of the error-correction matrix.

Why? With 3+ stocks, there might be multiple cointegrating vectors (e.g., A-B cointegrated, B-C cointegrated → A-C cointegrated by transitivity). Johansen catches them all.

Building a Robust Pairs Trading System

  1. Pair Selection:
    Screen for:

    • Same sector (energy, financials, etc.).
    • Similar market cap (avoid pairing mega-cap with small-cap).
    • High correlation + passing ADF test.
  2. In-Sample Testing:
    Use first 70% of data to estimate β\beta, μS\mu_S, σS\sigma_S.

  3. Out-of-Sample Validation:
    Test on remaining 30%. Did historical Z-scores predict actual reversions?

  4. Risk Management:

    • Stop-loss if Z>4|Z| > 4 (spread diverging, not reverting).
    • Max hold period (e.g., 30 days).
    • Position sizing: never risk > 2% capital per pair.
  5. Execution:

    • Enter simultaneously (market orders → slippage risk).
    • Monitor for earnings, dividends, corporate actions (break cointegration).
Recall Explain Like I'm 12

Imagine two best friends, Alice and Bob, who always share their Halloween candy 50-50. One day, Alice ends up with 80 pieces, Bob with 40. That's weird! You bet that by next week, they'll share more evenly again—maybe Alice gives some to Bob, or Bob trades for more. That's pairs trading: when two things that usually stick together get too far apart, you bet they'll come back together. Cointegration is the math way of saying "these two friends always end up balancing out, even if they drift apart for a bit."

Connections

  • Mean Reversion Strategies – Pairs trading is a subset; understanding Ornstein-Uhlenbeck processes deepens your grasp.
  • Statistical Arbitrage – Pairs trading is the simplest stat-arb strategy; scales to baskets.
  • Market Neutral Strategies – Hedge ratio ensures zero market beta.
  • Time Series Analysis – Stationarity, autocorrelation, and ARMA models underpin spread modeling.
  • Risk Management in Algo Trading – Stop-losses and position sizing are critical when spreads diverge.
  • Backtesting and Walk-Forward Analysis – Avoid overfitting by validating out-of-sample.

#flashcards/stock-market

What is cointegration in pairs trading? :: Two non-stationary price series are cointegrated if their linear combination (spread) is stationary (mean-reverting), allowing us to trade the spread.

How do you calculate the hedge ratio β in pairs trading?
Run an OLS regression Y = α + βX + ε. The slope β tells you how many units of X to trade per unit of Y to create a market-neutral position.
What does a Z-score > +2 signal in pairs trading?
The spread is abnormally wide (2 std devs above mean) → short the outperformer, long the underperformer, expecting mean reversion.
Why can't you rely on correlation alone for pairs trading?
High correlation means co-movement but doesn't guarantee the spread is mean-reverting. Two stocks can correlate yet diverge permanently. Cointegration (tested via ADF) is required.
What is the ADF test and why do we use it?
Augmented Dickey-Fuller test checks if the spread has a unit root (non-stationary). Rejecting the null (p < 0.05) confirms the spread is stationary → pair is cointegrated.
How do you construct the spread in pairs trading?
S(t) = P_A(t) - β P_B(t) - α, where β is the hedge ratio from regression and α centers the spread around zero.
When should you exit a pairs trade?
When |Z| < 0.5 (spread returned to mean) or if a stop-loss is hit (|Z| > 4, indicating divergence instead of reversion).
What is the half-life of mean reversion and why does it matter?
Time for the spread to decay halfway back to its mean. If too long (>30 days), capital is tied up inefficiently. Calculate via AR(1): half-life = ln(0.5)/ln(φ).
Why must pairs be from the same sector?
They share economic drivers (oil prices for energy, interest rates for banks). Different sectors may correlate by chance but lack fundamental linkage → cointegration breaks.
Why is the hedge ratio β different from relative volatility?
β is the OLS regression slope capturing average dollar-for-dollar co-movement in the cointegrating relationship; volatility measures the size of random fluctuations. Size legs by β, not by a volatility ratio.

Concept Map

relies on

guaranteed by

defined as

random walks

combines

estimates

builds

tested by

confirms

normalized into

triggers

Z above +2 short A long B

Z below -2 long A short B

Pairs Trading

Mean-Reverting Spread

Cointegration

Stationary Linear Combo

Non-Stationary Prices

No Mean Reversion

OLS Regression

Hedge Ratio Beta

Spread S t

ADF Test

Z-Score

Trading Rules

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Pairs trading ek statistical arbitrage strategy hai jisme ap do related stocks ka spread trade karte ho. Socho Coca-Cola aur Pepsi – dono beverage companies hain, similar business model hai. Agar inke prices normally sath chalte hain (cointegrated hain), lekin ek din Coke zyada upar chala gaya aur Pepsi peeche reh gayi, toh aap bet karte ho ki ye gap close hoga. Aap Coke ko short karo (becho) aur Pepsi ko long

Test yourself — Algorithmic & Quant Trading

Connections