$npx -y skills add agiprolabs/claude-trading-skills --skill cointegration-analysisCointegration testing for pairs trading using Engle-Granger, Johansen, and rolling stability analysis
| 1 | # Cointegration Analysis |
| 2 | |
| 3 | Cointegration testing identifies pairs of assets that share a long-run equilibrium |
| 4 | relationship, enabling statistical arbitrage and pairs trading strategies. |
| 5 | |
| 6 | ## What Is Cointegration? |
| 7 | |
| 8 | Two price series are **cointegrated** when they are individually non-stationary |
| 9 | (random walks) but a linear combination of them is stationary (mean-reverting). |
| 10 | Intuitively, the prices may wander apart temporarily but are pulled back to an |
| 11 | equilibrium spread over time. |
| 12 | |
| 13 | ### Cointegration vs Correlation |
| 14 | |
| 15 | | Property | Correlation | Cointegration | |
| 16 | |---|---|---| |
| 17 | | Measures | Short-term co-movement | Long-run equilibrium | |
| 18 | | Stationarity | Requires stationary returns | Works with non-stationary prices | |
| 19 | | Time horizon | Can change rapidly | Stable over months/years | |
| 20 | | Trading use | Momentum/trend signals | Mean-reversion pairs trades | |
| 21 | | Failure mode | Breaks in regime changes | Breaks on structural shifts | |
| 22 | |
| 23 | Two assets can be highly correlated but not cointegrated (e.g., two unrelated |
| 24 | uptrends). Conversely, cointegrated assets may have low short-term correlation |
| 25 | during temporary divergences — which is exactly when pairs trades are entered. |
| 26 | |
| 27 | ### Why It Matters |
| 28 | |
| 29 | - **Pairs trading**: Long the underperformer, short the outperformer, profit on convergence |
| 30 | - **Statistical arbitrage**: Systematic mean-reversion on spread z-scores |
| 31 | - **Spread trading**: Trade the spread directly as a synthetic instrument |
| 32 | - **Risk hedging**: Cointegrated hedge ratios minimize tracking error over time |
| 33 | |
| 34 | ## Methods |
| 35 | |
| 36 | ### 1. Engle-Granger Two-Step |
| 37 | |
| 38 | The most common approach for two series. |
| 39 | |
| 40 | **Step 1** — Regress Y on X using OLS: |
| 41 | |
| 42 | ``` |
| 43 | Y_t = α + β * X_t + ε_t |
| 44 | ``` |
| 45 | |
| 46 | **Step 2** — Test the residuals ε_t for stationarity using the ADF test. |
| 47 | |
| 48 | - If residuals are stationary (p < 0.05) → Y and X are cointegrated |
| 49 | - β is the **hedge ratio** for the pairs trade |
| 50 | - α is the long-run mean of the spread |
| 51 | |
| 52 | **Important**: Engle-Granger critical values differ from standard ADF critical |
| 53 | values. For n=2 series: 1% = -3.90, 5% = -3.34, 10% = -3.04. |
| 54 | |
| 55 | **Asymmetry warning**: Testing Y~X can give a different result than X~Y. Always |
| 56 | test both directions and use the stronger result. |
| 57 | |
| 58 | ```python |
| 59 | from scipy import stats |
| 60 | import numpy as np |
| 61 | from statsmodels.tsa.stattools import adfuller |
| 62 | |
| 63 | # Step 1: OLS regression |
| 64 | slope, intercept, _, _, _ = stats.linregress(x_prices, y_prices) |
| 65 | hedge_ratio = slope |
| 66 | |
| 67 | # Step 2: Test residuals |
| 68 | residuals = y_prices - hedge_ratio * x_prices - intercept |
| 69 | adf_stat, p_value, _, _, crit_values, _ = adfuller(residuals, maxlag=None, autolag="AIC") |
| 70 | |
| 71 | cointegrated = p_value < 0.05 |
| 72 | ``` |
| 73 | |
| 74 | ### 2. Johansen Test |
| 75 | |
| 76 | Tests multiple series simultaneously and returns the number of cointegrating |
| 77 | relationships. More powerful than Engle-Granger for >2 series. |
| 78 | |
| 79 | - Based on a VAR model: ΔY_t = Π·Y_{t-1} + Σ Γ_i·ΔY_{t-i} + ε_t |
| 80 | - Tests the rank of the Π matrix |
| 81 | - Uses trace test and maximum eigenvalue test |
| 82 | - Returns: number of cointegrating vectors and the vectors themselves |
| 83 | |
| 84 | ```python |
| 85 | from statsmodels.tsa.vector_ar.vecm import coint_johansen |
| 86 | |
| 87 | # data: T×N array of price series |
| 88 | result = coint_johansen(data, det_order=0, k_ar_diff=1) |
| 89 | |
| 90 | # Trace statistic vs critical values (90%, 95%, 99%) |
| 91 | trace_stats = result.lr1 # Trace statistics |
| 92 | trace_crit = result.cvt # Critical values |
| 93 | max_eigen_stats = result.lr2 # Max eigenvalue statistics |
| 94 | max_eigen_crit = result.cvm # Critical values |
| 95 | |
| 96 | # Cointegrating vectors |
| 97 | coint_vectors = result.evec |
| 98 | ``` |
| 99 | |
| 100 | ### 3. Phillips-Ouliaris |
| 101 | |
| 102 | Similar to Engle-Granger but uses Phillips-Perron style test statistics |
| 103 | instead of ADF. More robust to heteroskedasticity and serial correlation in |
| 104 | the residuals. Available via `statsmodels.tsa.stattools.coint`. |
| 105 | |
| 106 | ```python |
| 107 | from statsmodels.tsa.stattools import coint |
| 108 | |
| 109 | # Returns: test statistic, p-value, critical values |
| 110 | t_stat, p_value, crit_values = coint(y_prices, x_prices) |
| 111 | cointegrated = p_value < 0.05 |
| 112 | ``` |
| 113 | |
| 114 | ## Practical Workflow |
| 115 | |
| 116 | ### Step 1: Screen Pairs by Correlation |
| 117 | |
| 118 | Pre-filter using Pearson correlation > 0.7 to reduce the number of |
| 119 | cointegration tests (which are more expensive). |
| 120 | |
| 121 | ### Step 2: Test Cointegration |
| 122 | |
| 123 | Run Engle-Granger in both directions. Use p < 0.05 threshold. |
| 124 | |
| 125 | ### Step 3: Estimate Hedge Ratio |
| 126 | |
| 127 | Use OLS for simplicity. For production, consider Total Least Squares or |
| 128 | Dynamic OLS (see `references/methodology.md`). |
| 129 | |
| 130 | ### Step 4: Compute Spread |
| 131 | |
| 132 | ```python |
| 133 | spread = y_prices - hedge_ratio * x_prices - intercept |
| 134 | z_score = (spread - spread.mean()) / spread.std() |
| 135 | ``` |
| 136 | |
| 137 | ### Step 5: Test Spread for Mean Reversion |
| 138 | |
| 139 | - **ADF test**: p < 0.05 confirms stationarity |
| 140 | - **Hurst exponent**: H < 0.5 indicates mean reversion (H ≈ 0.5 = random walk) |
| 141 | - **Half-life**: λ from AR(1) on spread; half-life = -ln(2)/ln(λ) |
| 142 | - Viable pairs: half-life between 5 and 60 days |
| 143 | |
| 144 | ### Step 6: Trade the Spread |
| 145 | |
| 146 | If the spread is mean-reverting, it is a viable pairs trade can |