How to Write a Mean-reverting Trading Algorithm

Complete overview of training and testing a trading mean reverting algorithm. The first step in any automated trading strategy is to find a signal or signals that indicate when a trader should be entered. This video contains a discussion of identifying that algorithmic signal and testing the resulting profitability. While the signals vary the implementation of adding signals and testing is fairly constant, so while we may not identify the best strategy, you will be able to use the techniques discussed to test your own strategies quickly and easily. Discussion of drawbacks and limitations.

The idea behind mean reversion is that securities should not stray too far from their "mean". The question becomes what is the mean, and how far is too far away from it? There are many answers to these questions nd the video tutorial will use one method andthen leave it up to you to refine and improve on the model we develop.

Get the notebook here.

Mean Reverting Trading Algorithm

How the Strategy Works

The algorithm treats a 21-day moving average of the gold ETF's closing price as the mean, and uses the ratio of price to that average to measure how far price has strayed. When the ratio rises above its 95th percentile the strategy goes short; when it falls below its 5th percentile it goes long. It stays in each trade until the opposite signal, so it is always either long or short.

  • Downloading five years of closing prices with pandas-datareader
  • Calculating log returns, the 21-day moving average and the price-to-average ratio
  • Finding the 5th and 95th percentile thresholds with numpy.percentile
  • Plotting the ratio against those thresholds to see how it overshoots and corrects
  • Building the position column with np.where and forward-filling it
  • Shifting the signal one day to avoid look-ahead bias, then comparing the strategy with buy and hold

Over the five years tested, the strategy beat buy and hold by about seven percentage points. Try changing the percentiles, or add a neutral position when the ratio returns to the mean. For the companion momentum strategy, see Algorithmic Trading with Python: Intro. For educational purposes only; not investment advice.



Advertisement