See https://www.quantstart.com/articles/Basics-of-Statistical-Mean-Reversion-Testing for implementation.