Only until regimes shift and volatility bites
Published: 2025-11-08
URL: https://pyquantnews.substack.com/p/does-correlation-survive-contact
Subscribers, look for the code in your Private chat. Looking for the code notebooks? Consider a free subscription. Correlation feels comforting, but it rarely survives contact with live markets. Most beginners assume two stocks that line up on a chart will move together.
The truth is correlation shifts as regimes and volatility change. What holds up in a backtest often breaks when capital and slippage show up. That false confidence eats weeks on backtests that look sharp but wonât fill or hold up live.
The trap I learned this when a âperfectâ solar pair unraveled after earnings drift broke their correlation. The cointegration spread held up, while the naive correlation trade kept bleeding. You probably feel this when you keep tuning thresholds, adding tickers, or switching libraries instead of tightening your process.
The pain comes from confusing correlation with a stable relationship. Cointegration focuses on a spread that behaves consistently, then you standardize it and trade the reversion with clear exits. Pros avoid the noise by screening for cointegration, building a hedge-ratio spread, and acting only when the spread looks statistically stretched. I run a weekly scan on theme-linked equities, keep a short watchlist of stable spreads, and retest each month before putting risk on.
In todayâs post, youâll find cointegrated pairs in renewable energy stocks and frame a simple, testable trading workflow. Letâs go. What it is Cointegration is when a linear combination of two drifting price series stays stable over time, which makes mean reversion tradable.
In the late 1980s, Morgan Stanleyâs stat arb group pushed systematic equity pairs into production. Engle and Granger formalized cointegration testing in econometrics, and practitioners adapted it to equity spreads that behave more like y minus beta times x. Over time, desks moved from raw correlation toward robust spread modeling because it survives more market regimes.
How professionals use it Today, professionals use cointegration to isolate relative value, reduce market beta, and structure entries around standardized spread extremes. They start with a liquid, theme-linked universe and run EngleâGranger tests on rolling windows using adjusted log prices. They estimate the hedge ratio with a simple regression, construct the spread as S1 minus beta times S2, and compute a rolling z-score from past data only to avoid leakage. They trade when the z-score pushes beyond a chosen threshold and exit near zero, while tracking costs, borrow, time stops, and spread breaks with periodic retests.
This matters for beginners because it gives you a concrete workflow that replaces vibes with measured rules. You get a pipeline you can run weekly that selects pairs on evidence and sets entries with clear thresholds. You also avoid common traps like overfitting, lookahead bias in rolling stats, and false positives from testing too many pairs without retesting stability. Letâs see how it works with Python. Looking for the code notebooks? Subscribe. Library installation Install all required packages so the notebook runs end to end without dependency surprises.
We use pip to pull market data, statistical tests, and plotting tools in one step. Installing dependencies up front makes notebooks reproducible and reduces time lost to environment drift. statsmodels provides the EngleâGranger cointegration test we rely on, yfinance supplies prices, and matplotlib/seaborn handle visualization.
With these in place, we can focus on the cointegration workflow instead of tooling issues. Imports and setup We import matplotlib and seaborn for plotting, numpy for numerical arrays, and pandas for time series data handling. We use yfinance to download historical prices and statsmodels.tsa.stattools.coint to run the EngleâGranger cointegration test.
These are standard, well-supported libraries for quant research, which keeps our code concise and readable. The coint function gives us a direct statistical test for a stationary spread, which is the point of this workflow. Keeping imports minimal and purpose-driven helps beginners see which tools matter at each step. Download market data for theme universe Pull a theme-linked renewable energy universe and a training window of daily closes from yfinance, then align dates by dropping missing values.
Working within a coherent theme (renewables) raises the odds of stable relationships without relying on raw correlation. For production, prefer adjusted prices and log transforms to handle splits and dividends consistently; the postâs workflow assumes that. We keep the window short here for a quick demo, but youâd retest across rolling windows or monthly updates to avoid stale conclusions. Run cointegration scan and select pair Run EngleâGranger cointegration tests across all unique pairs, store scores and p-values, and collect pairs that pass a loose 10% level for initial screening.
A permissive threshold helps us find candidates, not trades. Because multiple testing inflates false positives, we treat this as a shortlist to retest on new data rather than a signal. The bigger lesson is we screen for a stationary spread instead of trusting correlation that often shifts with regime. Pick the most significant pair by the lowest p-value, extract the two series, and print the result for reference. Selecting the minimum p-value pair gives us the strongest statistical candidate in-sample, which we can monitor going forward.
In a robust workflow weâd estimate the hedge ratio via a regression (S1 ~ beta*S2) and validate on a rolling or out-of-sample window. Treat this as a starting point for a watchlist you re-check periodically. Build spread and visualize signals Build a simple 1:1 spread and compute a 21-day rolling z-score to standardize deviations the way many pairs traders frame entries and exits. Standardizing with a rolling window uses only past data (min_periods prevents lookahead), and 21 days approximates a trading month.
A proper hedge ratio often improves stationarity, but this 1:1 view shows the mechanics cleanly for learning. If you later switch to adjusted log prices, youâll usually get a cleaner, more stable spread. Plot a p-value heatmap that hides the lower triangle and any non-significant pairs so we can quickly see where cointegration evidence clusters.
The result is something that looks like this. Heatmaps help us triage a universe fast and keep a concise watchlist instead of overfitting everything that âlooksâ aligned. Remember this is an evidence map, not a trading signal; we still retest stability over time and account for costs and borrow. Keeping the focus on cointegration avoids the correlation trap the post warns about. Visualize the spread and its z-score so we can judge whether extremes align with plausible entries and mean reversion toward zero.
The result looks something like this: Lines at ±1 are illustrative thresholds; your entries and exits should be tuned and validated out-of-sample, with time stops and cost assumptions. The suptitle is hard-coded and may not match the selected pair, but the plot still demonstrates how standardized spread extremes set clear actions.
This closes the loop from screening to a testable, rules-based reversion setup. Your next steps You can now screen a sector for cointegrated pairs, fit the hedge by OLS, standardize residuals with a rolling zâscore, and run a clean, costâaware meanâreversion backtest without lookahead.
It reduces false positives, protects against regime drift, and directs capital into repeatable, marketâneutral trades.