Backtesting A Mean-Reversion Strategy In Python

The importable AIQ EDS file based on Anthony Garner’s article in May 2019 Stocks & Commodities “Backtesting A Mean-Reversion Strategy In Python,” can be obtained on request via email to info@TradersEdgeSystems.com. The code is also shown below.

I backtested the author’s mean-reversion system (MeanRev.eds) using both the EDS module, which tests every trade on a one-share basis, and also via the Portfolio Manager, which performs a trading simulation.

The short side strategy showed a loss overall in the EDS test so I tested only the long side in the Portfolio Manager. I selected trades using the z-score, taking the lowest values.

For capitalization, I used max of three trades per day with a max total of 10 open trades at one time, 10% allocated to each position. I did not deduct slippage but did deduct commissions. I used a recent list of the NASDAQ 100 stocks to run the test. The equity curve and account statistics report are shown in Figure 7.

Sample Chart

FIGURE 7: AIQ. This shows the equity curve (blue line) from long-only trading the NASDAQ 100 list of stocks from 1999 to March 15, 2019. The red line is the NDX index.

!Backtesting a Mean-Reversion Strategy In Python !Author: Anthony Garner, TASC May 2019 !Coded by: Richard Denning 3/14/19 !www.TradersEdgeSystems.com 

!ABBREVIATIONS:
C is [close].

!INPUTS:
meanLen is 10.
longZmult is -1.
shortZmult is 1.
meanMult is 10.

!FORMULAS:

SMA is simpleavg(C,meanLen).
LMA is simpleavg(C,meanLen*meanMult).
STD is sqrt(variance(C,meanLen)).
zScore is (C - SMA) / STD.

!TRADING SIGNALS & EXITS:

buyLong if zScore < longZmult and SMA > LMA.
sellShort if zScore > shortZmult and SMA < LMA.
exitLong if valresult(zScore,1) < -0.5 and zScore > 0.5.
exitShort if valresult(zScore,1) > 0.5 and zScore < -0.5.

showValues if 1.

—Richard Denning
info@TradersEdgeSystems.com
for AIQ Systems