am i broker back testing procedure

11

Click here to load reader

Upload: krishnmoorthy-subramaniam

Post on 18-Feb-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Am i Broker Back Testing Procedure

7/23/2019 Am i Broker Back Testing Procedure

http://slidepdf.com/reader/full/am-i-broker-back-testing-procedure 1/11

Back-testing your trading ideas

Introduction

One of the most useful things that you can do in the analysis window is to back-test your trading

strategy on historical data. This can give you valuable insight into strengths and weak points ofyour system before investing real money. This single AmiBroker feature is can save lots ofmoney for you.

Writing your trading rules

First you need to have objective or mechanical! rules to enter and e"it the market. This step isthe base of your strategy and you need to think about it yourself since the system must matchyour risk tolerance# portfolio si$e# money management techni%ues# and many other individualfactors.

Once you have your own rules for trading you should write them as buy and sell rules inAmiBroker Formula &anugage plus short and cover if you want to test also short trading!.

'n this chapter we will consider very basic moving average cross over system. The system would buy stocks(contracts when close price rises above )*-day e"ponential moving average and willsell stocks(contracts when close price falls below )*-day e"ponential moving average.

The e"ponential moving average can be calculated in AF& using its built-in function +,A. Allyou need to do is to specify the input array and averaging period# so the )*-day e"ponentialmoving average of closing prices can be obtained by the following statement

ema( close, 45 );

The close identifier refers to built-in array holding closing prices of currently analysed symbol.

To test if the close price crosses above e"ponential moving average we will use built-in crossfunction

buy = cross( close, ema( close, 45 ) );

The above statement defines a buy trading rule. 't gives / or true when close price crossesabove ema close# )* !. Then we can write the sell rule which would give / when opposite

situation happens - close price crosses below ema close# )* !

sell = cross( ema( close, 45 ), close );

0lease note that we are using the same cross function but the opposite order of arguments.

1o complete formula for long trades will look like this

Page 2: Am i Broker Back Testing Procedure

7/23/2019 Am i Broker Back Testing Procedure

http://slidepdf.com/reader/full/am-i-broker-back-testing-procedure 2/11

buy = cross( close, ema( close, 45 ) );

sell = cross( ema( close, 45 ), close );

 NOTE: To create new formula please open Formula Editor  using Analysis->Formula Editor  menu, type the formula and choose Tools->Send to Analysis menu in Formula editor 

Back testing

To back-test your system just click on the Back test button in the Automatic analysis window.,ake sure you have typed in the formula that contains at least buy and sell trading rules asshown above!. 2hen the formula is correct AmiBroker starts analysing your symbols accordingto your trading rules and generates a list of simulated trades. The whole process is very fast - youcan back test thousands of symbols in a matter of minutes. The progress window will show youestimated completion time. 'f you want to stop the process you can just click 3ancel button in the progress window.

Analysing results

2hen the process is finished the list of simulated trades is shown in the bottom part of Automaticanalysis window. the Results pane!. 4ou can e"amine when the buy and sell signals occurred just by double clicking on the trade in Results pane. This will give you raw or unfiltered signalsfor every bar when buy and sell conditions are met. 'f you want to see only single trade arrowsopening and closing currently selected trade! you should double click the line while holding15'FT key pressed down. Alternatively you can choose the type of display by selectingappropriate item from the conte"t menu that appears when you click on the results pane with aright mouse button.

'n addition to the results list you can get very detailed statistics on the performance of your

system by clicking on the Report button. To find out more about report statistics please checkout report window description.

Changing your back testing settings

Back testing engine in AmiBroker uses some predefined values for performing its task includingthe portfolio si$e# periodicity daily(weekly(monthly!# amount of commission# interest rate#ma"imum loss and profit target stops# type of trades# price fields and so on. All these settingscould be changed by the user using settings window. After changing settings please remember torun your back testing again if you want the results to be in-sync with the settings.

For e"ample# to back test on weekly bars instead of daily just click on the Settings button selectWeekly from eriodicity combo bo" and click !" # then run your analysis by clicking Back

test.

Reserved variable names

The following table shows the names of reserved variables used by Automatic Analyser. Themeaning and e"amples on using them are given later in this chapter.

Page 3: Am i Broker Back Testing Procedure

7/23/2019 Am i Broker Back Testing Procedure

http://slidepdf.com/reader/full/am-i-broker-back-testing-procedure 3/11

6ariable 7sage Applies to

 buy defines buy enter long position! trading rule AutomaticAnalysis#3ommentary

sell defines sell close long position! trading rule AutomaticAnalysis#3ommentary

short defines short enter short position - short sell! trading rule AutomaticAnalysis

cover defines cover close short position - buy to cover! trading rule AutomaticAnalysis

 buyprice defines buying price array this array is filled in with the defaultvalues according to the Automatic Analyser settings!

AutomaticAnalysis

sellprice defines selling price array this array is filled in with the defaultvalues according to the Automatic Analyser settings!

AutomaticAnalysis

shortprice defines short selling price array this array is filled in with thedefault values according to the Automatic Analyser settings!

AutomaticAnalysis

coverprice defines buy to cover price array this array is filled in with thedefault values according to the Automatic Analyser settings!

AutomaticAnalysis

e"clude 'f defined# a true or /! value of this variable e"cludes currentsymbol from scan(e"ploration(back test. They are also notconsidered in buy and hold calculations. 7seful when you want

to narrow your analysis to certain set of symbols.

AutomaticAnalysis

roundlotsi$e defines round lot si$es used by backtester see e"planations below!

AutomaticAnalysis newin )./8!

ticksi$e defines tick si$e used to align prices generated by built-in stops see e"planations below! note it does not affect entry(e"it prices specified by buyprice(sellprice(shortprice(coverprice!

AutomaticAnalysis newin )./8!

 pointvalue allows to read and modify future contract point value see backtesting futures!3A6+AT this AF& variable is by default set to / one!regardless of contents of 'nformation window 79&+11 you turnO9 futures mode 1etOptionFutures,ode# True !!

AutomaticAnalysis newin )./8!

margindeposit allows to read and modify future contract margin see backtesting futures!

AutomaticAnalysis newin )./8!

 positionsi$e Allows control dollar amount or percentage of portfolio that is Automatic

Page 4: Am i Broker Back Testing Procedure

7/23/2019 Am i Broker Back Testing Procedure

http://slidepdf.com/reader/full/am-i-broker-back-testing-procedure 4/11

invested into the trade see e"planations below! Analysis newin :.;!

Advanced concepts

7ntil now we discussed fairly simple use of the back tester. AmiBroker# however supports muchmore sophisticated methods and concepts that will be discussed later on in this chapter. 0leasenote that the beginner user should first play a little bit with the easier topics described above before proceeding.

1o# when you are ready# please take a look at the following recently introduced features of the back-tester

a! AF& scripting host for advanced formula writers b! enhanced support for short tradesc! the way to control order e"ecution price from the scriptd! various kinds of stops in back tester e! position si$ingf! round lot si$e and tick si$eg! margin accounth! backtesting futures 

AF& scripting host is an advanced topic that is covered in a separate document available here and' won<t discuss it in this document. =emaining features are much more easy to understand.

Short trade support

'n the previous versions of AmiBroker# if you wanted to back-test system using both long andshort trades# you could only simulate stop-and-reverse strategy. 2hen long position was closed anew short position was opened immediatelly. 't was because buy and sell reserved variables wereused for both types of trades.

 9ow with version :.*; or higher! there are separate reserved variables for opening and closinglong and short trades

 buy - true or / value opens long tradesell - true or / value closes long tradeshort - true or / value opens short tradecover - true or / value closes short trade

1om in order to back-test short trades you need to assign short and cover variables.'f you use stop-and-reverse system always on the market! simply assign sell to short and buy tocover 

short = sell;

cover = buy;

Page 5: Am i Broker Back Testing Procedure

7/23/2019 Am i Broker Back Testing Procedure

http://slidepdf.com/reader/full/am-i-broker-back-testing-procedure 5/11

This simulates the way pre-:.*; versions worked.

But now AmiBroker enables you to have separate trading rules for going long and for going shortas shown in this simple e"ample

// long trades entry and exit rules:

buy = cross( cci(), 100 );

sell = cross( 100, cci() );

// short trades entry and exit rules:

short = cross( 100, cci() );

cover = cross( cci(), 100 );

 9ote that in this e"ample if 33' is between -/88 and /88 you are out of the market.

Controlling trade price

AmiBroker now provides ) new reserved variables for specifying the price at which buy# sell#short and cover orders are e"ecuted. These arrays have the following names buyprice# sellprice#shortprice and coverprice.

The main application of these variables is controlling trade price

!uy"rice = ##$( dayo%&ee'() == 1, #, *+-. );

// on monday buy at high, other&ise buy on close

1o you can write the following to simulate real stop-orders

!uy-to = the %ormula %or buy sto level;

-ell-to = the %ormula %or sell sto level;

// i% anytime during the day rices rise above buysto level (highbuysto)

// the buy order ta'es lace (at buysto or lo& &hichever is higher)

!uy = *ross( igh, !uy-to );

// i% anytime during the day rices %all belo& sellrice level ( lo& 2

sellsto )

// the sell order ta'es lace (at sellsto or high &hichever is lo&er)

-ell = *ross( -ell"rice, -ell-to);

!uy"rice = max( !uy-to, +o& ); // ma'e sure buy rice not less than +o&

-ell"rice = min( -ell-to, igh ); // ma'e sure sell rice not greater than

igh

0lease note that AmiBroker presets buyprice# sellprice# shortprice and coverprice array variableswith the values defined in system test settings window shown below!# so you can but don<t needto define them in your formula. 'f you don<t define them AmiBroker works as in the old versions.

>uring back-testing AmiBroker will check if the values you assigned to buyprice# sellprice#shortprice# coverprice fit into high-low range of given bar. 'f not# AmiBroker will adjust it to

Page 6: Am i Broker Back Testing Procedure

7/23/2019 Am i Broker Back Testing Procedure

http://slidepdf.com/reader/full/am-i-broker-back-testing-procedure 6/11

high price if price array value is higher than high! or to the low price if price array value islower than low!

rofit target stops

As you can see in the picture above# new settings for profit target stops are available in thesystem test settings window. 0rofit target stops are e"ecuted when the high price for a given daye"ceedes the stop level that can be given as a percentage or point increase from the buying price.

By default stops are e"ecuted at price that you define as sell price array for long trades! or cover  price array for short trades!. This behaviour can be changed by using +"it at stop feature.

#$%it at stop# feature

'f you mark +"it at stop bo" in the settings the stops will be e"ecuted at e"act stop level# i.e. ifyou define profit target stop at ?/8@ your stop and the buy price was *8 stop order will bee"ecuted at ** even if your sell price array contains different value for e"ample closing price of*!.

,a"imum loss stops work in a similar manner - they are e"ecuted when the low price for a given

day drops below the stop level that can be given as a percentage or point increase from the buying price

&railing stops

This kind of stop is used to protect profits as it tracks your trade so each time a position valuereaches a new high# the trailing stop is placed at a higher level. 2hen the profit drops below thetrailing stop level the position is closed. This mechanism is illustrated in the picture below /8@trailing stop is shown!

The trailing stop# as well as two other kind of stops could be enabled from user interfaceAutomatic analysis< 1ettings window! or from the formula level - using Apply1top function

To reproduce the e"ample above you would need to add the following code to your automaticanalysis formula

Page 7: Am i Broker Back Testing Procedure

7/23/2019 Am i Broker Back Testing Procedure

http://slidepdf.com/reader/full/am-i-broker-back-testing-procedure 7/11

Apply1top C# /# /8# / !D (( /8@ trailing stop# percent mode# e"it at stop O9

or you can write it using predefined constants that are more descriptive

Apply1top stopTypeTrail# stop,ode0ercent# /8# True !D

Trailing stops could be also defined in points dollars! and percent of profit risk!. 'n the lattercase the amount parameter defines the percentage of profits that could be lost without activatingthe stop. 1o C8@ percent of profit risk! stop will e"it your trade that has ma"imum profit ofE/88 when the profit decreases below E8.

'ynamic stops

The Apply1top! function allows now to change the stop level from trade to trade. This enablesyou to implement for e"ample volatility-based stops very easily.

For e"ample to apply ma"imum loss stop that will adapt the ma"imum acceptable loss based on/8 day average true range you would need to write

Apply1top 8# C# C G AT= /8 !# / !D

or you can write it using predefined constants that are more descriptive

Apply1top stopType&oss# stop,ode0oint# C G AT= /8 !# True !D

The function above will place the stop C times /8 day AT= below entry price.

As AT= changes from trade to trade - this will result in dynamic# volatility based stop level.0lease note that :rd parameter of Apply1top function the amount! is sampled at the trade entryand held troughout the trade. 1o in the e"ample above it uses AT=/8! value from the date of theentry. Further changes of AT= do not affect the stop level.

1ee complete A00&41TO0 function documentation for more details.

Coding your own custom stop types

Apply1top function is intended to cover most popular kinds of stops. 4ou can however codeyour own kind of stops and e"its using looping code. For e"ample the following re-implements

 profit target stop and shows how to refer to the trade entry price in your formulas

/3 a samle lo&level imlementation o% "ro%ittarget sto in $+: 3/ 

Buy = *ross( *6(), -ignal() );

riceatbuy=0;

for( i = 0; i 2 BarCount; i77 )

8

Page 8: Am i Broker Back Testing Procedure

7/23/2019 Am i Broker Back Testing Procedure

http://slidepdf.com/reader/full/am-i-broker-back-testing-procedure 8/11

  if( riceatbuy == 0 99 Buy i )

riceatbuy = BuyPrice i ;

if( riceatbuy 0 99 SellPrice i 11 3 riceatbuy )

8

Sell i = 1;

SellPrice i = 11 3 riceatbuy;

riceatbuy = 0;

<

else 

Sell i = 0;

<

osition si(ing

This is a new feature in version :.;. 0osition si$ing in backtester is implemented by means ofnew reserved variable

0osition1i$e H si$e arrayI

 9ow you can control dollar amount or percentage of portfolio that is invested into the trade

•  positive number define dollar! amount that is invested into the trade for e"ample

0osition1i$e H /888D (( invest E/888 in every trade

• negative numbers -/88..-/ define percentage

-/88 gives /88@ of current portfolio si$e#-:: gives ::@ of available e%uity for e"ample

0osition1i$e H -*8D (G always invest only half of the current e%uity G(

• dynamic si$ing e"ample

0osition1i$e H - /88 ? =1'!D

as =1' varies from 8../88 this will result in position depending on =1' values -I lowvalues of =1' will result in higher percentage invested

'f less than /88@ of available cash is invested then the remaining amount earns interest rate asdefined in the settings.

There is also a new checkbo" in the AA settings window Allow position si$e shrinking - thiscontrols how backtester handles the situation when re%uested position si$e via 0osition1i$evariable! e"ceeds available cash when this flag is checked the position is entered with si$eshinked to available cash if it is unchecked the position is not entered.

To see actual position si$es please use a new report mode in AA settings window Trade listwith prices and pos. si$e

Page 9: Am i Broker Back Testing Procedure

7/23/2019 Am i Broker Back Testing Procedure

http://slidepdf.com/reader/full/am-i-broker-back-testing-procedure 9/11

For the end# here is an e"ample of Tharp<s AT=-based position si$ing techni%ue coded in AF&

!uy = 2your buy %ormula here

-ell = 0; // selling only by sto

rail-tomount = > 3 ?( >0 );

*aital = 100000; /3 #"?@: -et it also in the -ettings: #nitial .Auity 3/

?is' = 0013*aital;

"osition-iBe = (?is'/rail-tomount)3!uy"rice;

ly-to( >, >, rail-tomount, 1 );

The techni%ue could be summari$ed as follows

The total e%uity per symbol is E/88#888# we set the risk level at /@ of total e%uity. =isk level isdefined as follows if a trailing stop on a E*8 stock is at# say# E)* the value of two AT=<s againstthe position!# the E* loss is divided into the E/888 risk to give C88 shares to buy. 1o# the loss risk is E/888 but the allocation risk is C88 shares " E*8(share or E/8#888. 1o# we areallocating /8@ of the e%uity to the purchase but only risking E/888. (Edited excerpt from the

 AmiBroer mailing list!

Round lot si(e and tick si(e

 "ound lot si#e

6arious instruments are traded with various trading units or blocks. For e"ample you can purchase fractional number of units of mutual fund# but you can not purchase fractional numberof shares. 1ometimes you have to buy in /8s or /88s lots. AmiBroker now allows you to specifythe block si$e on global and per-symbol level.

4ou can define per-symbol round lot si$e in the 1ymbol-I'nformation page pic. :!. The value of $ero means that the symbol has no special round lot si$e and will use >efault round lot si$eglobal setting! from the Automatic Analysis settings page pic. /!. 'f default si$e is set also to$ero it means that fractional number of shares(contracts are allowed.

4ou can also control round lot si$e directly from your AF& formula using =ound&ot1i$ereserved variable# for e"ample

?ound+ot-iBe = 10;

Tic si#e

This setting controls the minimum price move of given symbol. 4ou can define it on global and per-symbol level. As with round lot si$e# you can define per-symbol tick si$e in the 1ymbol-I'nformation page pic. :!. The value of $ero instructs AmiBroker to use default tick si$edefined in the 1ettings page pic. /! of Automatic Analysis window. 'f default tick si$e is also setto $ero it means that there is no minimum price move.

Page 10: Am i Broker Back Testing Procedure

7/23/2019 Am i Broker Back Testing Procedure

http://slidepdf.com/reader/full/am-i-broker-back-testing-procedure 10/11

4ou can set and retrieve the tick si$e also from AF& formula using Tick1i$e reserved variable#for e"ample

ic'-iBe = 001;

 9ote that the tick si$e setting affects O9&4 trades e"ited by built-in stops and(or Apply1top!.The backtester assumes that price data follow tick si$e re%uirements and it does not change pricearrays supplied by the user.

1o specifying tick si$e makes sense only if you are using built-in stops so e"it points aregenerated at allowed price levels instead of calculated ones. For e"ample in Japan - you cannot have fractional parts of yen so you should define global ticksi$e to /# so built-in stops e"ittrades at integer levels.

)argin account

 Account margin setting defines percentage margin re%uirement for entire account. The defaultvalue of Account margin is /88. This means that you have to provide /88@ funds to enter thetrade# and this is the way how backtester worked in previous versions. But now you can simulatea margin account. 2hen you buy on margin you are simply borrowing money from your brokerto buy stock. 2ith current regulations you can put up *8@ of the purchase price of the stock youwish to buy and borrow the other half from your broker. To simulate this just enter *8 in the Account margin field see pic. /! . 'f your intial e%uity is set to /8888 your buying power will bethen C8888 and you will be able to enter bigger positions. 0lease note that this settings sets themargin for entire account and it is 9OT related to futures trading at all. 'n other words you cantrade stocks on margin account.

Additional settings

• =everse entry signal forces e"it check bo" to the Backtester settings.

2hen it is O9 the default setting! - backtester works as in previous versions and closesalready open positon if new entry signal in reverse direction is encountered. 'f this switchis OFF - even if reverse signal occurs backtester maintains currently open trade and doesnot close positon until regular e"it sell or cover! signal is generated.'n other words when this switch is OFF backtester ignores 1hort signals during longtrades and ignores Buy signals during short trades.

• Allow same bar e"it single bar trade! option to the 1ettings

2hen it is O9 the default settings! - entry and e"it at the very same bar is allowed as in

 previous versions!if it is OFF - e"it can happen starting from ne"t bar only this applies to regularsignals#there is a separate setting for Apply1top-generated e"its!. 1witching it to OFFallows to reproduce the behaviour of ,1 backtester that is not able to handle same daye"its.

• Activate stops immediately

Page 11: Am i Broker Back Testing Procedure

7/23/2019 Am i Broker Back Testing Procedure

http://slidepdf.com/reader/full/am-i-broker-back-testing-procedure 11/11

This setting solves the problem of testing systems that enter trades on market open. 'nversions prior to ).8; backtester assumed that you were entering trades on market closeso built-in stops were activated from the ne"t day. The problem was when you in factdefined open price as the trade entry price - then same day price fluctuations did nottrigger the stops. There were some published workarounds based on AF& code but now

you don<t need to use them. 1imply if you trade on open you should mark Activate stopsimmediately pic. /!.

4ou may ask why do not simply check the buyprice or shortprice array if it is e%ual toopen price. 7nfortunatelly this won<t work. 2hyK 1imply because there are doji dayswhen open price e%uals close and then backtester will never know if trade was entered atmarket open or close. 1o we really need a separate setting.

• 7se LuickAF&

LuickAF&tm! is a feature that allows faster AF& calculation under certain conditions.'nitially since C88:! it was available for indicators only# as of version *./)? it isavailable in Automatic Analysis too.

'nitially the idea was to allow faster chart redraws through calculating AF& formula onlyfor that part which is visible on the chart. 'n a similar manner# automatic analysis windowcan use subset of available %uotations to calculate AF&# if selected MrangeN parameter isless than MAll %uotations.

>etailed e"planation on how LuickAF& works and how to control it# is provided in thisnowledge Base article http((www.amibroker.com(kb(C88(8P(8:(%uickafl(

 9ote that this option works not only in the backtester# but also in optimi$ations#

e"plorations and scans.

See Also*

0ortfolio-level backtesting article.

Backtesting systems for futures contracts article.

A00&41TO0 function description

7sing AF& editor  section of the guide.

'nsider guide to backtester newsletter /(C88C!