ab back tester basics

Upload: tungkanguru

Post on 06-Apr-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 AB Back Tester Basics

    1/27

    Page 1 of 27

    Amibroker Backtester

    Personal ramblings, muses, tips and notes on becoming familiar with the AmibrokerBacktester

    This document is a personal aide de memoire and not designed to replace the User Manual or Help files which can be consulted at alltimes. No attempt has been made to be exhaustive or complete

    Abbreviations: AA = Automatic Analysis; AB = Amibroker; AFL = Amibroker Formula Language; CCY1 = First Currencyof Pair; CCY2 = Second Currency of a Pair; FX = Foreign Exchange; GUI = Graphic User Interface; PnL = Profit and Loss;TJ = Tomasz Janeczko, creator of Amibroker; USD = United States Dollar

    Introduction

    In attempt to get to gr ips w ith what the backtester does, and how it does i t , Ihave recorded some notes here together in one document for futurereference, which may be of use to others.

    Having done this I am at last somewhat more comfortable with the prospectof making some sense of results of backtests , rather than just running somebuy and sel l condit ions and wondering i f I could bel ieve the results , notbecause of any fault of Amibroker, but through ignorance on my own part asto how I could contro l what was happening under the bonnet as i t were.

    This document is a imed at being one stop shop for me to come back to anyt ime in the future, and may be of some use to other people new to theAmibroker backtester.

    I make no attempt to get involved wi th more advanced concepts such as theCustom Backtester interface, which has been covered elsewhere, rotat ionaltrading ( fund switching) and no attempt at system creat ion or moneymanagement.

    GETTING STARTED

    When we just enter some s imple code into the AA window:

    Buy = Cross( Close, EMA(Close,45));Sell = Cross( EMA(Close, 45), Close);

    and then c l ick Back Test we should e xpect to get some results .

    Therefore F IRST basic issue is we NEED buy and sel l condit ions, and thebacktester should run. I f i t does not run, there are other issues in thesett ings or AFL that are incorrect , such as i nsuff ic ient funds, too big aposit ion s ize, or not enough information for AFL to use in i ts calculat ions. Adiscuss ion of these fo l lows.

    For FX there are specif ic sett ings, which we wi l l d iscuss later in the Forexsect ion.

    SETTINGS CONUNDRUMS

    We can backtest in one of three ways:

    one t icker at a t ime: Just select Apply to Current Symbol

    or do an individual Backtest which can be run on a watch l i st or the wholedatabase. This runs the buy sel l code per t icker, i .e . i t runs through T icker#1and appl ies a l l the buy sel l s ignals , then moves to T icker#2 and so on. This

    can be useful to see which T icker a given set of Buy Sel l s ignals works bestfor.

  • 8/3/2019 AB Back Tester Basics

    2/27

    Page 2 of 27

    Or we can do a Port fo l io backtest which emulates real t rading condit ionsmore accurately. Here AB looks at a l l the t ickers i n the Watch l ist and basesentr ies and exits not only according to coded buy/sel l s ignals but a lsoaccording to other rules (such as Money Management rules, and PreferredT icker f i l ter) . So for example we can te l l AB to only use a given percent of capita l per trade, we can l imit the number of open posit ions, and so on. Moreimportant ly, to make the best use of the Port fo l io backtester we can te l l AB

    which t icker to select i f there are more than one buy candidates, based onuser preferences. So i f there are 10 Buy candidates, but only enough fundsfor two, which should AB choose? This is set with Posit ionScore. ( I f this is notset , then AB just chooses the avai lable t ickers a lphabet ical ly) . This funct ioncan be used for example to te l l AB to select in order of lower pr iced t ickers,or volume or volat i l i ty etc.

    Port fo l io level backtest ing therefore refers to posit ion s iz ing based on thecurrent equity value of your account.

    We can trade more than one t icker at a t ime.

    To ef fect this in Amibroker we need to def ine TWO things:a. the maximum number of open posit ions. MaxOpenPosit ions in the AFL

    overr ides the SETTINGS GUI b. the Posit ionSize variable in the AFL

    If we set Current Symbol in Automatic Analys is then Individual backtest givesthe same results as Port fo l io level backtester.

    I f we select Al l Symbols or Use F i l ter select ion, then Backtest by default isport fo l io level one. Else i f we c l ick I ndividual backtest i t goes through eacht icker one by one.

    So for most purposes we should just use the Back Test button, which defaultsto Port fo l io level backtest ing, and we need to set the rules up correct ly. I f weare trading Current symbol i t w i l l default to the current symbol.

    AFL SETTINGS

    Let us go through the avai lable backtest sett ings and see what we can dowith them.

    The sett ings can be placed in one of a number of places.

    1. The Backtest Sett ings GUI window. (Go to Analys is , Automatic Analys is ,Sett ings)

    2. The AFL code used for the Backtest (Enter code into the AFL editor)3. Specif ic data re lated to the T icker i nvolved, as def ined in Symbol,Information

    menu.

    Some sett ings can only be set in AFL.Some sett ings can only be set in the Sett ings window.Some can be set in AFL and the Sett ings window.Some can be set in AFL and Information window.Some can be set in AFL and Information window and the Sett ings window.

    In addit ion, once we have run a backtest we can view the trades in theResults part of the AA, but we can a lso view the sett ings we used, by c l ickingthe Report , Sett ings l ink. These are saved with the report in the directoryProgram Fi les\Amibroker\Reports and can be viewed from Report , View Last Report or Report , Report

  • 8/3/2019 AB Back Tester Basics

    3/27

    Page 3 of 27

    Explorer.

    Note, however, that not a l l o f the sett ings are stored i n this Report Sett ingslocat ion.

    Let s go through some (most) of the sett ings one by one and then create asummary table.

    SetFormulaName("TemplateBTShares");//can be any length but no punctuation is to be included. This helps to identify systems orversions of systems, for easy reference when you review them later.

    SetBackTestMode(Regular);// use this for most backtests, this is the default: redundant signals are removed.

    Timeframeset(InDaily);// does not override the Settings Inweekly.// SO THE TIMEFRAMESET HAS TO BE SET IN THE SETTINGS WINDOW and is not something wecan// code for in the AFL.

    TWOULD BE GOOD TO HAVE THE ABILITY TO SET THIS IN THE AFL.

    BUT: This cannot be done from AFL: see TJs response in post #114929 of the Yahoo GroupsAmibroker user group.

    SetOption(InitialEquity,10000);// this OVERRIDES the Settings value. We have to have this defined in one of these// places. AB looks for this First in the Backtester SETTINGS Graphics User Interface (GUI)// then looks for it in the AFL code. It gives precedence to the setting in the AFL code. Althoughthe// advice given by TJ in the past is to set this to the same value in both places, in my testing theAFL setting// is given predominance.

    SetOption(InterestRate,0);// Set this to zero to show only the results of the actual trades and not interest accrued,// to accurately assess your system.

    SetBarsRequired(10000,0);// According to TJ this is only needed if you use dll files or other script.// If you only use pure AFL this is not needed.// Note also that the first figure references past bars.// the second parameter references future bars so if this is greater than zero, we will get aCheck:// references future bars error.// therefore the second parameter needs to be set to zero.

    SetOption(CommissionMode,0);// exactly equal to, but OVERRIDES, the Settings Value

    SetOption(CommissionAmount, 15);// exactly equal to, but OVERRIDES, the Settings value

    SetTradeDelays(1,1,0,0);// or whatever settings we need: These OVERRIDE the Settings tab

    PositionSize = 1000;// does not appear in Settings GUI. Therefore must be set in AFL. If not defined in AFL

    // then full equity is used for each trade.

    SetPositionSize(value , method);// replaces the above with more advanced features. See the help files.

  • 8/3/2019 AB Back Tester Basics

    4/27

    Page 4 of 27

    setOptions(MaxOpenPositions,3);// changing this on its own makes no difference to the trade results. This must be used inconjunction with// PositionSize. The AFL OVERRIDES the Settings window value.// Only works with portfolio level Backtester if we choose Apply to All symbols, or Use Filter, i.e.not if we

    // only select one symbol.SetOption("MinShares",1);// overrides SETTINGS: defines minimal number of shares that can be bought

    SetOption("MinPosValue", 500);// overrides SETTINGS: defines minimal dollar value of desired position

    SetOption("UsePrevBarEquityForPosSizing",True);// Set to False to use current equity for Position Sizing. AFL overrides SETTINGS.

    SetOption(AllowSameBarExit,True);// AFL overrides SETTINGS.

    SetOption(PriceBoundChecking,True);// Can only be set in AFL. Leave True. Dont see any reason at the moment// to set this to false, but I am sure others may see a need for this.

    SetOption(PortfolioReportMode,0);// defaults to the Trade list, I see no reason at present to change this.// AFL setting OVERRRIDES the Settings in GUI.

    RoundLotSize =1;// As per help files use 1 for shares and futures, or use fractions for mutual funds.// Per symbol setting overrides global values in SETTINGS GUI// AFL overrides SETTINGS.

    // 1 is needed for shares to ensure we do not buy fractional shares.// if we want to buy shares in parcels of multiples of 10, set this 10.// if we want to buy shares in multiples of 100, we set this 100 and so on.// if we set this 0 (zero) backtester will buy fractions of shares.

    TickSize = 0.01;// TickSize is a special case. Settings can be made Globally (in SETTINGS) or per symbol, but donot override// the BuyPrice or SellPrice arrays. Mainly of use therefore in conjunction with Applystops tomake sure// entries and exits take place at allowed true prices and not fictitious calculated levels. If we donot use// Applystops, we should not need to specify TickSize.// See also TickSize under the Forex section for further details.

    SetOption(FuturesMode,0);// needs to be False for shares, and set to True for Futures and Forex backtesting// We need to set this in SETTINGS GUI.// This setting is not entirely consistent with the rules of AFL overriding most of the settings.The only// correct place to set this is in the SETTINGS GUI. This controls the column title (Contracts orShares) and// the way the profit is calculated. If we use the AFL to set this to ON, then for Shares databaseand shares// code, it will change the way the calculation is done but will not change the Column header

    from Shares// to Contracts.// Advice: Do not try and set this in the AFL. If we are to use the SetOption(FuturesMode, ..);in AFL we

  • 8/3/2019 AB Back Tester Basics

    5/27

  • 8/3/2019 AB Back Tester Basics

    6/27

    Page 6 of 27

    this takesprecedenceover the othertwo

    Settings

    CommissionMode AB looks atSettings first

    N/a Then AB looksfor AFL value

    Given toAFL value

    FormulaandSettings

    CommissionAmount AB looks at

    Settings first

    N/a Then AB looks

    for AFL value.

    Given to

    the AFLvalue

    Formula

    andSettings

    SetTradeDelays AB looks atSettings first

    N/a Then AB looksfor AFL value

    Given tothe AFLvalue

    FormulaandSettings

    MaxOpenPositions AB looks atSettings first

    N/a Then AB looksfor AFL value

    Given tothe AFLvalue

    Formulaonly

    MinShares AB looks atSettings first

    N/a Then AB looksfor AFL value

    Given tothe AFLvalue

    Formulaonly

    MinPosValue AB looks atSettings first

    N/a Then AB looksfor AFL value

    Given tothe AFLvalue

    Formulaonly

    "UsePrevBarEquityForPosSizing"

    AB looks atSettings first

    N/a Then AB looksfor AFL value

    Given tothe AFLvalue

    Formulaonly

    AllowSameBarExit AB looks atSettings first

    N/a Then AB looksfor AFL value

    Given tothe AFLvalue

    Formulaonly.

    AllowPositionShrinking AB looks atSettings first

    N/a Then AB looksfor AFL value

    Given tothe AFLvalue

    Formulaonly.

    InterestRate AB looks atSettings first

    N/a Then AB looksfor AFL value

    Given tothe AFLvalue

    Formulaandsettingsbutdisplays

    the valuefrom theAFL

    AccountMargin AB looks atSettings first

    N/a Then AB looksfor AFL value

    Given tothe AFLvalue

    Formula.The AFLvalue isshown inReportSettings.

    MarginDeposit = N/a Symbol Info Then AB looksfor AFL value

    Given tothe AFLvalue

    Formula

    RoundLotsize = AB looks atSettings first

    Then it looksat Per symbol

    info

    Then AB looksfor AFL value

    Given tothe AFL

    value

    Settings(can be

    wrongvalue ifoverridden by) AFLvalue inFormulas

    PortfolioReportMode AB looks atSettingsFirst

    N/a Then looks forAFL value

    Given tothe AFLvalue

    Only inFormula

    FuturesMode

    Special case: Set inSETTINGS alone OR in bothSETTINGS and AFL must

    match.

    AB looks insettings first

    N/a Then looks toAFL

    Calculations givenpreferenceto the AFLvalue

    InFormula+ also inSettings.

    Ticksize AB lookshere first.

    This is a

    Then AB lookshere. If setthis overrides

    Then AB lookshere

    Given tothe AFLvalue for

    InFormula.Settings

  • 8/3/2019 AB Back Tester Basics

    7/27

    Page 7 of 27

    globaldefaultvalue

    the Globalvalue

    calculations only readfrom theGlobalvalue.

    Table 2.

    Sett ings that can NOT be set in AFL

    These can NOT be set in AFL Can be set in AFL ? Set WherePeriodicity No SETTINGS GUIPositions: Long or Short No SETTINGS GUI

    Table 3.

    Posit ions Long or Short does not have an AFL switch but is obviouslycontro l led by the Buy and Sel l rules. However i f you have Long and Shortcondit ions in your code, you need to go to Sett ings and Select Posit ions,Long, Short or Long and Short . That way you can separate out the two toassess the results of the Long trades and Short trades i ndependent ly.

    So for a l l Backtests there wi l l be some sett ings that need to be set v ia theSETTINGS GUI and some that can be set with the AFL.

    The last thing to be said about these is that i f need be we can create anexplorat ion to display a l l of these sett ings us ing the GetOpt ion funct ion e.g.

    Addcolumn(GetOpt ion(MinPosValue) ,MinPos,6.0) ;

    Controls over ENTRIES

    Entr ies depend on the Buy condit ions and are coded up in AFL in the AAwindow.This document does not cover AFL or system design and so no more wi l l besaid here.

    Controls over the EXITS

    We can contro l our exits in one of two ways.

    1. We can use the Sel l Condit ion as coded in AFL2. In addit ion, AB provides us more f lexibi l i ty in sett ing the exits by use of stops.

    There are in-bui l t stops which we can set v ia the Sett ings GUI and there

    areApplystops which we code up in AFL. They perform the same task.

    F IRST, we can use the bui l t - in stops from the GUI in the Backtester Sett ings.These are sel f explanatory and can be looked up in the help f i les .These values wi l l show up in the Backtester report page for Sett ings.

    SECOND, we can use the Applystops in the actual AFL, which gives us theabi l i ty to use Param and Opt imize funct ions on these.

    [Note that a lthough these values work in the Backtester, and they overr idethe values set in the SETTINGS window, they do NOT show up correct ly in theRecords, Sett ings page, or at least I have not found a way to get them to do

    that.

    In addit ion the sett ing for StopTypeNBar does not appear in the Report ,

  • 8/3/2019 AB Back Tester Basics

    8/27

    Page 8 of 27

    Sett ings l ink.]

    Applystops

    The funct ions and commands of the Applystops can be obtained from the helpf i les .

    Moreover the pattern is the same: the AFL code for any one type of stopoverr ides the Sett ings GUI. So i f we have StopTypeLoss set in the AFL andStopTypeLoss set in the SETTINGS GUI, and no other stops, then contro l overthe exits passes to the AFL code.

    Fig 1.

    So we see that ALL the individual ApplyStop parameters in the AFL wi l loverr ide those in the SETTINGS GUI.

    From tests we can show that:

    StopTypeLoss: StopModeDisable, StopTypePercent, StopTypePoint:contro l passes to the AFL

    StopTypeLoss: Amount, ExitAtStop, and ReEntryDelay:contro l passes to the AFL

    StopTypeProf i t : StopModeDisable, StopTypePercent, StopTypePoint:

    contro l passes to the AFL

    StopTypeProf i t : Amount, ExitAtStop, and ReEntryDelay:contro l passes to the AFL

    StopTypeNBar: Amount (N-Bar exit ) and ReEntryDelay:contro l passes to the AFL.

    However, i f we have dif ferent types of stops in the SETTINGS GUI and theAFL, then whichever one gets hit f i rst wi l l be enacted by AB, s imulat ing realtrading.

    So for the s i tuat ion in F ig 2 , where we coded StopTypeLoss in both the AFL

    and SETTINGS GUI, together with N-bar stop in the SETTINGS GUI, the exit forthe StopTypeLoss is contro l led by the AFL, unless the N-bar stop gets hitf i rst , in which case this exit gets taken.

  • 8/3/2019 AB Back Tester Basics

    9/27

    Page 9 of 27

    Fig 2.

    To avoid any confusion we may choose to set the stops in e ither the AFL, orthe SETTINGS GUI. Us ing the AFL a l lows more contro l and f lexibi l i ty,especia l ly i f we are looking at Opt imiz ing the amount parameter.

    Remember to set ExitAtStop correct ly to suit your trading plan.

    [As an as ide, the Backtester Report Sett ings l ink seems to read the valuesfrom the SETTINGS table, EVEN IF they are disabled, OR i f they are enabled.So i f we need to read the ApplyStop Amounts in the Report Sett ings w indowthen we would need to have these entered in the SETTINGS window. I t wi l lnot show the AFL coded Applystops, a lthough these are the ones used by the

    backtester.]

    Sample Code

    Now that we have def ined a l l or most of the sett ings that we need to getaccurate backtest results , we can use a l l of the necessary AFL commandsbefore our actual systems code.

    This may look something l ike the fo l lowing.

    // Template BT Shares.afl// ChrisB Jan 2008// You can NOT select the Time Period here, Ya Haf Ta Go To SETTINGS.

    // SetFormulaName("SharesUnNamed");//Set this in each new backtest code: can be any// length but no punctuation

    SetBacktestMode(backtestRegular);// removes redundant signals

  • 8/3/2019 AB Back Tester Basics

    10/27

    Page 10 of 27

    SetBarsRequired(10000,0);// only needed if you use dlls or external scriptSetOption("InitialEquity",10000);//overrides SETTINGSSetOption("CommissionMode",2);//overrides SETTINGS //0 = Commision Table ; 1 = percent ; 2 = $ per trade; 3 = $ per share/contractSetOption("CommissionAmount",19.95);//overrides SETTINGS; used dollar value for Shares.SetTradeDelays(1,1,0,0);//overrides SETTINGSPositionSize = 1000;// POSITIVE = dollars; NEGATIVE = Percent // CANNOT be set in SETTINGSRoundLotSize = 1;// overrides SETTINGS; use default of 1 for shares.SetOption("MaxOpenPositions", 3);//Must be used with PositionSize. //overrides the SETTINGS //only works for Portfolio level testing with > 1 symbolSetOption("MinShares",1);//overrides SETTINGS; defines minimal shares to be boughtSetOption("MinPosValue", 500);//overrides SETTINGSSetOption("AllowPositionShrinking", True); //in case there is not enough cashSetOption("UsePrevBarEquityForPosSizing",True);// False to use current equity for Pos SizingSetOption("PriceBoundChecking",True);// Always set to True.SetOption("AccountMargin",100);//100 = no margin for shares; 50 = for 50% margin

    //NOT the same as MarginDeposit for futures.SetOption("HoldMinBars",0);// disables exits for this number of barsSetOption("HoldMinDays",0);// disables exits for this number of Calendar days//exitsSetOption("ReverseSignalForcesExit",False);//True for stop and reverse systems

    SetOption("AllowSameBarExit",True);//Use True as default, to allow thisSetOption("ActivateStopsImmediately",True);// Needed if you enter on Open. Not needed if

    // you enter on CloseSetOption("InterestRate",3.2);//Overrides SETTINGSSetOption("FuturesMode",False);//False for Shares, True for FX:

    // Set also in SETTINGS GUI.//reportsSetOption("PortfolioReportMode",0);// 0-Trade list: 1- Detailed Log; 2- Summary;

    // 3- No output

    To save t ime and coding we can save this as a Template f i le , e .g.Template_BT_Shares.af l in the chosen directory (by default C: \Program

    Fi les\Amibroker\Formulas\ Include), and then just use the fo l lowing code atthe beginning of a l l our backtest f i les

    #pragma nocache#include

    This wi l l run the above sett ings from the named f i le and then we canconcentrate only on coding up the system.

    SETTING THE PRICES AT THE BUY AND SELL

    Once we have def ined our rules for entr ies and exits , we need to te l l ABbacktester at what pr ices to open and c lose these trades.

    To do this we def ine BuyPrice, Sel lPr ice, (and ShortPr ice and CoverPrice forshort posit ions) .

    We can do this in the SETTINGS Trades Tab but a lso from the AFL.

    BuyPrice = Sel lPr ice = ShortPr ice = CoverPrice = 0pen;

    I f this is left out i t defaults to the SETTINGS values.

    Once again the AFL values OVERRIDE the SETTINGS values.

    DELAYS

    Based on our trading system we should next a im to def ine WHEN Amibrokers imulates the Buy and Sel l orders: we can do so in the SETTINGS Trades GUI,

  • 8/3/2019 AB Back Tester Basics

    11/27

  • 8/3/2019 AB Back Tester Basics

    12/27

    Page 12 of 27

    On Price charts we just need to make sure the Show trading arrows isenabled for each chart . Then run backtest , r i ght c l ick the reports l is t andselect Show Arrows.

    I f we were to add a new chart after running a Backtest , we repeat the same:just making sure that Chart has Show trading arrows enabled, go to the

    Reports l is t and select which arrows we wish to see.

    Note these above detai ls are for Buy and Sel l orders AND for exits based onthe Applystops.No extra coding is needed for AB to show an exit based on Applystops:however, the in-bui l t exit arrow in AB does not te l l us why an exit was taken,but just points to the bar where the exit occurred.

    So when we have coded exits based on one of a number of Applystops(perhaps together with a regular Sel l s ignal) these wi l l a l l be displayed asthe regular exit arrows in the Chart when we select Show Arrows for actualtrades.

    Which Exit?

    How then do we know why any one exit was taken?

    When you look at the Backtest report you can easi ly see why any oneposit ion was c losed:

    Fig 3.

    The type of stop that c losed the posit ion appears in brackets in the Tradecolumn, and is read by AB from stops set in AFL or v ia the SETTINGS GUI.

    However i f we wish to see on the charts which exit rule caused the posit ionto c lose, i .e . the regular Sel l command or which one of the ApplyStopfunct ions, then we need to use Method 2 by adding some extra code in theAFL. This is done by us ing the Equity(1) cal l and the PlotShapes funct ion.

    This is the required sequence as per T J :

    1. Buy Sel l s ignals2. Applystops as needed.3. equity(1) ;4. P lotShapes.

    The Equity(1) has the purpose of looking back at the type of exit that wastaken ,so that we can plot this on the charts us ing the PlotShapes funct ion.

  • 8/3/2019 AB Back Tester Basics

    13/27

    Page 13 of 27

    These are the rules for P lotShapes:

    PlotShapes( "reason" * shapeDownArrow, // say why to plot the shape . . .PlotShapes( "reason" * shapeDownArrow, colorRed, // set color of the shape . . .PlotShapes( "reason" * shapeDownArrow, colorRed, 0, // to the selected layer ( if weuse // a layer other than default, we should make sure we do not have that layerdisabled)PlotShapes( "reason" * shapeDownArrow, colorRed, 0, H, // position referenced to the High

    PlotShapes( "reason" * shapeDownArrow, colorRed, 0, H, -10) // 10 pixels above the High.

    Remember that to v iew the inbui l t Buy and Sel l arrows we need to Run theBacktester, have Show arrows enabled on the Chart and then Right c l ick theresults l is t and choose Display Arrows.

    Because the PlotShapes are plotted as an indicator they do so independent lyof the backtester, and can be displayed without having run the Backtest . Toget the backtest arrows to match those we have plotted however, w e shouldnot forget to run the backtest as wel l , especia l ly once we have adjusted thePlotShapes code or ApplyStop code.

    The Equity(1) funct ion l ooks at the exits based on the inbui l t stops or

    ApplyStop to see which type of stop w as used for the exit , and a l lows theseto be displayed on the chart (or in an Explorat ion) , according these rules:

    2 = StopTypeLoss3 = StopTypeProf i t4 = StopTypeTrai l ing5 = StopTypeNBar6 = Ruin stop

    Also from the help f i les , i f more than one type of stop s ignal is received onthe same bar, this is the order of precedence.

    If two or more different stops are triggered on the VERY SAME bar then they are evaluated

    in this fixed order:

    Fixed Ruin stop (loosing 99.96% of the starting capital)

    Max. loss stop

    Profit target stop

    Trailing stop

    N-bar stop

    Therefore to make things a l i t t le easier to decipher on the charts we can plotthose as actual numbers us ing the ShapeDigitx funct ion, with the codelooking l ike this :

    SetTradeDelays(0,0,0,0);Buysignal = Cross ( EMA (C,30) , Close);

    Buy = Ref (Buysignal, -1) ;

    Sellsignal = Cross ( RSI(21),56);Sell = Ref( Sellsignal,-1);

    ApplyStop ( stopTypeLoss, stopModePoint, 0.5 , 1 , 0 , 1 );// = 2ApplyStop ( stopTypeProfit, stopModePoint, 0.9 , 1 , 0 , 1 ); // = 3ApplyStop ( stopTypeTrailing, stopModePoint, 1 , 1 , 0 , 1 ); // =4ApplyStop ( stopTypeNBar, stopModeBars,10); // = 5

    Equity(1);

    Plot (C ,"" , colorBlack , 64);Plot (EMA(C,5), "ema 5", colorRed,1);Plot (EMA(C,30),"ema 30",colorBlue,1);

    Plot (EMA(C,200), "ema 50", colorGreen,1);PlotShapes ( Buysignal * shapeHollowUpArrow, colorBlue,0,L,-10);PlotShapes ( Buy * shapeSmallCircle, colorLime, 0 , BuyPrice,0);

  • 8/3/2019 AB Back Tester Basics

    14/27

    Page 14 of 27

    PlotShapes( Sellsignal * shapeHollowDownArrow, colorRed, 0 , H, -25);PlotShapes( IIf(Sell==1, shapeDigit1, shapeNone), colorRed, 0 , H, 35);PlotShapes( IIf(Sell==1, shapeSmallCircle, shapeNone) , colorRed, 0 , SellPrice, 0);

    PlotShapes( IIf(Sell==2, shapeDigit2, shapeNone) , colorRed,0,H,20);PlotShapes( IIf(Sell==2, shapeSmallCircle, shapeNone) , colorRed,0, SellPrice,0);

    PlotShapes( IIf(Sell==3, shapeDigit3, shapeNone) , colorLime,0,H,45);PlotShapes( IIf(Sell==3, shapeSmallCircle, shapeNone) , colorLime,0,SellPrice,0);

    PlotShapes( IIf(Sell==4, shapeDigit4, shapeNone) , colorGreen,0,H,50);PlotShapes( IIf(Sell==4, shapeSmallCircle, shapeNone) , colorGreen,0,SellPrice,0);

    PlotShapes( IIf(Sell==5, shapeDigit5, shapeNone) , colorBlack,0,H,38);PlotShapes( IIf(Sell==5, shapeSmallCircle, shapeNone), colorRed, 0,SellPrice,0);

    The last value in the PlotShapes funct ion refers to the of fset . For a l l p lottedshapes a posit ive value shi f ts the shape up and a negat ive value shi f ts theshape down, except for shapes with Down already in the name (such asshapeDownArrow, shapeDownTriangle etc) in which this is the other wayaround.

    As expla ined in the help f i l es , when we use shapeDownArrow we need of fsetof 30 to place the arrow above the Hi gh, but when we use ShapeDigit weneed offset of 30 to place the digit above the High.

    [See a lso Help f i les for ShapePosit ionAbove.]

  • 8/3/2019 AB Back Tester Basics

    15/27

  • 8/3/2019 AB Back Tester Basics

    16/27

    Page 16 of 27

    FOREX backtesting

    These are the settings we need to address for Forex backtesting

    1. Futures mode

    2. RoundLotSize3. MarginDeposit4. PointValue5. Position size6. TickSize

    Like the other backtest settings, we can set these in one of three places: Settings GUI for globalsettings, Symbol Information for symbol specific information or AFL.

    Note that some settings can be controlled in all three places, some in only two and some inonly one. To be sure of correct USD backtest results we need to make sure all values arecorrectly set in the AFL, the GUI SETTINGS and the information sheet. Like the other settingsthere is an order of precedence, and we can use Addcolumn in an exploration to reveal theorder of precedence by playing with the settings.

    Filter = 1;

    AddColumn ( GetOption("FuturesMode"),"FM", 1.0);AddColumn ( RoundLotSize,"RLS", 1.2);AddColumn (MarginDeposit, "Marg Dep");AddColumn ( PointValue,"Pnt Val");AddColumn ( PositionSize, "Pos Size");AddColumn ( TickSize,"ticksize",1.4);

    AB looks for these values in this order and gives precedence in ascending order like so:

    Forex settings SETTINGS GUI TICKER INFORMATION AFL Code

    Futures Mode AB looks here first N/a Set this to the same atSETTINGS GUI

    RoundLotSize Settings first Then Info sheet Then AFL dominates*MarginDeposit Not available Info sheet first Then AFL dominates*Pointvalue N/a Then info sheet Then AFL dominates*PositionSize N/a N/a AFL onlyTickSize AB looks at Settings

    first. **Then AB looks atticker specificInformation whichoverrides global value

    Then AB looks for AFLvalue*: this overridesthe other two

    Table 4.* AFL always dominates the settings placed elsewhere** This is a global setting. TickSize is better to set in AFL or in Ticker info because it varies fromcurrency to currency

    Why we need Futures specific settings

    FIRST i t is NB to understand we are not trading shares here, and we need totel l AB this , by switching Futures mode to ON. This can be done in theSett ings GUI or in the AFL.

    When we trade shares, the Backtester wi l l show a column header cal ledShares.

    When we trade futures/ forex and enable Futures mode, this co lumn headerchanges to Contracts .

  • 8/3/2019 AB Back Tester Basics

    17/27

    Page 17 of 27

    Fig 6.

    So buy paying attent ion the t i t le/header in this co lumn we can easi ly see i f we have Futures mode ON of OFF.

    So switching Future Mode ON displays the Contracts column in the Backtesterresults , which is the same as Lots in Forex.

    Fig 7.

    The other thing i t does is that i t recognizes that we are no longer deal ingwith shares where

    a. there is 1:1 re lat ionship between a 1 point move and 1 dol lar value

    b. we do not general ly use leverage to the same extent, i f at a l l .

    Therefore with Futures Mode ON we have to te l l the AB Backtester what thedol lar value of a Point move is , then we need to te l l the Backtester what our

  • 8/3/2019 AB Back Tester Basics

    18/27

    Page 18 of 27

    margin per contract is , and then we need to te l l the AB Backtester what ourPosit ion s ize is going to be.

    So when we enable Futures Mode, AB uses MarginDeposit and PointValue inthe calculat ions that i t uses to create the Report or Results . (See F ig 12) Itneeds us to te l l i t what these values are. This is because the dol lar value perpoint move wi l l vary per instrument traded, and in Forex can depend on the

    size of our Lots (regular, mini or f ract ional) . So just l ike the USD value perpip changes, so does the USD value per Point . Moreover, to compl icate thingsnote that the USD value per pip changes as the currency pr ices moves up anddown.

    In shares, a 1 point move i s a move from 12.00 USD per share to 13.00 USDper share or a move from 117.58 to 118.58 and so on. There is a l inearrelat ionship here because each dol lar has 100 cents. However, when USDJPYmoves from 119.00 to 120.00, which is a 1 point move, this is not a move of 1 dol lar. This is in fact a move of 100 pips, and the dol lar value of this movewil l depend on the USD value of each pip.

    Simi lar ly a 1 point move i n the other non- JPY pairs with t ick values of 0.0001

    comprises a move of 10,000 pips. The value of each pip wi l l then depend onthe exchange rate of the currency at the present moment, which currency wetrade in, whether we trade standard (1 00k) lots , mini lots (10k) or f ract ionsthereof .

    So i f we took one regular L ot of USDJPY (100 000 USD), with the USDJPYcurrent ly at around 109.90 each pip would be worth about 9.15 USD. I f wetake 2 lots each pip is worth 18.30 USD. Now i f we trade mini lots (10 000 of the Base currency pair) these values would be di f ferent: 0.915 USD and 1.83USD respect ively. Moreover i f our platform al lows us to trade fract ional lotse.g. 0.7 regular lots or even odd lots l ike buying 6 650 USDJPY thisintroduces more variables to the calculat ion of the PnL (Prof i t and Loss) inDol lars . So we specify this information by the PointValue, w hich can be set in

    AFL or in the Symbol, Information f ie ld.

    REPORTS in Dollars

    Remember when we look at the Reports page the value in the Prof i t co lumncan only have the correct Dol lar value i f we have the fo l lowing sett ingscorrect ly speci f ied:

    1. Futures mode ON2. Specify the Pointvalue3. MarginDeposit4. Position size5. RoundLotSize = 1; (tells AB to only take full Lots: if you have mini account or can usefractional units you may have a reason to change this)6. TickSize

    FuturesMode ON

    Best set in the SETTINGS GUI: if we want to have this in AFL then we need to ensure thismatches the GUI settings.

    PointValue: Let us quote the help f i le here with added emphasis to dr ive this

    home:

    Point-value is per-symbol setting (definable in Symbol-Information window ) that determines the

  • 8/3/2019 AB Back Tester Basics

    19/27

    Page 19 of 27

    amount of profit generated by one contract for a one point increase in price.

    This means that for Forex we need to specify the Dol lar value of a One Point

    move for One Lot .

    So for a standard 100 000 EURUSD lot this is ca lculated as fo l lows:A One Point move is f rom 1.0000 to 2.0000 EURUSDThis equals 10 000 pipsFrom our trading platform we read that one Pip = 10 USD.Therefore a one point move is calculated asPointValue = 10 000 pips * 10 dol lars per pip = 100 000 (USD) per lot.

    Current ly for a 10 000 mini lot in USDJPY the PointValue wi l l be 0.915 per lot .Therefore PointValue = 100 * 0.915 = 91.5 USD.

    As currency exchange rates change, the value of PointValue wi l l a lso s lowlychange over t ime for non US pairs . So for example i f we backtest the EURJPYover the last 4 years where the pr i ce moved from 127 to 168 us ing thePointValue for today, the backtest dol lar values may not be correct in the

    earl ier part of the test . Hence we may choose to test with results displayedin Pips.

    I f we only backtest one currency pair we can set the PointValue in the AFL.But i f we wish to test a number of currencies then we should use the Symbol,Information to set this , otherwise we would have to w rite some AFL code todetermine PointValue per t icker. This could be easi ly done with the I IF or I f funct ions or even fed in to Parameter, but i t would seem just as easy to setthis in the Information f ie ld.

    MarginDeposit

    MarginDeposit is the amount of money you need to deposit to open a trade,and wi l l be based on your account s ize, your leverage or trading platformmargin, and your Lot s ize and number of Lots .

    MarginDeposit can be set in the Symbol I nformation f ie ld, or in the AFL.The AFL sett ing takes precedence.

    So for a standard 100 000 EURUSD lot at Margin of 1% this means we wouldhave to place a deposit of 1 000 to open a 100 000 posit ion and so we wouldenter 1000 for MarginDeposit .

    Next, we have to te l l AB the ful l pos it ion s ize so i t can do the calculat ions .

    Position size

    To a l low AB to complete the calculat ions, we need to specify Posit ionSize.

    1. To start of f with we can choose to only trade in s ingle Lots. Then we justset the Posit ion s ize to the same value as the MarginDeposit : Pos it ionSize =MarginDeposit ;

    Sample code would be:

    SetOption("FuturesMode",1);SetOption("InitialEquity", 100000);RoundLotSize = 1;TickSize = IIf( StrRight( Name(),3) == "JPY", 0.01, 0.0001);

    MarginDeposit = 1000; // for example for 100:1 leverage on standard lotPointValue = 915 ;// for pairs with JPY as counter currencyPositionSize =MarginDeposit;

  • 8/3/2019 AB Back Tester Basics

    20/27

    Page 20 of 27

    The backtester wi l l then show 1 contract/Lot having been traded:

    Fig 8.

    2. I f we want to backtest with more than one lot we have two choices.

    a. We tel l AB how many Lots we want to tradeb. We tel l AB the Posit ionSize we want as percentage of Equity and let i twork out the Lots needed.c. We tel l AB the Posit ionSize we want in f ixed Dol lar amount and let i t workout the Lots needed.

    Assuming a standard 100 000 account trading standard 100k lots and 1%margin requir ing a 1 000 deposit :

    a . Tel l AB how many Lots to trade

    SetOption("FuturesMode",1);SetOption("InitialEquity", 100000);RoundLotSize = 1;TickSize = IIf( StrRight( Name(),3) == "JPY", 0.01, 0.0001);

    MarginDeposit = 1000; // for example for 100:1 leverage on standard lotPointValue = 915 ;// for pairs with JPY as counter currencyNumLots = 3;PositionSize = NumLots *MarginDeposit;

    Fig 9.

    [Or i f we wish to Opt imize the posit ion s iz ing we could use:

    NumLots = Optimize("NumLots", 1,1,10,10;PositionSize = NumLots *MarginDeposit; ]

    b. Let AB work out the required number of Lots by def ining the Posit ionSizeas percent of Equity.

    Sample code would be:

    SetOption("FuturesMode",1);SetOption("InitialEquity", 100000);RoundLotSize = 1;TickSize = IIf( StrRight( Name(),3) == "JPY", 0.01, 0.0001);

    MarginDeposit = 1000; // for example for 100:1 leverage on standard lotPointValue = 915 ;// for pairs with JPY as counter currencyPositionSize = -10; // this means 10% of equity

  • 8/3/2019 AB Back Tester Basics

    21/27

    Page 21 of 27

    Fig 10.

    AB then works out the Number of contracts as Posit ionSize / MarginDeposit .

    AB takes 10% of account, ca lculated as 0.1 * 100 000 = 10 000 as thePosit ion Size in Dol lars .AB then div ides this by the MarginDeposit : 10 000 / 1000 = 10 Lots

    Or we can use Posit ionSize = -20; / / te l ls AB to use 20% of equityPosit ion s ize wi l l be 100 000 * 0.2 = 20 000Number of contracts wi l l be 20,000 / 1000 = 20 Lots.

    As the Equity changes so wi l l the number of contracts traded.

    C. Let AB work out the Lots by def ining a f ixed dol lar amount to trade.Again i t works out the Number of contracts as Posit ionSize/MarginDeposit :

    SetOption("FuturesMode",1);SetOption("InitialEquity", 100000);RoundLotSize = 1;TickSize = IIf( StrRight( Name(),3) == "JPY", 0.01, 0.0001);

    MarginDeposit = 1000; // for example for 100:1 leverage on standard lotPointValue = 915 ;// for pairs with JPY as counter currencyPositionSize = 12000; // this means 12,000 dollar position

    Fig 11.Here we have specif iedPosit ionSize = 12 000;Number of contracts wi l l be 12 000 / MarginDeposit .So i f MarginDeposit is 1 000 then we wi l l expect to see AB open 12 Lots forus:Number of contracts = Posit ionSize/MarginDeposit

    = 12 000/ 1 000= 12 Lots

    The number of contracts traded stays f ixed as Equity changes.

    [As an as ide I have avoided us ing SetPosit ionSize in FX; I have not testedthis but somehow suspect i t internal ly looks at some of the other FX valuesand we could land up with double entr ies in the calculat ions.]

    Calculations

    Having to ld AB to use Futures Mode and having given i t the PointValue, theMarginDeposit and the Posit ionSize, the calculat ions are done as fo l lows

  • 8/3/2019 AB Back Tester Basics

    22/27

    Page 22 of 27

    Fig 12.

    TickSize

    Note that we have not speci f ied T ickSize specif ica l ly yet , and w e are st i l lgett ing correct dol lar values in the B acktester. T ickSize is not needed for thebasic PnL calculat ions, EXCEPT in two cases:F IRST where the Exit pr ice is defined by ApplyStop or in-bui l t stops, in whichcase i t appears that AB wi l l internal ly round or adjust the calculated Exit

    Pr ice to match aval id t icker speci f ic pr ice level .The SECOND reason has to do with the way we can calculate the Forexcommiss ions or spreads, which is discussed later.Therefore i t remains important that we always specify T ickSize.

    T ickSize can be set in one of three places.

    a. SETTINGS in GUIb. Symbol informationc. AFL

    The SETTINGS GUI value is the global default value which is used i f no othervalues are set , and then this value gets used for calculat ions, and i t is thisvalue which is displayed in the Backtest Report Sett ings l ink. (F ig 13)

    The Symbol Information value supersedes the Global value and is used in anyneeded calculat ions. However the Report Sett ings value is st i l l read from theGlobal Sett ingsvalue.

    I f we code up some AFL for the T ickSize then this gets given precedence forcalculat ions in the backtester. The actual value that gets used can bedisplayed with an explorat ion output. [Again the Report Sett ings l ink is of nouse in checking the sett ings of the backtest parameters, but cont inues to

    display the global value.]

  • 8/3/2019 AB Back Tester Basics

    23/27

    Page 23 of 27

    Fig 13.

    To use AFL in Backtester to set the T ickSize for Forex, we can use the I I f funct ion:

    TickSize = IIf( StrRight( Name(),3) == "JPY", 0.01, 0.0001);

    GETTING THE COMMISSION AMOUNT RIGHT IN FOREX BACKTESTING

    Having got the correct Dol lar value for the backtest results , we next need toset the correct costs/commiss ion.

    SetOpt ion(CommissionMode,3) ; / / te l ls AB to use a specif ic dol lar value percontractSetOpt ion(CommissionAmount, youramount) ; / / te l ls AB what value to usein the calculat ions.

    So i f we have one lot of 100 000 with PointValue of say 100 000, T ickSize of

    0.01 then the Commision Amount is set as

    SetOpt ion(CommissionAmount, T ickSize * Pointvalue);

    ( this is because in AB the PointValue i s the dol lar value of a s ingle pipdivided by the T ickSize:for standard lot EURUSD in USD denominated account each pip = $10, soPointValue = Dol lar value per pip / T ickSize

    = $10 / 0.0001= 100 000)

    Mult iply ing the PointValue by the T ickSize calculates the dol lar value per pip.Dif ferent currency pairs have varying spreads per Pair , ranging form 1 to say

    15 pips.

    So we need to arr ive at

  • 8/3/2019 AB Back Tester Basics

    24/27

    Page 24 of 27

    SetOpt ion(CommissionAmount, Spread * T ickSize * Pointvalue);

    And last ly, for Currencies we only pay the Spread once per round tr ip,general ly on enter ing the trade, so our f inal dol lar calculat ion for theCommissionAmount wi l l look l ike this :

    SetOpt ion(CommissionAmount, 0.5 * Spread * T ickSize * PointValue);

    This therefore shows again why we need the T ickSize to be specif ied. I f wedo not speci fy any T ickSize , i ts value is zero and the Commiss ionAmount wi l la lways be zero, leading to incorrect f inal dol lar values.

    We know that the T ickSize wi l l vary per currency: this is easi ly set in eacht ickers Information sheet or better st i l l with AFL l ike this :

    T ickSize = I I f (StrRight(Name() ,3) == JPY,0.01, 0.0001);

    and is a lready part of our code to get the correct Dol lar value in thebacktester.

    We also know that the spread varies per t icker, with the actual spreaddepending on your Broker, but can be easi ly done with the I I F statement.

    So the sample code for a Forex backtest commiss ion calculat ion for a pairwhere CCY2 is JPY would look something l ike this :

    SetFormulaName("FxCommissionCorrect");SetOption("FuturesMode",1);// SET THIS ALSO IN GUI SETTINGS.SetOption("InitialEquity", 100000);RoundLotSize = 1;TickSize = IIf( StrRight( Name(),3) == "JPY", 0.01, 0.0001);

    MarginDeposit = 1000; // for example for 100:1 leverage on standard lotPointValue = 915; // for pairs with JPY as the counter currencyNumLots = Param("NumLots", 1,1,10,1);

    PositionSize = NumLots *MarginDeposit;Spread = 4; // current GBPJPY SpreadSetOption("CommissionMode",3); // $ amount per contractSetOption("CommissionAmount", 0.5 * Spread * TickSize * PointValue);

    // silly simple Buy & Sell rulesBuy = Cross( Close, EMA(C,30));Sell = BarsSince(Buy) == 4;

    Now, i f we wanted to run this across a l l currency pairs at the same t ime, wewould have to both

    a. Set the correct spread with the I IF funct ion e.g.

    OnePip = Name() == "EURUSD"ORName() == "EURGBP";TwoPip = Name() == "EURCHF"ORName() == "EURJPY"ORName() == "USDJPY"ORName() =="AUDUSD";ThreePip = Name() == "CHFJPY"ORName() == "USDCHF"ORName() == "GBPUSD";FourPip = Name() == "CADJPY"ORName() == "USDCAD"ORName() == "AUDJPY"ORName() =="EURCAD"ORName() == "NZDUSD";SevenPip = Name() == "GBPCHF"ORName() == "GBPJPY";

    Spread = IIf( OnePip, 1, IIf(TwoPip,2, IIf(ThreePip,3, IIf(FourPip,4, IIf(SevenPip,7,5)))));

    b. Set the correct PointValue for each pair : as discussed above we can bestdo this with the Symbol, Information f ie ld, or i f we l ike we could code thisinto the AFL, a lso with I I F funct ion, such as

    PointValue = IIf ( StrRight( Name(),3) == "JPY", 915, IIf ( StrRight( Name(),3) == "CAD", 98900,

  • 8/3/2019 AB Back Tester Basics

    25/27

    Page 25 of 27

    IIf ( StrRight( Name(),3) == "CHF", 90000, IIf ( Name() == "AUDNZD", 78000,

    IIf ( Name() == "EURGBP", 195000, 100000)))));

    These values wi l l only need occasional changes once currency exchangerates change s ignif icant ly, and can easi ly be obtained from your brokersplatform or a s imple spreadsheet.

    They would a lso need to be adjusted i f one were to have di f ferent accounts izes, t rade di f ferent lot s izes or had accounts in di f ferent base currency.

    So now we are in a posit ion to set the Commiss ion Amount to a l low theBacktester to display correct dol lars amounts in the backtester.

    REPORTS in Pips

    We note a lso that i f have more than one account, perhaps trading di f ferentLot s izes or in di f ferent currencies, we would have to change the PointValuefor each account i f we want the Backtester sett ings to return the Prof i t inDol lars .

    Because of this we may choose to get the Backtester to give us the results inPips rather than Dol lars .

    I f we want to display the prof i t in pips, we can just set the PointValue equalto the amount of pips in a one point move:

    For Non Yen pairs this works wel l :

    PositionSize =MarginDeposit = 1;PointValue = 10000;

    For Yen pairs we need 100 for the PointValue because there are 100 pipsmoved for one point .

    PositionSize =MarginDeposit = 1;PointValue = 100;

    Now we can use the I I f Statement to def ine this in AFL, and then we do notneed to set this in the I nformation sheet.

    PositionSize =MarginDeposit =1;PointValue = IIf( StrRight( Name(),3) == "JPY", 100, 10000) ;

    Now we have a potent ia l ly new problem: the PnL is expressed in P ips butunless we convert the equity to P ips, then the Stat ist ics in the backtestReport wi l l be meaningless.

    So we can add this code to convert the init ia l Equity we start with into P ips.

    SetFormulaName("FxPnLinPIPS");// reminds us the results we are looking at is in pips.SetOption("FuturesMode",1);// SET this also in the SETTINGS GUIRoundLotSize = 1;

    MarginDeposit = 1000;PositionSize =MarginDeposit = 1;

    TickSize = IIf(StrRight(Name(),3)=="JPY",0.01,0.0001);

    // Use these to reset Equity from Dollars to PipsPositionSize =MarginDeposit = 1;

    PointValue = IIf( StrRight(Name(),3)=="JPY",915, 100000); // typical JPY and USD valuesdollarEQUITY = 100000; // Set trading capital in dollarsDollarPerPip = PointValue * TickSize;pipEQUITY = dollarEQUITY / DollarPerPip;

  • 8/3/2019 AB Back Tester Basics

    26/27

    Page 26 of 27

    SetOption("InitialEquity", pipEQUITY);

    //Reset PointValue to allow for results in Pips as abovePointValue = IIf( StrRight(Name(),3)=="JPY",100, 10000);

    Then when we run a backtest over the same t icker, same data and samesystem, once with normal dol lar results , and then with P ipValue results , thenwe f ind that MOST, but not a l l o f the Backtester stat ist ics are displayed

    correct ly.

    These statistics will remain valid:

    In i t ia l Capita l , Ending Capita l , Net Prof i t , Net Prof i t%, Annual return%; AvgProf i t /Loss, Avg Bars Held;

    Winners number and percent, Total Prof i t , Avg Prof i t , Avg bars held, MaxConsecut ive, largest win, # bars in l argest win;Losers Number and Percent, Total Loss, Avg Loss, Avg Bars held, MaxConsecut ive, Largest Loss, # bars in Largest Loss.

    Other stat ist ics: Max trade drawdown, Max System Drawdown, Max System %

    Drawdown, Recovery Factor,CAR/MaxDD, Prof i t Factor, Payoff Rat io , Standard Error, Risk-Reward Rat io ,Ul ce r In de x, Ul ce r Pe rf or ma nc e Index, Sharpe Ratio of trades, K-ratio.

    These statistics will not make sense:

    Exposure%, Net Risk Adjusted Return%, Risk Adjusted Return%; AvgProf i t /Loss%:Winners: Avg Prof i t% ;Losers: Avg Loss %;Other stat ist ics: Max trade % drawdown, RARMaxDD,

    So, a lthough not a l l the values wi l l be val id we can st i l l p l ot the Equity curveand extract the most important stat ist ics needed to compare one strategyagainst another.

    Setting the Commission in Pips

    Final ly, we need to inc lude the Commiss ion in P ips. This is easy, where thecommiss ion amount is s imply equal to the Spread, and we remember that weonly pay the spread in Forex once per round tr ip:

    Spread = 4;SetOption("CommissionMode",3);SetOption("CommissionAmount",Spread / 2);

    Summary

    Knowledge of how the backtester does i ts calculat ions, where we set themand how to use them is the f i rst step to developing conf idence in the resultsthe backtester displays.

    We have learnt the basics of the backtester, where we can use the AFL tooverr ide the SETTINGS GUI entr ies, which sett ings cannot be set in the AFLand which ones can only be set in the AFL.

    We have seen how the Applystops work and how they can be plotted forvisual reference.

    We have looked at the di f ferences between backtest ing shares and forex, andwhich sett ings were needed to obtain accurate forex calculat ions. We have

  • 8/3/2019 AB Back Tester Basics

    27/27

    Page 27 of 27

    seen how we can express forex results in dol lars or pips and shown how toobtain correct commiss ions to be factored into the calculat ions.

    Other Simple Tips

    When test ing and running these backtest AFLs, we make frequent changes tothe code or sett ings. The next run of the backtest does not a lways register

    the new change.

    We can just hit the Back Test button a few t imes,or we can save changes to the AFL and reload the f i le .

    Reference future bars

    Prior to running the backtester we need to ensure the code and sett ings donot a l low referencing future bars, or e lse the strategy wi l l not be able to betraded l ive.

    Go to AA, Check or Tools , Check. I f there is a reference to future bars we wi l lneed to rem out each l ine unt i l we f ind out which is the of fending code and

    rect i fy this f i rst .

    Even us ing the next bars data to work out the posit ion s iz ing can result inthis error.See message #97492 in Amibroker usergroups.

    References

    1. Amibroker help f i le

    2. Yahoo Amibroker group3. Amibroker support4. http://www.amibroker.com/kb/2006/08/09/amibroker-for-forex/

    ChrisBc/bJan 2008Feedback/errors/ corrections welcome via yahoo amibroker usergroup orkris45mar [at] iinet.net.au

    http://www.amibroker.com/kb/2006/08/09/amibroker-for-forex/mailto:[email protected]://www.amibroker.com/kb/2006/08/09/amibroker-for-forex/mailto:[email protected]