Build a pairs trading strategy in Python using statsmodels and z-score signals

By PyQuant News

Published: 2026-03-07

URL: https://pyquantnews.substack.com/p/pairs-trading-starts-with-a-thesis


Each week, I send out one Python tutorial to help you get started with algorithmic trading, market data analysis, and quant finance. Upgrade to a paid plan to access the code notebooks.


In today’s post, you’ll use Python to find stock pairs that move together, test whether that relationship is statistically meaningful, and build a simple trading strategy that bets on the relationship snapping back when it temporarily breaks down.

What pairs trading actually is

Pairs trading is a strategy where you buy one stock and sell another at the same time, betting that the price gap between them will shrink back to normal.

The idea has been around since the 1980s, when a quantitative research group at Morgan Stanley started systematically testing it. They noticed that stocks in the same industry tend to move together over time, and that temporary divergences often correct themselves.

The approach became one of the earliest forms of what people now call statistical arbitrage (using math to find and exploit pricing inefficiencies between related assets).

How professionals use it

Today, trading teams at hedge funds still run variations of this strategy across thousands of stock pairs.

They don’t just blindly test every possible combination. Instead, they start with groups of companies that share real economic connections, like two oil producers or two semiconductor manufacturers.

Then they use a statistical test called cointegration to check whether the price relationship between two stocks is stable enough to trade. Cointegration is different from correlation.

Correlation just means two stocks tend to go up and down at the same time.

Cointegration means there’s a specific mathematical relationship between their prices that stays consistent, so when prices drift apart, they tend to come back together.

Professionals also use something called a hedge ratio, which tells them exactly how many shares of one stock to trade against the other so the position stays balanced.

Why this matters for you

If you’re learning Python for trading, pairs trading is one of the best strategies to study first because it forces you to combine data analysis, statistics, and strategy logic in one project.

You’ll practice downloading real market data, running statistical tests to check whether a relationship is meaningful, and translating a trading idea into actual buy and sell decisions in code.

The strategy also teaches you an important lesson early on. Just because a statistical test says two stocks are related doesn’t mean the relationship will make money.

The code in today’s tutorial produces a strategy that actually loses money, and understanding why that happens is more valuable than finding a strategy that looks good on paper.

Let’s see how it works with Python.

This Substack is reader-supported. To get the code notebooks, consider becoming a free or paid subscriber.

Library installation

Install all required libraries for downloading market data, running statistical tests, and plotting results.

Imports and setup

numpy and pandas handle numerical arrays and tabular data. statsmodels provides the cointegration test (coint), ordinary least squares regression (OLS), and rolling regression tools we use to measure and track the relationship between stock pairs. yfinance downloads historical price data from Yahoo Finance. seaborn and matplotlib produce the heatmap and time series plots.

Download price data for candidate pairs

We download one year of daily closing prices for five large-cap tech stocks. Starting with a small, economically related group reflects the professional approach described in the post: pick companies that share a real business connection first, then let statistics confirm or reject the relationship.

Using only closing prices keeps the analysis simple and focused on end-of-day valuations, which is the standard starting point for pairs trading research. Notice we deliberately chose a narrow universe of five stocks rather than scanning hundreds. As the post explains, blindly testing every combination inflates false positives because you’re running too many comparisons without an economic thesis.

Test all pairs for cointegration

This function runs the Engle-Granger cointegration test on every unique pair in our universe and collects pairs whose p-value falls below 0.05, meaning there is statistical evidence that their price relationship is mean-reverting rather than random.

Cointegration is the core statistical concept behind pairs trading. Unlike correlation, which only measures whether two stocks move in the same direction, cointegration tests whether the gap between two price series tends to revert to a stable level over time. The p-value matrix we build here will let us visually compare every pair at once in the next step.

Run the cointegration scan across all pairs and visualize which relationships pass the significance threshold.

The result is a heatmap.

The mask hides every pair with a p-value at or above 0.05, so only statistically significant relationships appear on the heatmap. This gives us a quick visual filter. With five stocks we have only ten unique pairs, but in a larger universe this heatmap becomes essential for spotting candidates without scrolling through tables of numbers.

Compute the spread and hedge ratio

We isolate the AMZN-AAPL pair and use ordinary least squares regression to estimate the hedge ratio, which tells us how many dollars of AAPL to hold per dollar of AMZN so the combined position is balanced. The spread is the residual: the part of AAPL’s price that AMZN’s price cannot explain.

The hedge ratio b is what makes this a market-neutral strategy. Without it, we would be exposed to the overall direction of the tech sector. By subtracting b times AMZN from AAPL, we isolate only the relative mispricing between the two stocks. If the cointegration relationship holds, this spread should fluctuate around a stable mean.

Plot the spread over time with a horizontal line at its mean to see whether it behaves like a mean-reverting series.

The result is the spread.

Visually checking the spread is a sanity step before trading. We want to see the spread crossing its mean repeatedly. A spread that trends away from the mean suggests the cointegration relationship may be breaking down, which is exactly the kind of warning that separates careful analysis from blind backtesting.

Define a z-score function that standardizes the spread, then plot it with threshold lines at +1 and -1 to identify trade entry points.

The z-score converts the spread into units of standard deviation, which makes it easy to set universal entry thresholds regardless of the dollar scale of the spread. When the z-score drops below -1, the spread is unusually cheap and we go long. When it rises above +1, the spread is unusually expensive and we go short. These thresholds are a simple starting point; professionals often optimize them or add exit rules at the mean.

Build and evaluate the trading strategy

Combine the z-score signal and the dollar spread into a single DataFrame, then assign trade direction: go long the spread when the z-score is at or below -1, and short it when the z-score is at or above +1.

The side column holds +1, -1, or 0, representing long, short, or flat. We multiply the daily percentage change of the spread by this side value to get our strategy return each day. This is a simplified position model that assumes we enter and exit at closing prices with no transaction costs, which is fine for learning but would need refinement before live trading.

Calculate daily strategy returns by multiplying the spread’s percentage change by our position direction, then plot cumulative returns to see how the strategy performed.

The result is our naive equity curve.

As the post warns, this strategy loses money over the test period. That result is intentional and instructive. A passing cointegration test on historical data does not guarantee profitable trading.

The z-score thresholds use the full sample mean and standard deviation, which introduces lookahead bias since we would not know those values in real time.

Addressing that bias with rolling windows, adding transaction costs, and testing on out-of-sample data are the natural next steps that separate a learning exercise from a deployable strategy.

Your next steps

You now have the tools to test whether a stock pair relationship is real and to see exactly what happens when you trade it. Start with an economic thesis, let the statistics confirm or reject it, and trust what the backtest actually shows you.