BLOG

Behind the numbers.

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

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 Track S&P 500 Additions and Removals Over Time in 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

Are KO and PEP Cointegrated? Pairs Trading Signal Construction in Python

What's the question?

Pairs trading depends on a specific statistical property: cointegration. Two stock prices are cointegrated if a linear combination of them is stationary — meaning the spread between them fluctuates around a fixed mean rather than drifting permanently. This is stronger than correlation. Two stocks can be highly correlated in returns yet not cointegrated in prices, because correlation measures co-movement within a period while cointegration measures a long-run equilibrium that the prices are pulled back toward.

The Engle-Granger two-step procedure provides a direct test. First, regress one price series on the other using ordinary least squares to estimate the hedge ratio — the number of shares of stock A that offsets one share of stock B. Second, test whether the residuals (the spread) contain a unit root using the Augmented Dickey-Fuller test. If the spread is stationary (p-value below 0.05), the pair is cointegrated and a mean-reversion signal has a statistical foundation. If the spread has a unit root, there is no equilibrium to revert to, and trading the spread is no different from trading a random walk.

Three classic same-sector pairs serve as test cases: Coca-Cola and PepsiCo (beverages), Chevron and ExxonMobil (oil majors), and Home Depot and Lowe’s (home improvement). The common assumption is that competitors in the same industry should maintain a stable price relationship. The data may disagree.

The approach

  1. Pull 5 years of daily split-adjusted closing prices for all six stocks
  2. For each pair, run OLS regression to estimate the hedge ratio (beta coefficient)
  3. Compute the spread as the residual: stock B minus hedge ratio times stock A
  4. Run the ADF test on each spread to determine cointegration status
  5. Compute the z-score of each spread to generate a trading signal — values above +2 or below −2 indicate the spread has moved approximately two standard deviations from its mean

Code

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

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

tickers = ["KO", "PEP", "CVX", "XOM", "HD", "LOW"]
df = xfl.prices(tickers, period="5y", fields=["adj_close"])

pairs = [("KO", "PEP"), ("CVX", "XOM"), ("HD", "LOW")]

for t1, t2 in pairs:
    s1 = df[df["ticker"] == t1].sort_values("date").set_index("date")["adj_close"]
    s2 = df[df["ticker"] == t2].sort_values("date").set_index("date")["adj_close"]
    aligned = pd.concat([s1, s2], axis=1, keys=[t1, t2]).dropna()

    X = add_constant(aligned[t1].values)
    model = OLS(aligned[t2].values, X).fit()
    hedge_ratio = model.params[1]

    spread = aligned[t2].values - hedge_ratio * aligned[t1].values
    adf_stat, p_value = adfuller(spread, autolag="AIC")[:2]
    tag = "COINTEGRATED" if p_value < 0.05 else "NOT COINTEGRATED"

    z = (spread - spread.mean()) / spread.std()
    print(f"{t1}/{t2}: hedge={hedge_ratio:.4f}  ADF={adf_stat:.4f}  "
          f"p={p_value:.4f} ({tag})  z_now={z[-1]:.2f}")

Full script with formatting and visualisation: pairs-cointegration-signal-python.py

Output

Z-score time series for three pairs: KO/PEP and HD/LOW oscillate around zero with touches at the plus/minus 2 bands, while CVX/XOM drifts persistently upward
Pair        Hedge Ratio   ADF Stat   p-value Status                Z (now)
---------------------------------------------------------------------------
KO/PEP          -0.8954    -3.4219    0.0102 COINTEGRATED            -0.42
CVX/XOM          0.8880    -1.5055    0.5308 NOT COINTEGRATED         1.24
HD/LOW           0.5531    -3.0084    0.0341 COINTEGRATED            -0.51

What this tells us

Two of the three pairs are cointegrated at the 5% significance level. KO/PEP (p = 0.010) and HD/LOW (p = 0.034) both reject the null hypothesis of a unit root in the spread. CVX/XOM (p = 0.531) does not.

The KO/PEP result contains a counterintuitive detail: the hedge ratio is negative (−0.8954). Over the past five years, Coca-Cola has risen approximately 54% while PepsiCo has declined slightly. Their price levels have moved in opposite directions despite being in the same industry. The negative hedge ratio reflects this divergence — the cointegration relationship is between PEP and the inverse of KO. The spread is still stationary, meaning the divergence oscillates rather than growing without bound. The chart confirms this: the KO/PEP z-score touches the ±2 bands and reverts, generating clear entry signals.

CVX/XOM tells a different story. Despite being the two largest U.S. oil majors, their spread has drifted persistently since 2022 — visible as the steady upward movement in the middle panel of the chart. The z-score sits at +1.24 and has been above zero for most of the last two years. The ADF statistic of −1.51 is far from the critical value needed for rejection. There is no statistical basis for mean-reversion trading on this pair at the five-year horizon.

HD/LOW is cointegrated with a hedge ratio of 0.5531, meaning roughly 0.55 shares of Home Depot for each share of Lowe’s. The z-score at −0.51 places the spread near fair value, offering no immediate entry signal, but the cointegration relationship validates the pair as a candidate for future signals.

So what?

The Engle-Granger test converts a subjective judgment — “these two stocks should trade together” — into a statistical claim with a measurable confidence level. Of three pairs that most practitioners would assume are cointegrated, one fails the test entirely. The CVX/XOM result is a direct warning against assuming that same-sector membership implies a stable spread.

For the two cointegrated pairs, the z-score provides an actionable signal. A z-score above +2 suggests the spread is extended and may contract (short the spread). A z-score below −2 suggests the opposite (long the spread). The current readings of −0.42 (KO/PEP) and −0.51 (HD/LOW) indicate neither pair is at an extreme, so there is no immediate trade — which is itself useful information.

One important limitation: the hedge ratio estimated over 5 years is not guaranteed to remain stable. Rolling the estimation window (for example, re-estimating every quarter using the trailing 2 years) and confirming that the cointegration relationship persists before entering each trade adds robustness. The test is not a one-time event. It is a recurring diagnostic that should be re-run before each entry and monitored during each position.

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

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