BLOG

Behind the numbers.

Code examples, market analysis, and data quality deep-dives.

Does Skipping the Most Recent Month Improve Momentum? S&P 500 Decile Sorts in Python
Does Cointegration Survive Out of Sample? Pairs Trading Validation in Python
Which Dividends Are Not Covered by Cash? Free-Cash-Flow Coverage Screening in Python
GICS vs SIC vs NAICS: Which Industry Classification to Use
How Many Stocks Does It Take to Diversify? Random Portfolio Simulation in Python
How Many Days of Data Does a Volatility Estimate Need? Range-Based Estimators in Python
How Much of S&P 500 Cash Flow Is Stock Compensation? Cross-Sectional Analysis in Python
What Is a 13F Filing? Institutional Holdings Explained
Does Revenue Growth Explain Profit Growth? Cross-Sectional Decomposition in Python
How Much of the Nasdaq 100 Is Already in the S&P 500? Index Overlap Analysis in Python
How Often Does a 99% Value-at-Risk Limit Actually Break? VaR Backtesting in Python
Real-Time vs End-of-Day Market Data: Which Do You Need?
How Concentrated Are S&P 500 Earnings? Point-in-Time Index Analysis in Python
Does Volatility Scale With the Square Root of Time? Variance Ratio Test in Python
Does Goodwill Distort the Price-to-Book Screen? Goodwill-Adjusted Valuation in Python
How Are Shares Outstanding Reported (and Why They Disagree)
Do Low-Volatility Stocks Deliver Better Risk-Adjusted Returns? S&P 500 Quintile Sorts in Python
Does Trend Following Beat Buy and Hold? Time-Series Momentum in Python
Has the Stock-Bond Correlation Flipped? 60/40 Portfolio Risk in Python
What API to Use for a Stock Screener
Which Assets Hedge Inflation Shocks? Macro Factor Betas in Python
Does Covariance Shrinkage Beat the Sample Covariance? Minimum-Variance Portfolios in Python
Do Faster Inventory Turns Mean Thinner Margins? Gross Margin Return on Inventory in Python
SEC EDGAR API vs Fundamentals API: Which to Use
Does Fast Earnings Growth Persist? Rank Correlation Analysis in Python
Split Adjustment Explained: Adjusted Close vs Close
Which Trading Day of the Month Pays Best? Turn-of-the-Month Analysis in Python
Can You Use Yahoo Finance Data Commercially?
How Many Independent Bets Does a Nine-Sector Portfolio Give You? Eigenvalue Analysis in Python
Which Volatility Forecast Wins One Month Ahead? HAR vs EWMA in Python
How Concentrated Are Institutional Equity Portfolios? Form 13F Concentration Analysis in Python
Do Stocks Earn Their Returns Overnight or Intraday? Return Decomposition in Python
When Do Corporate Insiders Actually Trade? Form 4 Timing Analysis in Python
Data Requirements for Backtesting a Trading Strategy
What Is Survivorship Bias in Backtesting?
Do High Dividend Yields Come From Bigger Payouts or Falling Prices? Yield Decomposition in Python
Do Stocks Fall Harder Than They Rise? Downside Beta vs Upside Beta in Python
Does Volatility Targeting Improve Sharpe Ratios? Seven-Asset Backtest in Python
Free Stock Market Data APIs: What You Actually Get
How to Give an LLM Financial Data With an MCP Server
Does Post-Earnings Announcement Drift Survive Real Filing Dates? PEAD Event Study in Python
Do Insider Buying Clusters Predict Returns? Signal Testing in Python
Does the S&P 500 Index Effect Still Exist? Event Study in Python
Are Companies Leaving the S&P 500 Faster Than They Used To? Index Survival Analysis in Python
Does Gross Profitability Predict Stock Returns? Quintile Factor Test in Python
What Growth Rate Is the Market Pricing In? Reverse DCF in Python
Does a Strong Balance Sheet Cushion Drawdowns? Leverage and Downside Risk in Python
Does Ticker Recycling Corrupt a Mean-Reversion Backtest? Entity-Resolved Z-Scores in Python
How Much of a Growth Screen's Backtested Edge Is Survivorship Bias? Point-in-Time Index Testing in Python
Why Do Leveraged ETFs Decay? Measuring Volatility Drag in Python
Are Consumer Staples Margins Shrinking Under Inflation? Gross Margin Trend Analysis in Python
Do Weak Jobs Reports Predict Market Drawdowns? NFP Surprise Event Study in Python
Is the Rotation From Tech to Industrials Backed by Earnings? Relative EPS Growth Analysis in Python
Is the Semiconductor Rally Broadening Beyond NVIDIA? Return Dispersion Analysis in Python
Which Stocks Benefit Most When Oil Prices Fall? Oil Beta Screening in Python
Do Bond Returns Predict Stock Returns? Granger Causality Test in Python
Which Stocks Actually Drive Portfolio Returns? Shapley Value Attribution in Python
Does "Sell in May" Still Work? Calendar Anomaly Backtest in Python
How to Build Complete Price History Through Ticker Changes? Entity Resolution in Python
Are KO and PEP Cointegrated? Pairs Trading Signal Construction in Python
Which Commodities Have the Strongest Momentum? Rotation Backtest in Python
Which Commodity ETFs Have the Worst Tail Risk? Expected Shortfall in Python
Are Gold Miners Leveraged Gold Bets? Rolling Beta Analysis in Python
Does the Base-Metals-to-Gold Ratio Lead Cyclical Stocks? Signal Test in Python
Can Risk Parity Tame Commodity Volatility? Portfolio Optimization in Python
Are Power Stocks Becoming an AI Infrastructure Trade? Momentum Screening in Python
Which AI Chip Stocks Have Margin Momentum? Profitability Trend Analysis in Python
Which AI Stocks Are Cheapest Relative to Growth? Growth-Adjusted Valuation in Python
Does AI Stock Leadership Persist? Momentum Backtest in Python
Which AI Stocks Have the Cleanest Balance Sheets? Net Cash Screening in Python
Can Risk Parity Reduce Mega-Cap Drawdowns? Portfolio Optimization in Python
Which Growth Stocks Are Self-Funding? Cash-Flow Quality Screening in Python
Which Sectors Struggle When the Dollar Rallies? Sector Rotation Analysis in Python
Do Cheap Stocks Hold Up When Bonds Sell Off? Valuation Rotation in Python
Does the Nasdaq 100 Have Better Growth Quality Than the Dow? Index Constituent Analysis in Python
Do Healthcare Cash-Flow Margins Predict Returns? Signal Evaluation in Python
Which Dividend Stocks Survive a Cash-Flow Stress Test? Dividend Screening in Python
Does Heavy Insider Selling Predict Weak Returns? Insider Flow Test in Python
Can Quality Screens Reduce Small-Cap Balance-Sheet Risk? Russell 2000 Test in Python
Which Retailers Have Positive Operating Leverage? Margin Screening in Python
Is MSTR a Leveraged Bitcoin Proxy? Rolling Beta Analysis in Python
Is Micron's Memory Cycle Recovering? Inventory and Margin Forecasting in Python
Which Sectors Work When Bonds Rally? Rate-Sensitive Rotation in Python
Do One-Month Price Extremes Reverse? Signal Evaluation in Python
Do Low-Volatility S&P 500 Stocks Reduce Drawdowns? Factor Test in Python
Is AI Capex Paying Back Fast Enough? Revenue Hurdle Forecasting in Python
Could Shorter AI Asset Lives Hit Earnings? Depreciation Stress Test in Python
How Much AI Capex Risk Can a Portfolio Remove? Constrained Optimization in Python
Is the AI Capex Trade Crowded? Rolling Volatility and Sector Rotation in Python
Did the AI Boom Come From Existing S&P 500 Members? Point-in-Time Momentum Test in Python
Is AI Revenue Circular? Customer-Vendor Capex Loop Analysis in Python
Is the AI Trade Connected to Private Credit? Rolling Correlation Network in Python
Is Apollo More Balance-Sheet Sensitive Than Peers? Leverage Screen in Python
Are AI Earnings Supported by Cash Flow? Accrual and Capex Screen in Python
Can Defensive Stocks Hedge AI Drawdowns? Basket Regime Test in Python
How Fast Does the Market Price In Fed Decisions? FOMC Event Study in Python
How Much Are Options Sellers Overpaid? The Variance Risk Premium in Python
Which Companies Have the Worst Earnings Quality? Sloan Accrual Screen with Geographic Revenue Data in Python
Does the Oil-to-Gold Ratio Signal Recessions? XLE/GLD Backtest in Python
Is AI Spending Crowding Out Free Cash Flow? Capex Sustainability Across the Mag 7 in Python
Does a Long Energy / Short Bonds Portfolio Capture Inflation Surprises? Factor Construction in Python
Can a Hidden Markov Model Detect Oil Market Regimes? HMM Analysis in Python
Do Grain Prices Predict Food Inflation? Granger Causality Test in Python
Does the Corporate Credit Spread Predict Stock Market Crashes? BAA-AAA Spread Analysis in Python
Do Oil Stocks Hedge Inflation? Rolling Beta Analysis in Python
Which Stocks Are Most Rate-Sensitive? Equity Duration via Bond Beta in Python
Which Companies Have the Highest Accrual Ratios? Earnings Quality Screening in Python
Is Alpha Persistent or Decaying? Rolling Sharpe Ratio Analysis in Python
Are Markets Trending or Mean-Reverting? Hurst Exponent Analysis in Python
Is Consumer Discretionary vs Staples a Leading Indicator? XLY/XLP Ratio Analysis in Python
Does Heavy Capex Predict Future Stock Returns? Capital Expenditure Analysis in Python
How to Estimate Cost of Equity Using CAPM in Python
Is Volatility Predictable? Testing for Volatility Clustering in Python
Which Industrials Are Overleveraged? Net Debt to EBITDA Screening in Python
GM Before and After Bankruptcy: Why Entity Resolution Matters for Financial Data
What Is Adjusted Beta? Merrill Lynch Beta Shrinkage in Python
How Good Is a Stock Pick? Information Ratio and Tracking Error in Python
Do Stock Returns Follow a Normal Distribution? Testing for Fat Tails in Python
Which Large Caps Have the Highest Free Cash Flow Yield? FCF Screening in Python
Which Sectors Won Over 5 Years? Sector Rotation Analysis in Python
How to Forecast Stock Volatility with GARCH Models in Python
Are Stock Prices Mean-Reverting? Augmented Dickey-Fuller Test in Python
How to Calculate CAPM Alpha and Beta with Regression in Python
How to Compare Sector Sharpe Ratios and Sortino Ratios in Python
DELL: Why Stitching Historical Price Data Together Is Wrong
How to Analyze Drawdown and Recovery for Bank Stocks in Python
How to Screen SaaS Stocks by Revenue Growth and Cash Flow in Python
How to Screen REITs by Dividend Yield and Valuation in Python
How Correlated Are the Magnificent 7? Intra-Group Correlation in Python
AAPL vs XOM: Do Individual Stocks Have Seasonal Patterns?
How to Rank Large-Cap Stocks by Momentum in Python
How to Build a Multi-Endpoint Financial Dashboard in Python
How to Compare Volatility Across Energy Stocks in Python
How to Screen Healthcare Stocks by Valuation in Python
How to Build a Sector Correlation Matrix for Portfolio Diversification in Python
How to Find Oversold and Overbought Stocks Using Z-Scores in Python
How to Measure Earnings Quality: Cash Flow vs Net Income in Python
How to Build a Multi-Factor Stock Screen in Python (Value + Momentum + Quality)
How to Build a Simple DCF Model for Any Stock in Python
How to Screen Tech Stocks by Revenue Growth in Python
How to Screen Stocks by Balance Sheet Health in Python
Is "Sell in May" Real? SPY Monthly Seasonality Over 10 Years
How to Compare Sector Performance YTD Using Python
How to Screen Dividend Stocks by Yield and Quality in Python
How to Calculate Max Drawdown and Recovery Time for Any Stock in Python
How to Compare Profitability Across Mega-Cap Tech Stocks in Python
Why Ticker Symbols Are Unreliable: The Recycling Problem Every Quant Should Know
How to Calculate and Compare Stock Volatility in Python
How to Screen Blue-Chip Stocks by P/E Ratio in Python
How to Track Companies Through Ticker Changes, Bankruptcies, and Renames in Python
S&P 500 Turnover: How Much the Index Has Changed Since 2010
How to Calculate Stock Beta and Correlation in Python
← All articles

Does Cointegration Survive Out of Sample? Pairs Trading Validation in Python

What’s the question?

Pairs trading rests on cointegration. Two share prices can each wander with no fixed level to return to, and yet one combination of them stays anchored: the gap opens, closes, opens again. Engle and Granger set out the standard test in 1987. Regress one log price on the other and test the residual for a unit root; a p-value below 0.05 says the spread is stationary, which is the licence a mean-reversion rule needs.

The test looks backwards and the trade happens afterwards. Nothing promises that a relationship measured over three years is still there in the fourth. Worse, at the 5% level a test rejects a true unit root one time in twenty by construction, so a thousand-pair screen produces about fifty passes from noise alone.

The question is therefore not whether same-industry pairs pass the test. It is whether passing says anything about the three years that follow.

The approach

  1. Take S&P 500 members as at 5 August 2020, keyed on entity identifiers rather than symbols, so companies that later left the index stay in the sample.
  2. Map each member to its GICS industry and keep the ten industries with the most members.
  3. Pull daily split-adjusted closes from 5 August 2020 to 4 August 2026. Names that traded under more than one symbol in the window, and names without a complete daily history for it, leave the panel: 148 companies and 1,506 sessions remain.
  4. Split the window in half: 755 formation sessions ending 4 August 2023, 751 holdout sessions after it. Test all 1,048 within-industry pairs once in each window, estimated independently, with the regression direction fixed alphabetically since Engle-Granger is not symmetric.
  5. Freeze the formation hedge ratio, spread mean and spread standard deviation, then run the textbook entry rule forward: open when the z-score of the spread reaches plus or minus 2, close when it returns to zero, abandon after 60 sessions.

One detail decides whether the p-values mean anything. The series tested is a fitted residual, not an observed one, so the ordinary Dickey-Fuller distribution is too generous and the Engle-Granger critical values from MacKinnon are the correct reference; statsmodels.tsa.stattools.coint applies them. Marathon Petroleum against ExxonMobil gives the same statistic either way, −3.705, and p = 0.018 against the correct table where the ordinary one reads 0.0002.

Code

import itertools
import numpy as np
import pandas as pd
import xfinlink as xfl
from statsmodels.regression.linear_model import OLS
from statsmodels.tools import add_constant
from statsmodels.tsa.stattools import coint

xfl.set_api_key("YOUR_API_KEY")  # free at https://xfinlink.com/signup

FORM_END = "2023-08-04"

members = xfl.index("sp500", as_of="2020-08-05").dropna(subset=["entity_id"])
ids = sorted(members["entity_id"].astype(int))
px = pd.concat([xfl.prices(entity_id=ids[i:i + 5], start="2020-08-05", end="2026-08-04",
                           fields=["adj_close"], max_rows=200000)
                for i in range(0, len(ids), 5)], ignore_index=True)
# uni carries the GICS industry of each entity from xfl.resolve(); sym maps id to symbol

wide = px.pivot_table(index="date", columns="entity_id", values="adj_close").sort_index()
form, hold = wide.loc[:FORM_END], wide.loc[wide.index > FORM_END]
keep = [i for i in wide.columns
        if form[i].notna().all() and hold[i].notna().all() and wide[i].min() > 0]
lf, lh = np.log(form[keep]), np.log(hold[keep])

for industry, grp in uni.groupby("industry"):
    for a, b in itertools.combinations(sorted(grp["entity_id"], key=lambda e: sym[e]), 2):
        p_form = coint(lf[b].values, lf[a].values, trend="c", autolag="AIC")[1]
        p_hold = coint(lh[b].values, lh[a].values, trend="c", autolag="AIC")[1]

        fit = OLS(lf[b].values, add_constant(lf[a].values)).fit()
        z = (lh[b].values - fit.params[0] - fit.params[1] * lh[a].values
             - fit.resid.mean()) / fit.resid.std(ddof=1)

        print(f"{sym[a]}/{sym[b]}: formation p={p_form:.4f}  holdout p={p_hold:.4f}  "
              f"holdout entries={(np.abs(z) >= 2).sum()}")

Full script with formatting and visualisation: cointegration-out-of-sample-pairs-python.py

Output

Scatter of formation-window against holdout-window cointegration p-values for 1,048 same-industry pairs, beside a bar chart comparing how often a divergence closed within 60 sessions
Panel: 148 names, 1048 same-industry pairs, 755 formation sessions, 751 holdout sessions
Formation cointegrated at 5%: 49 (4.68%), chance alone predicts 52.4
Holdout cointegrated at 5%:   62 (5.92%)
Repeat rate, selected pairs:  1/49 (2.0%)
Repeat rate, rejected pairs:  61/999 (6.1%)
At the 1% level: 7 selected, 0 repeat

Holdout entry rule: enter at |z| >= 2, exit at z = 0 or after 60 sessions
group          trades  converged  median days  mean sigma  mean log ret
selected          185      18.9%           39      -0.119        -0.52%
rejected         2716       6.7%           38       0.010         0.13%
  converged trades: mean +2.34 sigma
  timed out trades: mean -0.19 sigma

What this tells us

The formation screen found nothing that chance would not have produced. 49 of 1,048 pairs cleared the 5% threshold against 52.4 expected when no pair is cointegrated at all, and tightening to 1% leaves 7 against 10.5 expected. At this sample size the count of cointegrated peers in a sector screen restates the significance level.

Repetition is where the case collapses. One of the 49 selected pairs passed again in the holdout, a repeat rate of 2.0%, against 6.1% for the 999 pairs the screen rejected. Selection did not raise the odds of a stationary spread over the next three years, and a Fisher exact test returns p = 0.36, so even that reversal is noise. None of the 7 pairs selected at the 1% level repeated.

The entry rule tells a subtler story. Divergences on the selected pairs came back to fair value within 60 sessions 18.9% of the time against 6.7% for the rejected pairs, so the formation test carried real information about short-horizon convergence even where it carried none about cointegration. The outcome does not follow. A converged trade returns +2.34 standard deviations of spread and a stalled one loses 0.19, and the stalled trades on selected pairs run further than that: the selected book averages −0.119 standard deviations per entry, or −0.52% in log terms, against +0.010 for the rejected book. A few episodes dominate, with the MPC/XOM spread alone giving back 10.3 standard deviations. Trim outcomes at plus or minus 3 and both books sit at zero.

So what?

Count the tests before trusting any of them. A screen of 1,048 pairs at the 5% level turns noise into 52 candidates, and the correction costs one line: divide the threshold by the number of tests. At 0.05/1048 the strongest p-value in this panel is BDX against STE at 0.00042, nine times too large to pass. Not one same-industry pair clears a multiple-testing correction over these three years.

The stronger discipline is a holdout: fit the hedge ratio on one window, then require the relationship to hold on a later window that took no part in the fitting before any capital moves. Pairs that pass twice are rare, and that scarcity is the signal about how many deserve a position.

For a book already running, the asymmetry is what to size against. Winners come home in about 39 sessions and pay roughly two and a third standard deviations; losers keep going. An entry band without exit discipline is short that left tail, and a cointegration test at entry does nothing to shorten it.

Built with xfinlink — free financial data API for Python. pip install -U xfinlink

Built with xfinlink — free financial data API for Python. pip install -U xfinlink
← All articles