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).
1import ccxt2import pandas as pd3import numpy as np4from statsmodels.tsa.stattools import coint, adfuller5from itertools import combinations67exchange = ccxt.binance({'enableRateLimit': True})89# Fetch daily closes for candidate pairs10symbols = ['BTC/USDT', 'ETH/USDT', 'SOL/USDT', 'AVAX/USDT',11 'LINK/USDT', 'DOT/USDT', 'MATIC/USDT', 'ATOM/USDT']1213prices = {}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']1819price_df = pd.DataFrame(prices).dropna()2021# Test all pairs for cointegration22results = []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 })3132coint_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.
1from statsmodels.tsa.vector_ar.vecm import coint_johansen23# Test a basket of L1 tokens4l1_basket = price_df[['ETH/USDT', 'SOL/USDT', 'AVAX/USDT']].values56result = coint_johansen(l1_basket, det_order=0, k_ar_diff=1)78# 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 value13 is_coint = 'YES' if trace > crit else 'NO'14 print(f" r <= {i}: Trace={trace:.2f}, Critical={crit:.2f} -> {is_coint}")1516# 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.
1import statsmodels.api as sm23# Compute hedge ratio via OLS regression4y = 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]910print(f"Hedge ratio: {hedge_ratio:.4f}")11print(f"R-squared: {model.rsquared:.4f}")1213# Construct the spread14spread = price_df['ETH/USDT'] - hedge_ratio * price_df['SOL/USDT'] - intercept1516# Verify stationarity17adf_stat, adf_p, *_ = adfuller(spread.dropna())18print(f"ADF statistic: {adf_stat:.4f}, p-value: {adf_p:.4f}")1920# Compute rolling z-score21lookback = 60 # 60-day rolling window22spread_mean = spread.rolling(lookback).mean()23spread_std = spread.rolling(lookback).std()24z_score = (spread - spread_mean) / spread_std2526# Generate signals27entry_threshold = 2.028exit_threshold = 0.02930signals = pd.DataFrame(index=spread.index)31signals['z_score'] = z_score32signals['long_entry'] = z_score < -entry_threshold # Spread too low: buy ETH, sell SOL33signals['short_entry'] = z_score > entry_threshold # Spread too high: sell ETH, buy SOL34signals['exit'] = abs(z_score) < exit_threshold # Close when reverted to mean3536print(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.
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()56 # Align the two series7 spread_lag = spread_lag.iloc[1:]8 spread_diff = spread_diff.iloc[1:]910 spread_lag = sm.add_constant(spread_lag)11 model = sm.OLS(spread_diff, spread_lag).fit()12 theta = -model.params.iloc[1]1314 if theta <= 0:15 return float('inf') # Not mean-reverting1617 half_life = np.log(2) / theta18 return half_life1920hl = estimate_half_life(spread)21print(f"Half-life: {hl:.1f} days")2223if 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.
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.
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.
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.
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.
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
1import ccxt2import pandas as pd3import numpy as np4from statsmodels.tsa.stattools import coint5import asyncio67class 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 = exchange11 self.sym1 = sym112 self.sym2 = sym213 self.lookback = lookback14 self.entry_z = entry_z15 self.exit_z = exit_z16 self.stop_z = stop_z17 self.position = None # 'long_spread' or 'short_spread'18 self.hedge_ratio = None1920 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 lost2526 x = sm.add_constant(prices2)27 model = sm.OLS(prices1, x).fit()28 self.hedge_ratio = model.params.iloc[1]29 return True3031 def compute_z_score(self, prices1, prices2):32 """Compute current z-score of the spread."""33 spread = prices1 - self.hedge_ratio * prices234 recent = spread.iloc[-self.lookback:]35 z = (spread.iloc[-1] - recent.mean()) / recent.std()36 return z3738 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)4243 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'4849 z = self.compute_z_score(p1, p2)5051 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'5859 elif self.position == 'long_spread':60 if z > -self.exit_z or z < -self.stop_z:61 await self._flatten()62 return 'EXIT'6364 elif self.position == 'short_spread':65 if z < self.exit_z or z > self.stop_z:66 await self._flatten()67 return 'EXIT'6869 return 'HOLD'7071 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
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?
Put this lesson to work
Free on Thrive, no account needed.