Skip to main content

Statistical Arbitrage Strategies

Pairs trading, cointegration testing (Engle-Granger, Johansen), mean reversion via Ornstein-Uhlenbeck, spread monitoring, and risk management for stat arb.

Statistical Arbitrage in Crypto

Statistical arbitrage exploits temporary mispricings between related assets using mathematical models. Unlike directional trading, stat arb does not bet on whether the market goes up or down. It bets that the relationship between two or more assets will revert to its historical norm. When ETH/BTC deviates from its mean spread, a stat arb system goes long the underperformer and short the outperformer, profiting when the spread normalizes. The key assumption is mean reversion: that deviations from equilibrium are temporary.

In crypto, stat arb opportunities are more abundant than in traditional markets because of fragmented liquidity, retail-driven overreactions, and the prevalence of highly correlated assets (L1 tokens, DeFi tokens, meme tokens within the same narrative). The trade-off: crypto pairs can structurally diverge when narratives shift, tokenomics change, or one project fails, making risk management critical.

Finding Cointegrated Pairs

Cointegration is the statistical foundation of pairs trading. Two price series are cointegrated when their linear combination is stationary, meaning the spread between them fluctuates around a constant mean. Correlation measures whether two assets move in the same direction; cointegration measures whether they maintain a stable distance. Two assets can be highly correlated but not cointegrated (they trend together but drift apart over time), or weakly correlated but cointegrated (they move differently in the short term but snap back to equilibrium).

python-Engle-Granger cointegration test
1import ccxt
2import pandas as pd
3import numpy as np
4from statsmodels.tsa.stattools import coint, adfuller
5from itertools import combinations
6
7exchange = ccxt.binance({'enableRateLimit': True})
8
9# Fetch daily closes for candidate pairs
10symbols = ['BTC/USDT', 'ETH/USDT', 'SOL/USDT', 'AVAX/USDT',
11 'LINK/USDT', 'DOT/USDT', 'MATIC/USDT', 'ATOM/USDT']
12
13prices = {}
14for sym in symbols:
15 ohlcv = exchange.fetch_ohlcv(sym, '1d', limit=365)
16 df = pd.DataFrame(ohlcv, columns=['ts','o','h','l','c','v'])
17 prices[sym] = df.set_index('ts')['c']
18
19price_df = pd.DataFrame(prices).dropna()
20
21# Test all pairs for cointegration
22results = []
23for sym1, sym2 in combinations(symbols, 2):
24 score, p_value, _ = coint(price_df[sym1], price_df[sym2])
25 results.append({
26 'pair': f"{sym1} / {sym2}",
27 'test_stat': score,
28 'p_value': p_value,
29 'cointegrated': p_value < 0.05,
30 })
31
32coint_df = pd.DataFrame(results).sort_values('p_value')
33print("Cointegrated pairs (p < 0.05):")
34print(coint_df[coint_df['cointegrated']])

Johansen Test for Multi-Asset Cointegration

The Engle-Granger test works for two-asset pairs. The Johansen test extends cointegration testing to three or more assets simultaneously, finding all cointegrating vectors in a system. This is valuable for crypto baskets: for example, testing whether ETH, SOL, and AVAX share a common stochastic trend as "alt L1s" and constructing a portfolio that exploits deviations from the common factor.

python-Johansen cointegration for 3+ assets
1from statsmodels.tsa.vector_ar.vecm import coint_johansen
2
3# Test a basket of L1 tokens
4l1_basket = price_df[['ETH/USDT', 'SOL/USDT', 'AVAX/USDT']].values
5
6result = coint_johansen(l1_basket, det_order=0, k_ar_diff=1)
7
8# Compare trace statistics to critical values (95% confidence)
9print("Trace statistics vs critical values (95%):")
10for i in range(len(result.trace_stat)):
11 trace = result.trace_stat[i]
12 crit = result.trace_stat_crit_vals[i][1] # 95% critical value
13 is_coint = 'YES' if trace > crit else 'NO'
14 print(f" r <= {i}: Trace={trace:.2f}, Critical={crit:.2f} -> {is_coint}")
15
16# Cointegrating vector (hedge ratios)
17if result.trace_stat[0] > result.trace_stat_crit_vals[0][1]:
18 weights = result.evec[:, 0]
19 print(f"\nHedge ratios: ETH={weights[0]:.4f}, SOL={weights[1]:.4f}, AVAX={weights[2]:.4f}")

Spread Construction and Z-Score Trading

Once you identify a cointegrated pair, construct the spread using the hedge ratio from the cointegration regression. The spread should be stationary: fluctuating around a mean with a tendency to revert. Normalize the spread into a z-score (number of standard deviations from the mean) to generate entry and exit signals. Enter when the z-score exceeds a threshold (typically ±2.0), exit when it reverts to zero.

python-Spread construction and z-score signals
1import statsmodels.api as sm
2
3# Compute hedge ratio via OLS regression
4y = price_df['ETH/USDT']
5x = sm.add_constant(price_df['SOL/USDT'])
6model = sm.OLS(y, x).fit()
7hedge_ratio = model.params.iloc[1]
8intercept = model.params.iloc[0]
9
10print(f"Hedge ratio: {hedge_ratio:.4f}")
11print(f"R-squared: {model.rsquared:.4f}")
12
13# Construct the spread
14spread = price_df['ETH/USDT'] - hedge_ratio * price_df['SOL/USDT'] - intercept
15
16# Verify stationarity
17adf_stat, adf_p, *_ = adfuller(spread.dropna())
18print(f"ADF statistic: {adf_stat:.4f}, p-value: {adf_p:.4f}")
19
20# Compute rolling z-score
21lookback = 60 # 60-day rolling window
22spread_mean = spread.rolling(lookback).mean()
23spread_std = spread.rolling(lookback).std()
24z_score = (spread - spread_mean) / spread_std
25
26# Generate signals
27entry_threshold = 2.0
28exit_threshold = 0.0
29
30signals = pd.DataFrame(index=spread.index)
31signals['z_score'] = z_score
32signals['long_entry'] = z_score < -entry_threshold # Spread too low: buy ETH, sell SOL
33signals['short_entry'] = z_score > entry_threshold # Spread too high: sell ETH, buy SOL
34signals['exit'] = abs(z_score) < exit_threshold # Close when reverted to mean
35
36print(f"Long entries: {signals['long_entry'].sum()}")
37print(f"Short entries: {signals['short_entry'].sum()}")

Mean Reversion: Ornstein-Uhlenbeck Process

The Ornstein-Uhlenbeck (OU) process models how a spread reverts to its mean. The key parameter is the half-life: the time it takes for a deviation to decay by 50%. A half-life of 5 days means a 2σ deviation will reach 1σ in about 5 days. Short half-lives (3-15 days) indicate strong mean reversion and tradeable pairs. Long half-lives (30+ days) mean the spread meanders too slowly for practical trading. Your capital is locked in a position waiting for convergence.

python-Half-life estimation via OU process
1def estimate_half_life(spread: pd.Series) -> float:
2 """Estimate mean-reversion half-life using OLS on lagged spread."""
3 spread_lag = spread.shift(1).dropna()
4 spread_diff = spread.diff().dropna()
5
6 # Align the two series
7 spread_lag = spread_lag.iloc[1:]
8 spread_diff = spread_diff.iloc[1:]
9
10 spread_lag = sm.add_constant(spread_lag)
11 model = sm.OLS(spread_diff, spread_lag).fit()
12 theta = -model.params.iloc[1]
13
14 if theta <= 0:
15 return float('inf') # Not mean-reverting
16
17 half_life = np.log(2) / theta
18 return half_life
19
20hl = estimate_half_life(spread)
21print(f"Half-life: {hl:.1f} days")
22
23if hl < 15:
24 print("Strong mean reversion: suitable for trading")
25elif hl < 30:
26 print("Moderate mean reversion: tradeable with patience")
27else:
28 print("Weak mean reversion, not recommended for active trading")

Risk Management for Stat Arb

The biggest risk in stat arb is structural divergence: the cointegration relationship breaks permanently. This happens when one asset in the pair undergoes a fundamental change: a protocol hack, a tokenomics overhaul, a regulatory action, or a narrative shift that decouples the assets. The spread widens instead of reverting, and your "market-neutral" position turns into a catastrophic loss. LUNA/UST was a cointegrated pair until it was not.

Stop-loss on z-score

Exit if the z-score reaches 4.0+. If the spread is 4 standard deviations from the mean, the cointegration relationship may be breaking. Cut losses rather than doubling down.

Rolling cointegration check

Re-test cointegration on a rolling window (e.g., every 30 days using the last 180 days). If the p-value rises above 0.10, flatten the position and stop trading the pair.

Maximum holding period

If a trade has not reverted within 3x the estimated half-life, exit. A trade expected to close in 10 days that is still open after 30 days is behaving abnormally.

Position sizing

Risk 1-2% of capital per pair. Run multiple pairs simultaneously to diversify: a portfolio of 5-10 cointegrated pairs smooths returns and reduces single-pair blowup risk.

Structural break detection

Monitor for CUSUM (cumulative sum) test breaks on the spread. A CUSUM signal indicates the mean has shifted: the pair may no longer be cointegrated.

Full Implementation with ccxt

python-Complete pairs trading system
1import ccxt
2import pandas as pd
3import numpy as np
4from statsmodels.tsa.stattools import coint
5import asyncio
6
7class PairsTrader:
8 def __init__(self, exchange, sym1, sym2, lookback=60,
9 entry_z=2.0, exit_z=0.5, stop_z=4.0):
10 self.exchange = exchange
11 self.sym1 = sym1
12 self.sym2 = sym2
13 self.lookback = lookback
14 self.entry_z = entry_z
15 self.exit_z = exit_z
16 self.stop_z = stop_z
17 self.position = None # 'long_spread' or 'short_spread'
18 self.hedge_ratio = None
19
20 def update_hedge_ratio(self, prices1, prices2):
21 """Recalculate hedge ratio and check cointegration."""
22 _, p_val, _ = coint(prices1, prices2)
23 if p_val > 0.10:
24 return False # Cointegration lost
25
26 x = sm.add_constant(prices2)
27 model = sm.OLS(prices1, x).fit()
28 self.hedge_ratio = model.params.iloc[1]
29 return True
30
31 def compute_z_score(self, prices1, prices2):
32 """Compute current z-score of the spread."""
33 spread = prices1 - self.hedge_ratio * prices2
34 recent = spread.iloc[-self.lookback:]
35 z = (spread.iloc[-1] - recent.mean()) / recent.std()
36 return z
37
38 async def check_signal(self):
39 """Fetch prices and generate trading signals."""
40 p1 = self._fetch_closes(self.sym1)
41 p2 = self._fetch_closes(self.sym2)
42
43 is_coint = self.update_hedge_ratio(p1, p2)
44 if not is_coint:
45 if self.position:
46 await self._flatten()
47 return 'NO_COINT'
48
49 z = self.compute_z_score(p1, p2)
50
51 if self.position is None:
52 if z < -self.entry_z:
53 await self._enter_long_spread()
54 return 'ENTER_LONG'
55 elif z > self.entry_z:
56 await self._enter_short_spread()
57 return 'ENTER_SHORT'
58
59 elif self.position == 'long_spread':
60 if z > -self.exit_z or z < -self.stop_z:
61 await self._flatten()
62 return 'EXIT'
63
64 elif self.position == 'short_spread':
65 if z < self.exit_z or z > self.stop_z:
66 await self._flatten()
67 return 'EXIT'
68
69 return 'HOLD'
70
71 def _fetch_closes(self, symbol):
72 ohlcv = self.exchange.fetch_ohlcv(symbol, '1d', limit=200)
73 return pd.Series([c[4] for c in ohlcv])

Cointegration is not permanent

Every stat arb trade is a bet that a historical relationship will persist. In crypto, relationships break faster than in equities because of rapid narrative shifts, token unlocks, and protocol changes. Re-test cointegration regularly, use strict stop-losses on z-score, and never treat a cointegrated pair as a risk-free trade. The pairs that look most stable are often the ones that break most catastrophically.
Module Quiz

1.What is the fundamental difference between correlation and cointegration?

2.A cointegrated pair has an estimated half-life of 45 days. What does this imply for trading?

3.Your pairs trade z-score has reached -4.2, well beyond your entry at -2.0. What should you do?

4.Why is the Johansen test preferred over Engle-Granger for testing cointegration among 3+ assets?

5.What is the most dangerous risk in statistical arbitrage that cannot be hedged with stop-losses alone?

0/5 answered

Put this lesson to work

Free on Thrive, no account needed.