One of the most interesting challenges I faced as a portfolio manager post the 2008 GFC was a renewed interest in pairs trading as a risk mitigation strategy.

And while we often paired off stocks by region or business type, I was never really sure a pair was an actual mean-reverting pair.

Fortunately there’s a pretty simple mechanism for this. Cointegration is a measure of the linear relationship between two stationary variables. Cointegrated stock prices share similar stochastic trends, and therefore their residuals follow a stationary process, and while two cointegrated variables may not necessarily move in the same direction (correlation), the distance between them will remain constant over time

Code base here:

Two stocks that DO cointegrate (p-value < .05 is the traditional metric, though really that’s just a rule of thumb) are credit card companies Capital One and Discover Financial. Recent charge-off guidance at DFS has put COF well ahead of its peer for the moment.

The codebase includes an Objects module which contains a Portfolio class, which itself contains a Pair class.

Send in a list of stocks (I am sending in two but you can send in several – it uses itertools to create multiple pairs) and log-normalize the stock prices is a convention in cointegration testing so – set log to True.

The code for which is:

Good article on this topic here: