🐍 How to test if two stocks actually move together


EXCLUSIVE PARTNER DEAL FOR PYQUANT NEWS READERS:

20% off options-based trading signals

MenthorQ uses the options market to generate trading signals for stocks and futures. Join with an exclusive discount.

Be sure to use the discount code PYQUANTNEWS20.

​

Most pairs trading strategies fail because the statistical relationship was never real in the first place (here's how to check)

You've probably heard that pairs trading is a good first strategy to learn.

So you start searching for stock pairs, run some tests, and find what looks like a perfect match.

Then you trade it and lose money.

The frustrating part isn't the loss.

It's not knowing whether the relationship was real or whether you just got fooled by random data.

Here's the reality.

A study by Do and Faff (2010) found that pairs trading profits have declined significantly since the 1990s as more traders adopted the strategy.

One major reason is that most people test too many stock combinations at once without any reason to believe the stocks are connected.

When you run hundreds of statistical tests, some will pass by pure chance.

Professionals avoid this by starting with a business reason why two companies should move together, then using statistics to confirm it.

Here's the good news.

Python gives you a straightforward way to test whether a stock pair relationship is statistically meaningful before you risk any money.

You can go from a hypothesis about two related companies to a concrete, testable result in a few lines of code.

Here's an example.

Assumes `data` is a pandas DataFrame where each column holds daily closing prices for one stock (for example, columns named "AMZN" and "AAPL").

This code does three things.

First, it runs a cointegration test, which checks whether the price gap between two stocks tends to snap back to a stable level rather than wandering randomly.

A p-value below 0.05 means there's statistical evidence the relationship is real.

Second, it calculates a hedge ratio using regression, which tells you exactly how to size your positions so you're only betting on the relative gap between the two stocks, not on whether the whole market goes up or down.

Third, it converts the spread into a z-score so you can see how far the current gap is from its historical average, measured in standard deviations.

If the z-score is above +1 or below -1, the gap is unusually wide and might be worth trading.

But as the original analysis shows, a passing statistical test alone doesn't guarantee profits.

You still need to test on data the model hasn't seen before and account for trading costs.

​Getting Started With Python for Quant Finance covers this exact workflow and goes further.

It walks you through how to run realistic simulations on historical data, measure whether a strategy actually has an advantage, and understand whether performance holds up in different market conditions.

You don't have to figure out the right sequence on your own.

Inside Getting Started With Python for Quant Finance:

  • Step-by-step frameworks for strategy testing. Instead of guessing which statistical tests to run and in what order, you follow a structured process for turning a trading idea into a properly validated simulation.
  • 40 code templates. The pairs trading workflow above is a starting point. The templates cover portfolio management, risk measurement, and automated execution so you can modify working code instead of writing everything from scratch.
  • Private community of 1,700+ Python traders. When your cointegration test passes but your strategy still loses money, you can ask people who've dealt with the same problem and get a real answer.

These resources work together to take you from running a single test to building strategies you can actually trust with real money.

⭐️ ⭐️ ⭐️ ⭐️ ⭐️
" A top-tier introduction to Python and quant finance. "
– Zac T
​

Your next steps

Start with two companies you believe are connected for a real business reason (same industry, same supply chain, direct competitors).

Run the cointegration test on a year of their price data.

If the test passes, compute the spread and z-score, then check whether the spread actually crosses back through its mean multiple times.

If it does, you have a candidate worth testing further with out-of-sample data (price data the model has never seen).

That progression, from hypothesis to statistical test to realistic simulation, is exactly the path a structured program lays out for you.

​Build, test, and run your own trading strategies πŸ‘‰β€‹

The course takes you from pulling market data to running realistic simulations and connecting to a broker, one step at a time.


​

Jason Strimpel, founder of PyQuant News

Say πŸ‘‹ on X/Twitter, LinkedIn, or book a call with me. You can always reply to these emails. I check them all

You got this email because you joined the PyQuant Newsletter or bought a product of mine.

You told me your email address is Reader.

Not right? Update your profile.

Want to stop getting these emails? No problem! Unsubscribe from all my emails.

Never investment advice. Use at your own risk. For educational purposes.

113 Cherry St #92768, Seattle, WA 98104

Β© 2026 PyQuant News, LLC

​

PyQuant Tips

For finance professionals, coders, and complete beginners. Automate your trading, investing, and data analysis with Python. No jargon, no fancy math, code you can use.

Read more from PyQuant Tips
Decompose time series into trend, seasonality, and noise with Python to build better forecasting models for quant finance.

Most beginners model a whole time series at once (here's why that fails) You sit down with a price chart or an economic indicator, build a model, and the predictions look solid on historical data. Then you feed in new data and the results fall apart. If that sounds familiar, you're not alone. The problem usually isn't your model. It's that you skipped a step professionals never skip. Most financial and economic data contains several patterns layered on top of each other. There's a long-term...

Calculate the Hurst exponent in Python to detect trending or mean-reverting markets. Pick the right trading strategy.

EXCLUSIVE PARTNER DEAL FOR PYQUANT NEWS READERS: 20% off options-based trading signals MenthorQ uses the options market to generate trading signals for stocks and futures. Join with an exclusive discount. Grab your 20% discount with this link πŸ‘‰ Be sure to use the discount code PYQUANTNEWS20. Most traders use the same strategy no matter what the market is doing (here's how to know when to switch) You've probably found a strategy that looked great on a chart, then watched it bleed money for...

Smooth stock prices in Python with a Kalman filter. Replace arbitrary moving average windows with adaptive estimates.

EXCLUSIVE PARTNER DEAL FOR PYQUANT NEWS READERS: 20% off options-based trading signals MenthorQ uses the options market to generate trading signals for stocks and futures. Join with an exclusive discount. Grab your 20% discount with this link πŸ‘‰ Be sure to use the discount code PYQUANTNEWS20. Most beginners pick a moving average window that looks good on old data, then watch it fail on new data (here's how to fix that) You've probably spent time tweaking a moving average, trying 20 days, then...