This website uses cookies to collect usage information in order to offer a better browsing experience. By browsing this site or by clicking on the "ACCEPT COOKIES" button you accept our Cookie Policy.

A Python Package for Optimal Mean Reversion Trading

Pairs trading is among the most popular trading strategies in many markets, ranging from equities and ETFs to currencies and futures markets. It involves taking simultaneous positions in two correlated assets. The idea is that while typically it is difficult to accurately capture the price evolution of a single asset, a pairs position may exhibit mean reversion that can be better modeled. In short, pairs trading is a market-neutral strategy that seeks to profit from the price convergence between the two assets.  

Practical examples of mean reverting price spread include pairs of stocks/ETFs, futures and its spot, physical commodity and associated ETFs, and more. There are also automated approaches for identifying mean-reverting portfolios. 

In this new python package called Machine Learning Financial Laboratory (mlfinlab), there is a module that automatically solves for the optimal trading strategies (entry & exit price thresholds) when the underlying assets/portfolios have mean-reverting price dynamics. It covers a few mean-reverting models, including the Ornstein-Uhlenbeck (OU) model. The trading model and computations are based on the results from this journal article

The module includes three main steps: 

Model Fitting 

We fit any given portfolio value to the mean-reverting Ornstein-Uhlenbeck (OU) process. The statistical technique involved is the maximum likelihood estimation (MLE) method where we optimize the average log-likelihood. While pairs trading is an intuitive strategy, any serious pairs trading system must include a procedure for optimizing the positions along with timing for entry and exit. The goal of this model fitting step is to select the portfolio weights so as to optimize the level of mean reversion.  

Source: MLfinlab documentation 

Determining the Optimal Entry & Exit Levels 

The optimal entry & exit levels are computed based on your data. The user can call one of the functions mentioned below. They present the solutions to the equations established in this paper. Stop-loss level can be added and optimal levels are adjusted accordingly. 

A Python Package for Optimal Mean Reversion Trading

Source: MLfinlab documentation

Summary of Results & Plotting 

The description function returns all the model parameters, optimal pair ratio, allocated trading costs, stop-loss level, along with the optimal levels. 

The plotl_levelsfunction illustrates the optimal exit and entry levels on the graph alongside with the given data 

The documentation provides an example for instant implementation. The ETF pair (GLD, GDX) and dates are chosen to coincide with that in the book, but one can change them easily. 

Source: MLfinlab documentation 

For additional pairs trading examples based on the approach presented above, with real data and performance summary, we refer to this article on Towards Data Science


T. Leung T. and X. Li (2015), Optimal Mean Reversion Trading with Transaction Costs & Stop-Loss Exit, International Journal of Theoretical & Applied Finance, vol 18, issue 3, p.1550020. ← Python package is developed based on this paper. 

D. Lee and T. Leung (2020), On the Efficacy of Optimized Exit Rule for Mean Reversion Trading, International Journal of Financial Engineering. 

Disclosure: Interactive Brokers

Information posted on IBKR Traders’ Insight that is provided by third-parties and not by Interactive Brokers does NOT constitute a recommendation by Interactive Brokers that you should contract for the services of that third party. Third-party participants who contribute to IBKR Traders’ Insight are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.

This material is from Computational Finance and Risk Management, University of Washington and is being posted with permission from Computational Finance and Risk Management, University of Washington. The views expressed in this material are solely those of the author and/or Computational Finance and Risk Management, University of Washington and IBKR is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to sell or the solicitation of an offer to buy any security. To the extent that this material discusses general market activity, industry or sector trends or other broad based economic or political conditions, it should not be construed as research or investment advice. To the extent that it includes references to specific securities, commodities, currencies, or other instruments, those references do not constitute a recommendation to buy, sell or hold such security. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

Disclosure: Forex

There is a substantial risk of loss in foreign exchange trading. The settlement date of foreign exchange trades can vary due to time zone differences and bank holidays. When trading across foreign exchange markets, this may necessitate borrowing funds to settle foreign exchange trades. The interest rate on borrowed funds must be considered when computing the cost of trades across multiple markets.

Disclosure: Futures Trading

Futures are not suitable for all investors. The amount you may lose may be greater than your initial investment. Before trading futures, please read the CFTC Risk Disclosure. A copy and additional information are available at

trading top