TRADESTATION: MAY 2019In “Backtesting A Mean-Reversion Strategy In Python” in this issue, author Anthony Garner introduces a strategy based on the concept of buying an oversold asset and selling an overbought asset. To quantify this, he uses the classic z-score calculation. In addition, he adds a component to evaluate the existing trend as well as position sizing to allow for reinvestment.Here is TradeStation EasyLanguage code for an indicator and strategy based on the author’s concepts. WEALTH-LAB: MAY 2019Wealth-Lab owes to C# the power of extensibility and ability to express trading rules of any complexity. However, its strong point is also that no programming may be required to “wire-frame” a trading system idea.The Strategy Builder in Wealth-Lab lets us throw building blocks known as rules onto a “drawing board,” group them together, or divide them into separate chunks.
METASTOCK: MAY 2019Anthony Garner’s article in this issue, “Backtesting A Mean-Reversion Strategy In Python,” presents a trading system and the code to backtest it using the Python language. The code to test the system in MetaStock is provided here.General tab:Name: Mean-Reversion StrategyNotes:Based on code provided by Anthony GarnerBuy Order tab:Formula:length:= 10;sma:= mov(c,length, S);lma:= mov(c, length.10, s);dev:= std(c, length);z:= (C - sma)/dev;(z lma)Sell Order tab:Formula:length:= 10;sma:= mov(c,length, S);lma:= mov(c, length.10, s);dev:= std(c, length);z:= (C - sma)/dev;z -0.5Sell Short Order tab:Formula:length:= 10;sma:= mov(c,length, S);lma:= mov(c, length.10, s);dev:= std(c, length);z:= (C - sma)/dev;(z 1) AND (sma. THINKORSWIM: MAY 2019We have put together a strategy for thinkorswim based on Anthony Garner’s article “Backtesting A Mean-Reversion Strategy In Python.” The strategy is built using our proprietary scripting language, thinkscript, as opposed to Python. To ease the loading process, simply click on or enter the address into a web browser and then click open shared item from within thinkorswim. Choose view thinkscript and name it “SimpleMeanReversion.” This can then be added to your chart.A sample chart is shown in Figure 4. NINJATRADER: MAY 2019The MeanReversal strategy that is discussed in “Backtesting A Mean-Reversion Strategy In Python” in this issue by Anthony Garner is available for download at the following links for NinjaTrader 8 and NinjaTrader 7:. NinjaTrader 8: 0007.
NinjaTrader 7: 0007Once the file is downloaded, you can import the strategy in NinjaTader 8 from within the control center by selecting Tools → Import → NinjaScript Add-On and then selecting the downloaded file for NinjaTrader 8. To import into NinjaTrader 7, from within the control center window, select the menu File → Utilities → Import NinjaScript and select the downloaded file.You can review the strategy’s source code in NinjaTrader 8 by selecting the menu New → NinjaScript Editor → Strategies from within the control center window and selecting the MeanReversal file. You can review the strategy’s source code in NinjaTrader 7 by selecting the menu Tools → Edit NinjaScript → Strategy from within the control center window and selecting the MeanReversal file.NinjaScript uses compiled DLLs that run native, not interpreted, to provide you with the highest performance possible.A sample chart implementing the strategy is shown in Figure 5. NEUROSHELL TRADER: MAY 2019The mean-reversion strategy described by Anthony Garner in his article in this issue, “Backtesting A Mean-Reversion Strategy In Python,” can be easily implemented in NeuroShell Trader by combining a few of NeuroShell Trader’s 800+ indicators. Simply select “New trading strategy” from the insert menu and enter the following in the appropriate locations of the trading strategy wizard:BUY LONG CONDITIONS: All of which must be trueCrossBelow(StndNormZScore(Close,10),-1)AB(Avg(Close,10),Avg(Close,100))AB(Lag(StndNormZScore(Close,10),1),-0.5)COVER SHORT CONDITIONS: All of which must be trueCrossBelow(StndNormZScore(Close,10),0.5)POSITION SIZING METHOD:Percent of Account100.00% of account balanceIf you choose to use pyramiding or slippage, those can be set up in the trading parameters dialog as well.
After entering the system conditions, you can also choose whether the parameters should be genetically optimized. After backtesting the trading strategy, use the detailed analysis button to view the backtest and trade-by-trade statistics for the system.Users of NeuroShell Trader can go to the Stocks & Commodities section of the NeuroShell Trader free technical support website to download a copy of this or any previous Traders’ Tips.A sample chart is shown in Figure 6. TRADE NAVIGATOR: MAY 2019To make it easy to implement the concepts presented in “Backtesting A Mean-Reversion Strategy In Python” by Anthony Garner in this issue, we’ve created a special file that can be downloaded in Trade Navigator.The file name for this library is “SC201905.” To download it, click on Trade Navigator’s blue telephone button, select download special file, and replace the word “upgrade” with “SC201905” (without the quotes). Then click the start button.
EasyLanguage Essentials Programmer s Guide is a programmers introductio n to TradeStation’s EasyLanguage programming tools. This book is based on the current release of TradeStation 8.3. It is assumed that the reader has access to the TradeStation platform.
When prompted to upgrade, click the yes button. If prompted to close all software, click on the continue button. Your library will now download.The library contains a prebuilt strategy called “mean-reversion strategy” based on the article. This prebuilt strategy can be overlaid onto your chart by opening the charting dropdown menu, selecting the add to chart command, then selecting the strategies tab.If you have any difficulty importing the library or using the strategy, users may contact our technical support staff by phone or by live chat.
The live chat tool is located under Trade Navigator’s help menu, or near the top of the homepage. Support hours are M-F 8am-8pm US Eastern Time.
Happy Trading!—Genesis Financial TechnologiesTech support 719 884-0245. AIQ: MAY 2019The importable AIQ EDS file based on Anthony Garner’s article in this issue, “Backtesting A Mean-Reversion Strategy In Python,” can be obtained on request via email to. 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. 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 LMA.sellShort if zScore shortZmult and SMA 0.5.exitShort if valresult(zScore,1) 0.5 and zScore. TRADERSSTUDIO: MAY 2019The importable TradersStudio file based on Anthony Garner’s article in this issue, “Backtesting A Mean-Reversion Strategy In Python,” can be obtained on request via email to. The code is also shown below.After coding the system given in the article in TradersStudio, I ran a quick optimization trading the Nasdaq 100 list of stocks.
The results showed the short moving average parameter should be changed to 20 from 10, with the other parameters staying the same. Figures 8 and 9 show the results of trading a constant 200 shares of each stock with parameters (20,-1,10) trading the long-only side. I did not code or test the short side.'
Backtesting a Mean-Reversion Strategy In Python'Author: Anthony Garner, TASC May 2019'Coded by: Richard Denning 3/14/19'www.TradersEdgeSystems.comsub MEANREV(meanLen,longZmult,meanMult)'INPUTS:'meanLen = 20,longZmult = -1,meanMult = 10Dim SMA As BarArrayDim LMA As BarArrayDim STD As BarArrayDim zScore As BarArray'FORMULAS:SMA = Average(C,meanLen)LMA = Average(C,meanLen.meanMult)STD = StdDevS(C,meanLen)zScore = (C - SMA) / STD'TRADING SIGNALS & EXITS:If zScore LMA Then Buy('LE',1,0,Market,Day)If zScore1 0.5 Then ExitLong('LX',',1,0,Market,Day)End Sub. FIGURE 10: EXCEL. Price action is shown with z-score decision boundaries highlighted.He includes a number of settings that can be used to customize the results. Which I have implemented in Excel (Figure 10). Some of the controls need a bit of explaining:The% of equity actually controls the number of shares in a given transaction, as it is the main driver in the calculation of fixed fraction, which is the number of shares you can buy with that percentage of your current equity.Max position (Figure 11) sets a “soft” high-water mark in that once you have more shares (long or short) than this number, you will not add any more. But your first purchase or short sale may have exceeded this max by quite a bit.
FIGURE 11: EXCEL. Here, the equity with max position control is set to 1.You can play with the user controls. Enjoy!The spreadsheet file for this Traders’ Tip can be downloaded. To successfully download it, follow these steps:.
Right-click on the, then. Select “save as” (or “save target as”) to place a copy of the spreadsheet file on your hard drive.—Ron McAllisterExcel and VBA programmerOriginally published in the May 2019 issue ofTechnical Analysis of STOCKS & COMMODITIES magazine.All rights reserved.
© Copyright 2019, Technical Analysis, Inc.