http://tradingtuitions.com/category/categories/amibroker/tutorials/
Build your own Algorithmic Trading Trading System: Step by Step TutorialTutorial- Part 1 Posted on July 26, 2016 by admin
This is a follow up article on our Introductory post Algorithmic Trading 101. 101 . I hope you understood the basic concepts of Algorithmic Trading and its benefits. Now, let’s gear up to build your own Trading system from scratch. This article would describe descr ibe every step needed Amibroke ker r to to create your first Algorithmic Trading system. We shall use our favorite tool Amibro create Trading Algorithm.
Pre-requisites:
Elementary knowledge of Technical Analysis. Hands on experience in Amibroker and AFL Coding.
Check out our Amibroker tutorial series here here..
Step 1: Formulate your Trading Plan The very first step would be to make a checklist of the parameters based on which you take your Trading decisions. These parameters should be something that can be formulated into an Algorithm, strictly avoiding elements of Gut feeling or speculation. It can be as simple as time based decisions like buying a a particular stock on the first day of every month, or decisions based on technical analysis like Trendline breakout with increasing volume. You should also plan your investment amount for each transaction, timeframe for trading, as well as your stoploss and targets. Once you have formulated your plan you should validate it against a bunch of stocks to see if it really works. This step is very important before you jump into the next steps. If your plan works for 50% of time, with a Risk-Reward ratio of atleast 1:2, then you are good to convert it into an Algorithm.
Step 2: Convert Algorithm
your
idea
into
an
Next, you should start writing a code for your formulated trading plan. A code is nothing but a bunch of statements through which computer can understand your Buy/Sell logic. We would use Amibroker Formula Language (AFL) for writing Trading Algorithm. It’s a high level programming language and very easy to understand if you start from basics. Even a person from non-programming background can learn AFL and avoid spending unnecessary on expensive ready-made ready-made AFL’s. Check this post for AFL tutorial from scratch. Let’s suppose you trade based on exponential moving average crossover in daily timeframe. You would buy a stock when 50 EMA crosses 200 EMA from below, and sell when 50 EMA crosses 200 EMA from above. For the sake of simplicity let’s consider it is a Buy only strategy. Below is the simple AFL code for this logic.
http://tradingtuitions.com/category/categories/amibroker/tutorials/
_SECTION_BEGIN("Simple Algorithmic Trading System"); //Parameters MALength1 = 50; MALength2 = 200; //Buy-Sell Logic Buy = Cross(ema( C, MALength1 ),ema( C, MALength2 )); Sell =Cross( ema( C, MALength2 ), ema( C, MALength1 )) ; Buy = ExRem( Buy, Sell ); Sell = ExRem( Sell, Buy ); Plot( Close, "Price", colorWhite, styleCandle ); Plot(ema( C, MALength1 ),"FastEMA",colorWhite); Plot(ema( C, MALength2 ),"SlowEMA",colorBlue); _SECTION_END();
This is how it looks like when applied in the chart:
Step 3: Backtest your Algorithm Algorithm Backtesting is a process to validate the performance of your Algorithm on Historical Data. This is something similar to what you did in Step 1 manually. Amibroker has a very powerful backtest engine that can do this in seconds. You just need to import Historical data of your favorite scrips into Amibroker. Check out this link to to download Intraday 1 minute data for Nifty and Banknifty. In order to understand the detailed process of backtesting in Amibroker, please refer to the below link from official documentation:
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Backtesting your Trading ideas in Amibroker To backtest this EMA Crossover strategy, we will use NSE Nifty as our preferred scrip, with the initial capital of 200000 Rupees. Let’s say we buy 2 Lots(150 nos) per transaction. Once you backtest this strategy you will get a detailed report which includes your Annual CAGR, Drawdown, Net Profit/Loss% etc. You can understand various parameters in Amibroker Backtest report here. See below the summary of our initial backtest:
Value Parameter Nifty Initial Capital
200000
Final Capital
1037655
Backtest Period
26-Mar-2002 to 23-July-2016
Net Profit %
418.83%
Annual Return %
10.45%
Number of Trades
11
Winning Trade %
54.55%
Average holding Period
227.91 days
Max consecutive losses
2
Max system % drawdown
-33.24%
Max Trade % drawdown
-29.94%
Well, this is not bad, but there are still scopes of improvement. i mprovement. Drawdown is on a little higher side which can put retail investors in trouble.
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Amibroker AFL: Step S tep by Step Tutorial Tutorial-Part 2 Posted on January 16, 2016 by admin
This is Part 2 of Amibroker AFL tutorial series. If you haven’t already gone through Part through Part 1 of this series, please find it in the below link:Amibroker AFL: Step by Step Tutorial- Part 1
Parameterized AFL code //-----------------------------------------------------// Formula Name: Parameterized AFL code // Author/Upload Author/Uploader: er: Trading Tuitions // E-mail: support@tradin
[email protected] gtuitions.com // Website: www.tradingt www.tradingtuitions.com uitions.com //-----------------------------------------------------_SECTION_BEGIN("Parameters"); Plot(Close,"Price",ParamColor("Color",colorBlue),styleLine); _SECTION_END();
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Plotting simple EMA Indicator //-----------------------------------------------------// Formula Name: Simple EMA Indicator // Author/Uploader: Trading Tuitions // E-mail:
[email protected] // Website: www.tradingtuitions.com //-----------------------------------------------------_SECTION_BEGIN("Simple EMA Indicator"); SetChartOptions(0,chartShowArrows|chartShowDates); _N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C )); Plot(Close,"Price",color=colorBlue,style=styleCandle); Plot(EMA(C,50),"EMA50",ParamColor("EMAColor",colorBlue)); _SECTION_END();
Plotting parameterized EMA //-----------------------------------------------------// Formula Name: Parameterized EMA // Author/Uploader: Trading Tuitions // E-mail:
[email protected] // Website: www.tradingtuitions.com //-----------------------------------------------------_SECTION_BEGIN("Parameterized EMA Indicator"); SetChartOptions(0,chartShowArrows|chartShowDates); _N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C )); Plot(Close,"Price",color=colorBlue,style=styleCandle);
http://tradingtuitions.com/category/categories/amibroker/tutorials/
EMAPeriod=Param("EMAPeriod",50,1,200,1); Plot(EMA(C,EMAPeriod),"EMA",ParamColor("EMAColor",colorBlue)); _SECTION_END();
Plotting a Heikin Ashi Chart //-----------------------------------------------------// Formula Name: Heikin Ashi Chart // Author/Uploader: Trading Tuitions // E-mail:
[email protected] // Website: www.tradingtuitions.com //-----------------------------------------------------_SECTION_BEGIN("Heikin Ashi Chart"); SetChartOptions(0,chartShowArrows | chartShowDates); _N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C )); HaClose = (O + H + L + C)/4; HaOpen = AMA( Ref( HaClose, -1 ), 0.5 ); HaHigh = Max( H, Max( HaClose, HaOpen ) ); HaLow = Min( L, Min( HaClose, HaOpen ) ); barcolor = IIf(HaClose >= HaOpen,colorGreen,colorRed); PlotOHLC( HaOpen, HaHigh, HaLow, HaClose, "HeikinAshi", barcolor, styleCandle ); _SECTION_END();
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Writing text to Commentary window //-----------------------------------------------------// Formula Name: Commentary // Author/Uploader: Trading Tuitions // E-mail:
[email protected] // Website: www.tradingtuitions.com //-----------------------------------------------------_SECTION_BEGIN("Price"); SetChartOptions(0,chartShowArrows|chartShowDates); _N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C )); Plot( C, "Close", colorDefault,styleCandle ); _SECTION_END(); _SECTION_BEGIN("Volume"); Plot( Volume, "Volume", color=colorGrey40, ParamStyle( "Style", styleHistogram | styleOwnScale | styleThick, maskHistogram ) ); writeif( Volume > ma(Volume,5), "The volume is greater than 5 days average. Indicates a good buying opportunity","None"); _SECTION_END();
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Liked the article? Please share it with your friends!
Amibroker AFL: Step by Step TutorialPart 3 Posted on January 16, 2016 by admin This is Part 3 of Amibroker AFL tutorial series. If you haven’t already gone through Part 1 & 2 of this series, please refer the below links:Amibroker AFL: Step by Step Tutorial- Part 1
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Amibroker AFL: Step by Step Tutorial- Part 2
Plotting a simple EMA Crossover //-----------------------------------------------------// Formula Name: Simple EMA Crossover // Author/Uploader: Trading Tuitions // E-mail:
[email protected] // Website: www.tradingtuitions.com //------------------------------------------------------
_SECTION_BEGIN("Simple EMA Crossover"); SetChartOptions(0,chartShowArrows | chartShowDates); _N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C )); FastEMA=Param("FastEMA",20,1,200,1); SlowEMA=Param("SlowEMA",50,1,200,1); Buy = Cross(ema( C, FastEMA ),ema( C, SlowEMA )); Sell =Cross( ema( C, SlowEMA ), ema( C, FastEMA )) ; Buy = ExRem( Buy, Sell ); Sell = ExRem( Sell, Buy ); Short = Sell; Cover = Buy; Plot( Close, "Price", colorBlue, styleCandle ); Plot(ema( C, FastEMA ),"FastEMA",colorWhite); Plot(ema( C, SlowEMA ),"SlowEMA",colorBlue); _SECTION_END();
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Plotting Buy/Sell Arrows //-----------------------------------------------------// // Formula Name: Simple EMA Crossover with Buy Sell Arrows // Author/Uploader: Trading Tuitions // E-mail:
[email protected] // Website: www.tradingtuitions.com //------------------------------------------------------
_SECTION_BEGIN("Simple EMA Crossover with Buy Sell Arrows"); SetChartOptions(0,chartShowArrows | chartShowDates); _N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C )); FastEMA=Param("FastEMA",20,1,200,1); SlowEMA=Param("SlowEMA",50,1,200,1); Buy = Cross(ema( C, FastEMA ),ema( C, SlowEMA )); Sell =Cross( ema( C, SlowEMA ), ema( C, FastEMA )) ; Buy = ExRem( Buy, Sell ); Sell = ExRem( Sell, Buy ); Short = Sell; Cover = Buy; Plot( Close, "Price", colorBlue, styleCandle ); Plot(ema( C, FastEMA ),"FastEMA",colorWhite); Plot(ema( C, SlowEMA ),"SlowEMA",colorBlue); /* Plot Buy and Sell Signal Arrows */ PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40); PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50); PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45); PlotShapes(IIf(Cover, shapeSquare, shapeNone),colorGreen, 0, L, Offset=40); PlotShapes(IIf(Cover, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50); PlotShapes(IIf(Cover, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=45); PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorRed, 0, H, Offset=40); PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50); PlotShapes(IIf(Sell, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=45); PlotShapes(IIf(Short, shapeSquare, shapeNone),colorRed, 0, H, Offset=40); PlotShapes(IIf(Short, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50); PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=45); _SECTION_END();
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Plotting Inside Day and Outside Day patterns
Note: Circle represents Inside Day and Star represents Outside Day //-----------------------------------------------------// Formula Name: Inside Day Outside Day Patterns // Author/Uploader: Trading Tuitions // E-mail:
[email protected] // Website: www.tradingtuitions.com //------------------------------------------------------
_SECTION_BEGIN("Inside Day Outside Day Patterns"); SetChartOptions(0,chartShowArrows | chartShowDates); _N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C )); Plot( Close, "Price", colorBlue, styleBar); PlotShapes(IIf(Inside(), shapeSmallCircle, shapeNone),colorGreen, 0, H, Offset=100); PlotShapes(IIf(Outside(), shapeStar, shapeNone),colorGreen, 0, H, Offset=100); _SECTION_END();
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Plotting MACD indicator with Signal Line //-----------------------------------------------------// Formula Name: MACD Crossover // Author/Uploader: Trading Tuitions // E-mail:
[email protected] // Website: www.tradingtuitions.com //-----------------------------------------------------_SECTION_BEGIN("MACD Crossover"); SetChartOptions(0,chartShowArrows | chartShowDates); _N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C )); Plot( Close, "Price", colorBlue, styleCandle); fast = Param( "Fast avg", 12, 2, 200, 1 ); slow = Param( "Slow avg", 26, 2, 200, 1 ); signal1 = Param( "Signal avg", 9, 2, 200, 1 ); Plot(MACD(fast,slow),"MACD",color=colorRed,styleOwnScale); Plot(Signal(fast,slow,signal1),"Signal",color=colorBlue,styleOwnScale); Buy= Cross(MACD(fast,slow), Signal(fast,slow,signal1)); Sell= Cross(Signal(fast,slow,signal1),MACD(fast,slow)); Buy = ExRem( Buy, Sell ); Sell = ExRem( Sell, Buy ); Short = Sell; Cover = Buy; _SECTION_END();
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Plot Price level at Buy/Sell signal //-----------------------------------------------------// // Formula Name: Plot Price Level // Author/Uploader: Snehil Kamal // E-mail: // Website: //------------------------------------------------------
_SECTION_BEGIN("Plot Price Level"); SetChartOptions(0,chartShowArrows | chartShowDates); _N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C )); FastEMA=Param("FastEMA",20,1,200,1); SlowEMA=Param("SlowEMA",50,1,200,1); Buy = Cross(ema( C, FastEMA ),ema( C, SlowEMA )); Sell =Cross( ema( C, SlowEMA ), ema( C, FastEMA )) ; Buy = ExRem( Buy, Sell ); Sell = ExRem( Sell, Buy ); Short = Sell; Cover = Buy; Plot( Close, "Price", colorBlue, styleCandle ); Plot(ema( C, FastEMA ),"FastEMA",colorWhite);
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Plot(ema( C, SlowEMA ),"SlowEMA",colorBlue); dist = 1.5*ATR(10); for( i = 0; i < BarCount; i++ ) { if( Buy[i] ) PlotText( "Buy\n@" + C[ i ], i, L[ i ]-dist[i], colorGreen,colorYellow ); if( Sell[i] ) PlotText( "Sell\n@" + C[ i ], i, H[ i ]+dist[i], colorRed, colorYellow ); }
_SECTION_END();
Amibroker AFL: Step by Step TutorialPart 4 Plot Text in Chart Area //-----------------------------------------------------// Formula Name: Plot Text in Chart // Author/Uploader: Trading Tuitions // E-mail:
[email protected] // Website: www.tradingtuitions.com //-----------------------------------------------------_SECTION_BEGIN("Plot Text in Chart");
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Plot(Close,"Price",color=colorGreen,style=styleCandle); GfxSelectFont("Times New Roman", 30, 700, True ); GfxSetBkMode( colorWhite ); GfxSetTextColor( colorAqua ); GfxTextOut("Close Price:"+C, 900 , 15 ); _SECTION_END();
Popup Alert for Buy/Sell signal //-----------------------------------------------------// Formula Name: Popup Alert for Buy/Sell Signals // Author/Uploader: Trading Tuitions // E-mail:
[email protected] // Website: www.tradingtuitions.com //------------------------------------------------------
_SECTION_BEGIN("Popup Alert"); SetChartOptions(0,chartShowArrows | chartShowDates); _N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C )); FastEMA=Param("FastEMA",20,1,200,1); SlowEMA=Param("SlowEMA",50,1,200,1); Buy = Cross(ema( C, FastEMA ),ema( C, SlowEMA )); Sell =Cross( ema( C, SlowEMA ), ema( C, FastEMA )) ; Buy = ExRem( Buy, Sell ); Sell = ExRem( Sell, Buy ); Short = Sell;
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Cover = Buy; if (Buy[BarCount-1]==true) { PopupWindow("Your Strategy has given a Buy Signal","Buy Signal",30); } if (Sell[BarCount-1]==true) { PopupWindow("Your Strategy has given a Sell Signal","Sell Signal",30); }
Plot( Close, "Price", colorBlue, styleCandle ); Plot(ema( C, FastEMA ),"FastEMA",colorWhite); Plot(ema( C, SlowEMA ),"SlowEMA",colorBlue); /* Plot Buy and Sell Signal Arrows */ PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40); PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50); PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45); PlotShapes(IIf(Cover, shapeSquare, shapeNone),colorGreen, 0, L, Offset=40); PlotShapes(IIf(Cover, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50); PlotShapes(IIf(Cover, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=45); PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorRed, 0, H, Offset=40); PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50); PlotShapes(IIf(Sell, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=45); PlotShapes(IIf(Short, shapeSquare, shapeNone),colorRed, 0, H, Offset=40); PlotShapes(IIf(Short, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50); PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=45);
_SECTION_END();
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Plotting EMA from multiple Timeframes //-----------------------------------------------------// Formula Name: Multi Timeframe EMA // Author/Uploader: Trading Tuitions // E-mail:
[email protected] // Website: www.tradingtuitions.com //-----------------------------------------------------_SECTION_BEGIN("Multi Timeframe EMA"); SetChartOptions(0,chartShowArrows|chartShowDates); _N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C )); Plot(Close,"Price",color=colorBlue,style=styleCandle); TimeFrameSet(inWeekly); WeeklyEMA20=EMA(C,20); TimeFrameRestore(); TimeFrameSet(inDaily); DailyEMA20=EMA(C,20); TimeFrameRestore(); Plot( TimeFrameExpand( WeeklyEMA20, inWeekly), "20 Period Moving average from Weekly Chart", colorRed ); Plot( TimeFrameExpand( DailyEMA20, inDaily), "20 Period Moving average from Daily Chart", colorBlue); _SECTION_END();
http://tradingtuitions.com/category/categories/amibroker/tutorials/
This brings and end to our basic tutorial series on Amibroker formula language. Just go through the syntax carefully for each and every AFL in this and previous posts. Also try these out yourself in Amibroker. Seriously speaking this won’t make you and expert, but it will strong lay foundation which you can leverage to design complex trading systems. Going forward we’ll post AFL codes for profitable trading systems with backtest reports. Stay tuned for the same. As always, feel free to post your queries in comment box.
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Amibroker Custom Backtester: Step by Step Tutorial Posted on September 20, 2016 by admin Amibroker is one of the most versatile tools for Trading system development and testing. It has a very robust backtest and optimization engine out of the box. Additionally, it also provide custom backtester interface using which you can play around the default backtest rules and metrics. It allows customizing the operation of the backtester’s second phase which processes the trading signals. In this post, we’ll try to explore Amibroker custom backtester features and examples. You should be ready to write your own custom backtest AFL after reading this post.
Amibroker Custom Backtester model Amibroker uses object oriented model for custom backtesting. Amibroker provides a single Backtester object to perform backtests. To use the Backtester object, you first have to get a copy of it and assign that to your own variable: bo = GetBacktesterObject(); The variable “bo” is your own variable, and you can call it whatever you li ke within the naming rules of AFL. The interface also exposes the signal object, stats object and trade object, but only object directly accessible from AFL is Backtester object, all other objects are accessible by calling Backtester object methods as shown in the picture below.
Image Source: Amibroker Official Documentation Each of these objects have multiple methods which can be accesses from within the AFL code. The detailed documentation of these methods can be found here.
http://tradingtuitions.com/category/categories/amibroker/tutorials/
The Amibroker custom backtester interface provides three levels of user customization, simply called high-level, mid-level, and low-level. The high-level approach requires the least programming knowledge, and the low-level approach the most.
high-level approach (the easiest) – using Backtest() method and it runs default backtest procedure (as in old versions) – allows simple implementation of custom metrics mid-level approach – using PreProcess()/ProcessTradeSignal()/PostProcess() methods – allows to modify signals, query open positions (good for advanced posit ion sizing) low-level approach (the most complex) – using PreProcess()/EnterTrade()/ExitTrade()/ScaleTrade()/UpdateStats()/HandleStops()/Pos tProcess() methods – provides full control over entire backtest process for hard-code programmers only
Using the Amibroker custom backtester interface To use your own custom backtest procedure, you first need to tell Amibroker that you will be doing so. There are a few ways of doing this:
By setting a path to the file holding the procedure in the Automatic Analysis Settings Portfolio page. This procedure will then be used with all backtests, if the “Enable
http://tradingtuitions.com/category/categories/amibroker/tutorials/
custom
backtest
procedure”
checkbox
is
checked.
By specifying these same two settings in your AFL code using the functions SetOption(“UseCustomBacktestProc”, True) and SetCustomBacktestProc(“
”). Note that path separators inside strings need to use two backslashes, for example “c:\\AmiBroker\\Formulas\\Custom\\Backtests\\MyProc.afl”. By putting the procedure in the same file as the other AFL code and using the statement SetCustomBacktestProc(“”). This tells AmiBroker that there is a custom backtest procedure but ther e’s no path for it, because it’s in the current file. This option will be used in the examples going forward in this post.
http://tradingtuitions.com/category/categories/amibroker/tutorials/
The next thing that’s required in all backtest procedures is to ensure the procedure only runs during the second phase of the backtest. That’s achieved with the following conditional statement: if { . }
(Status(“action”)
==
.
actionPortfolio) .
.
And finally, before anything else can be done, a copy of the Backtester object is needed: bo = GetBacktesterObject();
So all custom backtest procedures, where they’re in the same file as the other AFL code, will have a template like this: SetCustomBacktestProc(“”); if (Status(“action”) { bo = // Rest of }
==
actionPortfolio)
procedure
GetBacktesterObject(); goes here
Amibroker Custom Backtester Examples Example 1: Profit/Loss percentage for individual symbols in portfolio backtest This AFL will calculate Profit/Loss % for each individual scrip in Portfolio Backtesting. This can help to determine on which securities the trading system works well, and on which securities it doesn’t. function ProcessTrade( trade ) { global tradedSymbols; symbol = trade.Symbol; // if( ! StrFind( tradedSymbols, "," + symbol + "," ) ) { tradedSymbols += symbol + ","; } // // HINT: you may replace it with GetPercentProfit if you wish profit = trade.GetPercentProfit (); // if( trade.IsLong() ) { varname = "long_" + symbol; VarSet( varname, Nz( VarGet( varname ) ) + profit ); } else { varname = "short_" + symbol; VarSet( varname, Nz( VarGet( varname ) ) + profit );
http://tradingtuitions.com/category/categories/amibroker/tutorials/
} } // SetCustomBacktestProc( "" ); // /* Now custom-backtest procedure follows */ // if ( Status( "action" ) == actionPortfolio ) { bo = GetBacktesterObject(); // bo.Backtest(); // run default backtest procedure // tradedSymbols = ","; // //iterate through closed trades for ( trade = bo.GetFirstTrade( ); trade; trade = bo.GetNextTrade( ) ) { ProcessTrade( trade ); } // //iterate through open positions for ( trade = bo.GetFirstOpenPos( ); trade; trade = bo.GetNextOpenPos( ) ) { ProcessTrade( trade ); } // //iterate through the list of traded symbols and generate custom metrics for ( i = 1; ( sym = StrExtract( tradedSymbols, i ) ) != ""; i++ ) { longprofit = VarGet( "long_" + sym ); shortprofit = VarGet( "short_" + sym ); allprofit = Nz( longprofit ) + Nz( shortprofit ); // metric uses 2 decimal points and // 3 (calculate sum) as a "combine method" for walk forward out-ofsample bo.AddCustomMetric( "Profit for " + sym, allprofit, longprofit, shortprofit, 2, 3 ); } } // SetOption( "MaxOpenPositions", 10 ); // Buy = Cross( MACD(), Signal() ); Sell = Cross( Signal(), MACD() ); Short = Sell; Cover = Buy; SetPositionSize( 10, spsPercentOfEquity ) ; SetOption("InitialEquity",1000000);
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Example 2: Relative Average Profit/Loss for each trade This AFL will add a metric in the trade log which will specify for each winning trade how far above or below the average winning profit it was as a percenta ge, and similarly for each losing trade, how far above or below the average loss i t was as a percentage. For this we need the “WinnersAvgProfit” and “LosersAvgLoss” values from the Stats object, and the profit from the Trade objects for each closed trade (for this example we’ll ignore open positions). Relative loss percentages are displayed as negative numbers. SetCustomBacktestProc( "" ); if( Status( "action" ) == actionPortfolio ) { bo = GetBacktesterObject(); // Get backtester object bo.Backtest( True ); // Run backtests with no trade listing stat = bo.GetPerformanceStats( 0 ); // Get Stats object for all trades winAvgProfit = stat.GetValue( "WinnersAvgProfit" ); loseAvgLoss = stat.GetValue( "LosersAvgLoss" ); for( trade = bo.GetFirstTrade(); trade; trade = bo.GetNextTrade() ) { // Loop through all closed trades prof = trade.GetProfit(); // Get trade profit in dollars relProf = 0; // This will be profit/avgProfit as % if( prof > 0 ) // If a winner (profit > 0) relProf = prof / winAvgProfit * 100; // Profit relative to average else // Else if a loser (profit <= 0) relProf = -prof / loseAvgLoss * 100; // Loss relative to average trade.AddCustomMetric( "Rel Avg Profit%", relProf ); // Add metric } // End of for loop over all trades bo.ListTrades(); // Generate list of trades
http://tradingtuitions.com/category/categories/amibroker/tutorials/
} SetOption( "MaxOpenPositions", 10 ); // Buy = Cross( MACD(), Signal() ); Sell = Cross( Signal(), MACD() ); Short = Sell; Cover = Buy; SetPositionSize( 10, spsPercentOfEquity ) ; SetOption( "InitialEquity", 1000000 );
Liked the article? Please share it with your friends!
Walk Forward Optimization and Testing – Amibroker Tutorial Posted on August 30, 2016 by admin All amateur or professional trading system developers would be aware of Backtesting and Optimization concepts. In-fact, it is the most integral part of Algorithmic system
http://tradingtuitions.com/category/categories/amibroker/tutorials/
development. However, what most people are not aware of is how to interpret the backtesting and optimization results. This leads to a trap and people lose enough money even when the trading system was proven profitable during backtesting. Walk Forward Optimization is an important method to determine the robustness or credibility of your trading system. Like simple Optimization, it is also a process to determine the best parameters for your trading system. However, in Walk Forward Optimization the system is optimized for a particular period of data to find the best parameters, and the obtained parameters are tested on the data following that period (known as forward data). If the parameters look profitable in both the data sets, then the system is considered to be trustworthy. This process is iterated over multiple chunks of data to arrive at the best parameters. The basic purpose of Walk Forward Optimization is to avoid curve fitting in simple optimization. Check our article on Algorithmic Trading system development below: Build your own Algorithmic Trading System: Step by Step Tutorial Before doing backtesting or optimization, one needs to set up the data required which is the historical data of a specific time period. This historical data segment is divided into the following two types:
I n-Sample Data: It is a past segment of market data (historical data) reserved for testing purposes. This data is used for the initial testing and any optimization and is the original parameters of a system under test. Out-of-Sample Data: It is the reserved data set (historical data) which is not a part of the in-sample data. It is important as this ensures that the system is tested on another period of historical data not earlier thus removing any bias or influences in the checking of the system’s performance.
The process is to first develop a trading system using in-sample data and then apply the outof-sample data to the system. The results of both cases can then be compared and tested. The entire process of Wak Forward Optimization can be better understood using the below graphic:
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Graphic Source: https://www.amibroker.com/guide/h_walkforward.html Performing walk forward optimization manually would definitely be a tedious and time taking process. In order to make it easier, Amibroker has a inbuilt functionality for this.In the next section, we would go through the step by step process to perform Walk Forward Optimization.
Walk Forward Optimization in Amibroker Let’s consider a simple EMA Crossover strategy where EMA Periods need to be optimized for Daily timeframe. Below is the AFL code for this strategy: //-----------------------------------------------------// // Formula Name: Walk Forward Testing // Author/Uploader: Trading Tuitions // E-mail: [email protected] // Website: www.tradingtuitions.com //-----------------------------------------------------_SECTION_BEGIN("Walk Forward Testing"); SetChartOptions(0,chartShowArrows|chartShowDates); _N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C )); //Initial Parameters
http://tradingtuitions.com/category/categories/amibroker/tutorials/
SetTradeDelays( 1, 1, 1, 1 ); SetOption( "InitialEquity", 200000); SetOption("FuturesMode" ,True); SetOption("MinShares",1); SetOption("CommissionMode",2); SetOption("CommissionAmount",100); SetOption("AccountMargin",10); SetOption("RefreshWhenCompleted",True); SetPositionSize(150,spsShares); SetOption( "AllowPositionShrinking", True ); BuyPrice=Open; SellPrice=Open; ShortPrice=Open; CoverPrice=Open; //Parameters MALength1 = Optimize("MALength1",20,5,200,5); MALength2 = Optimize("MALength2",50,5,200,5); //Buy-Sell Logic Buy = Cross(ema( C, MALength1 ),ema( C, MALength2 )); Sell =Cross( ema( C, MALength2 ), ema( C, MALength1 )) ; Buy = ExRem( Buy, Sell ); Sell = ExRem( Sell, Buy ); Short = Sell; Cover = Buy;
_SECTION_END();
As you can observe, the default periods for slower EMA is 50, and that of faster EMA is 20. This system would be optimized for NSE:Nifty for the time span of around 16 years (From 2000 to 2016). Other required parameters for this trading system has been mentioned in the above AFL code.In the AFL, we have used a function called ‘ Optimize‘. This function instructs Amibroker that the variable needs to be optimized. Below is the signature of this function: optimize( “ Description“, default , min, max, step ); where,
Description: Parameter description that we are optimizing Default : Default Value of the parameter to be shown if plotted in chart Min : minimum value of the variable being optimized Max : maximum value of the variable being optimized Step: An interval used for increasing the value from min to max
http://tradingtuitions.com/category/categories/amibroker/tutorials/
For Walk Forward Optimization, click on the backtester settings and then click on ‘Walk Forward’. You would see the below window:
The settings in this window would be defaulted based on your data. So you actually don’t need to change anything, but still you have the liberty to do so.
Start and End dates mark initial period begin /end. This period will be moved forward by Step until the End reaches the Last date.
http://tradingtuitions.com/category/categories/amibroker/tutorials/
The Start date can move forward by step too, or can be anchored (constant) if Anchored check is on. If you mark Use today then Last date entered will be ignored and TODAY (current date) will be used instead. By default an “EASY MODE” is selected which simplifi es the process of setting up WF parameters. It assumes that Out-of-sample segment immediately follows insample segment and the length of out-of-sample segment equals to the walk-forward step You should use Easy mode (EOD) when testing on end-of-day data or Easy mode (Intraday) when testing on intraday data. The difference is that in EOD mode the END date of previous period and START date of next period are the same – thus avoiding gap between periods. Intraday mode set START date of the next period as NEXT DAY after END of previous period. That guarantees that boundary day is not counted twice when testing on intraday data. In the Advanced mode, the user has complete control over all values, to the extent that they may not constitute valid WF procedure. The “Optimization target” field defines the optimization raport COLUMN NAME that will be used for sorting results and finding the BEST one. Any built-in column can be used (as appears in the optimization output), or you can use any custom metric that you define in custom backtester. The default is CAR/MDD, you can however select any other built-in metric from the combo.
Once you defined Walk-Forward settings, please go to Automatic Analysis and press the dropdown ARROW on the Optimize button and select “Walk Forward Optimization” .This will run sequence of optimizations and backtest and the results will be displayed in the “Walk Forward” document that is open in the main application frame. The optimization process would run for few minutes or hours depending on the volume of data and number of parameters. Below is the sample result of Walk Forward Optimization:
http://tradingtuitions.com/category/categories/amibroker/tutorials/
How to interpret Optimization results?
Walk
Forward
Walk Forward Optimization results can be very useful to evaluate the reliability of your trading system. If a particular set of parameters works good in all the in-sample and out of sample data sets, then it indicates a fair possibility that the system would work in real market conditions. Walk forward test determines the optimized system performance as follows:
Was it realistic? It is considered realistic if it could fit to the entire test data (or at least to a larger segment of the test data) used. It implies that the system has the characteristics of the real time markets and is robust. Is it overfitting? If the system does not perform well using the test data and seems to fit only chance characteristics (not necessarily part of the test data), the system is considered to be overfitting. It is neither a robust nor reliable one and ought not to be used for trading.
If the results for the ‘out-of-sample’ years look good, continue the walk -forward process in real time to find the parameters to use with real money. Another advantage to this method of system development and trading is that your system will better adapt to changes in market behavior over time. Markets do change with time – we have all seen systems that have made money for several years and then simply stopped working because the markets have changed how often these changes affect the system is related to the best size for the training and outof-sample set. Find below the detailed Walk Forward Optimization results for this Moving average trading system. Walk Forward Testing Results Similar to Walk Forward Optimization, you should also perform Monte Carlo Analysis to check the robustness of your trading system. Check out the below article t o understand it:
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Build your own Algorithmic Trading System: Step by Step Tutorial- Part 1 Posted on July 26, 2016 by admin
This is a follow up article on our Introductory post Algorithmic Trading 101. I hope you understood the basic concepts of Algorithmic Trading and its benefits. Now, let’s gear up to build your own Trading system from scratch. This article would describe every step needed to create your first Algorithmic Trading system. We shall use our favorite tool Amibroker to create Trading Algorithm.
Pre-requisites:
Elementary knowledge of Technical Analysis. Hands on experience in Amibroker and AFL Coding.
Check out our Amibroker tutorial series here.
Step 1: Formulate your Trading Plan The very first step would be to make a checklist of the parameters based on which you take your Trading decisions. These parameters should be something that can be formulated into an Algorithm, strictly avoiding elements of Gut feeling or speculation. It can be as simple as time based decisions like buying a a particular stock on the first day of every month, or decisions based on technical analysis like Trendline breakout with increasing volume. You should also plan your investment amount for each transaction, timeframe for trading, as well as your stoploss and targets. Once you have formulated your plan you should validate it against a bunch of stocks to see if it really works. This step is very important before you jump into the next steps. If your plan works for 50% of time, with a Risk-Reward ratio of atleast 1:2, then you are good to convert it into an Algorithm.
Step 2: Convert Algorithm
your
idea
into
an
Next, you should start writing a code for your formulated trading plan. A code is nothing but a bunch of statements through which computer can understand your Buy/Sell logic. We would use Amibroker Formula Language (AFL) for writing Trading Algorithm. It’s a high level programming language and very easy to understand if you start from basics. Even a person from non-programming background can learn AFL and avoid spending unnecessary on expensive ready-made AFL’s. Check this post for AFL tutorial from scratch. Let’s suppose you trade based on exponential moving average crossover in daily timeframe. You would buy a stock when 50 EMA crosses 200 EMA from below, and sell when 50 EMA crosses 200 EMA from above. For the sake of simplicity let’s consider it is a Buy only strategy. Below is the simple AFL code for this logic.
http://tradingtuitions.com/category/categories/amibroker/tutorials/
_SECTION_BEGIN("Simple Algorithmic Trading System"); //Parameters MALength1 = 50; MALength2 = 200; //Buy-Sell Logic Buy = Cross(ema( C, MALength1 ),ema( C, MALength2 )); Sell =Cross( ema( C, MALength2 ), ema( C, MALength1 )) ; Buy = ExRem( Buy, Sell ); Sell = ExRem( Sell, Buy ); Plot( Close, "Price", colorWhite, styleCandle ); Plot(ema( C, MALength1 ),"FastEMA",colorWhite); Plot(ema( C, MALength2 ),"SlowEMA",colorBlue); _SECTION_END();
This is how it looks like when applied in the chart:
Step 3: Backtest your Algorithm Backtesting is a process to validate the performance of your Algorithm on Historical Data. This is something similar to what you did in Step 1 manually. Amibroker has a very powerful backtest engine that can do this in seconds. You just need to import Historical data of your favorite scrips into Amibroker. Check out this link to download Intraday 1 minute data for Nifty and Banknifty. In order to understand t he detailed process of backtesting in Amibroker, please refer to the below link from official documentation:
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Backtesting your Trading ideas in Amibroker To backtest this EMA Crossover strategy, we will use NSE Nifty as our preferred scrip, with the initial capital of 200000 Rupees. Let’s say we buy 2 Lots(150 nos) per transaction. Once you backtest this strategy you will get a detailed report which includes your Annual CAGR, Drawdown, Net Profit/Loss% etc. You can understand various parameters in Amibroker Backtest report here. See below the summary of our initial backtest:
Value Parameter Nifty Initial Capital
200000
Final Capital
1037655
Backtest Period
26-Mar-2002 to 23-July-2016
Net Profit %
418.83%
Annual Return %
10.45%
Number of Trades
11
Winning Trade %
54.55%
Average holding Period
227.91 days
Max consecutive losses
2
Max system % drawdown
-33.24%
Max Trade % drawdown
-29.94%
Well, this is not bad, but there are still scopes of improvement. Drawdown is on a little higher side which can put retail investors in trouble.
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Build your own Algorithmic Trading System: Step by Step Tutorial- Part 2 Posted on July 26, 2016 by admin
This is the continuation to our previous post on Algorithmic Trading System development. If you have missed reading it, refer the below post: Build your own Algorithmic Trading System: Step by Step Tutorial- Part 1
Step 4: Optimize Parameters
your
Algorithm
Optimization is the process of iteratively finding the best parameters for your Trading System. For ex: in our example we have used 50 and 200 as the EMA periods, now we would try to optimize these parameters to see if there is any other Moving average combination which can give better results with least drawdowns. You need not to input these parameters manually and record backtest results. Amibroker optimization engine would make this task simpler for your. It will iterate through the range of parameters you specify and evaluate your system performance for each set of parameters. To understand Optimization process in detail, go through the below link from the official documentation: Amibroker Optimization Guide We’ll add below two lines in our AFL code MALength1 = Optimize("MALength1",50,5,150,5); MALength2 = Optimize("MALength2",200,10,200,10);
Here we have used a function called ‘Optimize‘. This function instructs Amibroker that the variable needs to be optimized. Below is the signature of this function: optimize( “ Description“, default , min, max, step ); where,
Description: Parameter description that we are optimizing Default : Default Value of the parameter to be shown if plotted in chart Min : minimum value of the variable being optimized Max : maximum value of the variable being optimized Step: An interval used for increasing the value from min to max
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Go to Analysis – >Optimize. Make sure that your AFL file is selected in the Optimization window. This process can take few minutes depending on the amount of Historical data. Once Optimization is completed, Amibroker would display the detailed results automatically sorted from best to worst. Below is the snapshot of Optimization result:
Clearly 5/30 combination of EMA’s gives the best results with minimum drawdowns. Net profit has increased from 418% to 585%, also drawdown has decreased from 29% to 13%. You should try the same combination on different symbols and time-frames t o see how robust is your Trading system.
Step 5: Risk Management It’s not enough to build a successful Trading system which gives decent results. You definitely need to incorporate Risk Management which would help you overcome unpredictable market risks. Check out our blog post which outlines the detailed Risk Management strategies for Traders: Risk Management strategies for Traders You might have noticed that the simple Algorithmic system we have developed does not have any Stop loss component. All the long positions are squared off based on the Sell signal. Let’s try to add Stop Loss in this system. Add the below piece of line in your code:
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Stoploss=2; ApplyStop(Type=0,Mode=1,Amount=StopLoss);
ApplyStop is a Function which instructs Amibroker to exit the trade when a predefined Stoploss or Target condition is met. Below is the signature of this function. ApplyStop( type, mode, amount)
type 0 = stopTypeLoss – 1 = stopTypeProfit – 2 = stopTypeTrailing 3 = stopTypeNBar – N-bar stop
maximum profit –
loss target trailing
= stop, stop, stop,
mode = 0 – disable stop (stopModeDisable), 1 – amount in percent (stopModePercent), or number of bars for N-bar stop (stopModeBars), 2 – amount in points (stopModePoint); 3 – amount in percent of profit (risk) amount percent/point loss/profit trigger/risk This could be a number (static stop level) or an array (dynamic stop level)
= amount.
Step 6: Monte Carlo Analysis Monte Carlo simulation is one of the most important steps in Trading system development and optimization. s a process which performs repeated execution of pre-defined set of steps by adding randomness to the input parameters at e ach iteration. The results are noted down at the end of each iteration which forms the basis of probabilistic analysis of the desired result. In Trading terms, Monte Carlo simulation is performed to forecast the success of a backtested trading system. In order to ensure that your trading system is robust, backtesting should be performed multiple times by adding variations to your trading rules or data. If it gives consistent result each time, then it has a higher probability of generating profit. The below post explains the detailed process of performing Monte Carlo Analysis in Amibroker: Monte Carlo Analysis in Amibroker See the snapshot of Monte Carlo Analysis report for our example Trading System:
It is a well-known fact that ‘Markets are Random’, so Monte Carlo simulation is a method to absorb this randomness in your Trading system. If your system performs well in random market conditions, then it has a huge probability of success. At the end, everything boils down to probability and that is actually the basis of all profitable Trading systems. It’s really not enough to believe in the Trading system just based on profitable backtest reports. Monte Carlo analysis weighs equally while designing a system.
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Step 7: Automate your Trading System We strictly recommend that you should trade manually for at-least 6 months before you go for fully automated trading. Once you have full conviction on the performance of your Trading System, you should start exploring automation. Automatic or semi-automatic trading do not let emotions affect your trading decisions, it directly places the order in terminal when your strategy gives signals. There are many ready-made plugins and softwares available in market which can interpret buy/sell orders from Amibroker and place it into your Trading terminal. Check out the below post for list of such softwares: Auto Trading Softwares and Plugins In order to completely automate your strategy, you will need a dealer terminal. Exchanges don’t allow completely automated platform on a retail terminal.To get a dealer terminal for NSE/BSE Segments, you will need to become an authorized person with your broker and also clear the NISM-Series-VIII – Equity Derivatives Certification Examination.Whereas there is no such procedure for MCX. There will be a one time cost to register as an Authorized person(need to check with your broker) and a rental for dealer terminal of Rs 250/segment/exchange.
Step 8: Observe the performance So you have developed your system, convinced with its performance an/or automated it. Unfortunately the story doesn’t end here. The markets are always changing, and so should your strategy. You have to observe you system performance regularly and note down anything that doesn’t happen as expected. Always remember that you would never be able to devise a holy grail system that performs in all market conditions. Download the example AFL Trading system that we discussed throughout this article in the below link: Simple Algorithmic Trading System Liked the article? Please share it with your friends!
Automate Backtesting in Amibroker Posted on June 2, 2016 by admin
Backtesting is the most integral part of any Trading system development. While developing any trading system from scratch, we have to perform several iterations of backtesting to arrive at the most optimized parameters. Also, to ensure stability of the system we have to repeatedly perform backtesting on different securities in different timeframes. This consumes lot of time and effort on an whole. In order to make this process simpler, Amibroker has provided OLE Automation interface using which external applications can access various
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Amibroker functionalities like backtest, optimization, data import etc. In this post, we will understand how to make use of this interface to automate Backtesting in Amibroker.
Prerequisites for this tutorial
Basic understanding of Amibroker and AFL .Read here if you are an absolute beginner. Access to any basic Trading system developed in Amibroker. Find the list of Trading systems here. Exposure to scripting languages like JScript or VB Scr ipt
Steps to Amibroker
automate
Backtesting
in
Step 1 Open Amibroker and goto menu item Analysis – >New Analysis. Load your AFL formula in the analysis window and make sure that the backtest settings are proper.
Step 2 Goto File –>Save. Provide a name to this Analysis Project. For illustration let’s say it is default.apx
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Step 3 Open Notepad and paste the following code: AB = new ActiveXObject( "Broker.Application" ); // creates AmiBroker object
try { NewA = AB.AnalysisDocs.Open( "D:\\Analysis Projects\\Default.apx" ); // Give path of the location where you saved APX file // NewA represents the instance of New Analysis document/window
if ( NewA ) { NewA.Run( 2 ); // start backtest asynchronously
http://tradingtuitions.com/category/categories/amibroker/tutorials/
while ( NewA.IsBusy ) WScript.Sleep( 500 ); // check IsBusy every 0.5 second
NewA.Export( "D:\\Analysis Projects\\test.csv" ); // export result list to CSV file in the given path
WScript.echo( "Completed" );
NewA.Close(); // close new Analysis } } catch ( err ) { WScript.echo( "Exception: " + err.message ); // display error that may occur }
Step 4 Save this file in “.JS” extension and then execute it using one of the below options. It’s not neccessary that Amibroker is open before executing this file. Option 1: Simply double click on the file (You need to have Administrator rights) Option 2: Goto Command Prompt. Type the JS file name and press enter (You should be in the same path where JS file is stored)
Either of the two options above will automatically call Amibroker backtest engine and save the backtest results in the CSV file in the path provided. You will get a confirmation message once it is completed successfully. To verify, go and check for “Test.CSV” file in the location provided.
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Step 5 You can even open the APX file in Notepad (saved in Step 2) and manually change the AFL name and code. Also,you can automate Optimization by adding a line NewA.Run( 4 ) in the JS file . The Optimization results can also be saved as CSV file. This is a very basic yet important script for Automating backtest in Amibroker. You can play with the JS code to do wonders. Try adding a loop to backtest multiple securities in different timeframes. Or try optimizing a strategy in different date ranges. Let us know if you have any million dollar idea which would make this automation more useful for Trading system development.
Understanding Amibroker Backtest Report Posted on February 27, 2016 by admin
For successful trading system development, it’s very important to understand and analyze backtest reports. Beginners often overlook this fact as they find it very difficult to comprehend financial and mathematical terms in these reports. This post will try to simplify this task of understanding backtest reports. We’ll consider Amibroker for illustration purpose since it has one of the most powerful backtest engine. However, most of the parameters in these reports are same across different trading platforms. Please download our sample backtest report from the below link. Sample Backtest Report Let’s explore some of the most common and important parameters present in this report:
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Initial Capital Starting capital at the beginning of backtest period.
Ending Capital Capital at the end of backtest period.
Net Profit Ending Capital-Initial Capital
Net Profit % Net Profit expressed in % terms. For ex: if Initial Capital=100000, Ending Capital=200000, then, Net Profit %=(200000-100000)/100000*100= 100%.
Exposure % It is the net average exposure of your trading system for the period of backtesting. It is calculated as the sum of individual bar exposures divided by total number of bars. Individual bar exposure is calculated as the ratio of open positions value to the overall portfolio equity for that particular bar. Let’s suppose you are backtesting your strategy on daily timeframe, if at the end of Day 1 your open position value is 10000 and portfolio equity is 100000 then bar exposure for that particular day is 10.
Net Risk Adjusted Return % It is the ratio of Net Profit % and Exposure %. For ex: If net profit %=100 and Exposure %=10, then Net Risk Adjusted Return %=100/0.1=1000
Annual Return % It is the compounded annual return %. It is the annualized rate at which capital has compounded over the backtest period.
Risk Adjusted Return % It is the ratio of Annual return % and Exposure %. For ex: If Annual return %=20 and Exposure %=10, then Net Risk Adjusted Return %=20/0.1=200
All Trades
http://tradingtuitions.com/category/categories/amibroker/tutorials/
Total number of trades executed as per the backtested strategy in specified period.
Winners Total number of winning trades.
Losers Total Number of losing trades.
Total Transaction costs Total Transaction costs based on brokerage per trade settings. For Ex: If Total number of Trades=100, and Brokerage per Trade=50, then Total Transaction costs=100*50=5000
Average Profit It’s the ratio of total profit and number of winners. For Ex: if total profit=200000, number of winners=50, then Average Profit=200000/50=4000
Average Loss It’s the ratio of total loss and number of losers. For Ex: if total loss=-100000, number of losers=50, then Average Loss=-100000/50=-2000
Average Profit/Loss Also known as Expectancy, It’s calculated as (Total Profit+ Total Loss)/(Number of trades). It represents expected gain/loss per trade. For Ex: If Total Profit=200000, Total Loss=-100000, Number of trades=100, then Expectancy=(200000-100000)/100=1000
Average Bars Held Average holding period per trade. If you are backtesting on Daily timeframe, then this represents the average number of days a Trade is held.
Max. Consecutive Winners This represents the maximum number of consecutive wins in the whole backtest period. High value is better
Max. Consecutive Loses
http://tradingtuitions.com/category/categories/amibroker/tutorials/
This represents the maximum number of consecutive losses in the whole backtest period. Low value is better.
Maximum trade drawdown The largest peak to valley decline experienced in any single trade. The lower the better.
Maximum trade % drawdown The largest peak to valley percentage decline experienced in any single trade. The lower the better.
Maximum system drawdown The largest peak to valley decline experienced in portfolio equity. The lower the better.
Maximum system % drawdown The largest peak to valley percentage decline experienced in portfolio equity. The lower the better.
Recovery Factor It is the ratio of net Profit and maximum system drawdown. Higher the better. For Ex: If net Profit=100000, maximum system drwadoen=50000, the Recovery Factor=100000/50000=2
CAR/MaxDD Compound Annual % Return divided by Maximum system % drawdown. Good if bigger than 2. For Ex: If Annual Return %=30, and Maximum system % drawdown=10, then CAR/MaxDD=30/10=3
RAR/MaxDD Risk adjusted return divided by Maximum system % drawdown. Good if bigger than 2. For Ex: If Risk adjusted Return %=50, and Maximum system % drawdown=10, then CAR/MaxDD=50/10=5
Profit Factor Ratio of Total profit and Total Loss. Higher the better. For ex: if Total profit=200000, Total loss=100000, then Profit Factor=200000/100000=2