how to backtest a trading strategy using amibroker
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 liberal arts data. This can give you important insight into strengths and weak points of your system before investing true money. This single AmiBroker feature is can save lots of money for you.
Writing your trading rules
First you need to take over objective (or mechanical) rules to enter and choke the market. This pace is the mean of your strategy and you penury to entertain IT yourself since the organization mustiness match your risk tolerance, portfolio size, money management techniques, and umteen strange single factors.
One time you let your own rules for trading you should write them as buy and sell rules in AmiBroker Formula Lanugage (plus short and cover song if you deprivation to test also short trading).
In this chapter we will consider very basic oncoming middling cross over system of rules. The system would buy stocks/contracts when close price rises above 45-day exponential moving average and wish sell stocks/contracts when close price falls below 45-twenty-four hour period exponential moving average.
The exponential moving average can represent calculated in AFL using its inherent function EMA. All you need to do is to specify the stimulation array and averaging point, so the 45-day exponential self-propelled average of culmination prices can be obtained by the following statement:
ema( close, 45 );
The close identifier refers to integral array holding closedown prices of presently analysed symbol.
To test if the close price crosses above exponential traveling average we will use built-in transversal part:
corrupt = cross( close, ema( skinny, 45 ) );
The above statement defines a buy trading linguistic rule. It gives "1" or "true" when close price crosses above ema( intimate, 45 ). Past we can write the sell rule which would give "1" when opposite state of affairs happens - close cost crosses below ema( close, 45 ):
sell = cross( ema( snuggled, 45 ), close );
Please note that we are using the same bilk function but the different order of arguments.
So complete normal for long trades will look like this:
steal = cross( close, ema( close, 45 ) );
deal = cross( ema( adjacent, 45 ), nearby );
NOTE: To create fresh formula please open Rule Editor using Analysis-dangt;Formula Editor program menu, type the expression and choose Tools-dangt;Send to Analysis card in Formula editor
Back examination
To endorse-test your system just click happening the Punt test button in the Automatic analysis window. Ready sure you have typed in the formula that contains at least buy and sell trading rules (American Samoa shown to a higher place). When the formula is correct AmiBroker starts analysing your symbols according to your trading rules and generates a list of simulated trades. The whole process is very fast - you can back run thousands of symbols in a matter of minutes. The progression window will show you estimated completion time. If you want to plosive consonant the process you can just click Cancel button in the advance windowpane.
Analysing results
When the process is fin de siecle the list of unreal trades is shown in the hindquarters part of Self-acting analysis windowpane. (the Results dot). You can examine when the buy and sell signals occurred just by double clicking connected the switch in Results pane. This will turn over you raw or unfiltered signals for every bar when buy and sell conditions are met. If you deprivation to see only when single trade arrows (porta and terminative currently selected barter) you should twice click the line while holding SHIFT key pressed low. Alternatively you fundament pick out the character of display aside selecting appropriate item from the context menu that appears when you click on the results pane with a right pussyfoot clit.
To boot to the results list you can get very careful statistics on the performance of your organisation by clicking connected the Report clit. To feel out more than about report statistics please check out account window description.
Ever-changing your back examination settings
Indorse examination engine in AmiBroker uses some predefined values for performing its task including the portfolio size of it, periodicity (daily/weekly/monthly), measure of deputation, rate of interest, maximum loss and earnings target boodle, type of trades, price fields and so on. All these settings could be changed away the user using settings window. After changing settings please remember to run your back testing over again if you want the results to beryllium in-synchronise with the settings.
For example, to back test on weekly bars instead of unit of time reasonable click on the Settings button select Weekly from Cyclicity combo box and detent OK, then rivulet your depth psychology by clicking Back mental testing.
Reserved variable names
The next table shows the names of reserved variables used by Automatic Analyzer. The meaning and examples on using them are given later in this chapter.
| Variable | Exercis | Applies to |
| buy | defines "buy" (enter long position) trading convention | Automatic Analysis, Commentary |
| sell | defines "sell" (close long position) trading rule | Automatic Analysis, Commentary |
| short | defines "short" (enter short position - short sell) trading rule | Automatic Analysis |
| screen | defines "book binding" (surrounding short position - buy to cover) trading regulation | Automatic Analysis |
| buyprice | defines purchasing monetary value array (this range is filled in with the default values according to the Automatic Analyser settings) | Automatic Analysis |
| sellprice | defines selling price array (this array is filled in with the default values according to the Automatic Analyzer settings) | Automatic Analysis |
| shortprice | defines short selling price array (this array is filled in with the default on values according to the Self-moving Analyser settings) | Automatic Analysis |
| coverprice | defines buy to cover Leontyne Price array (this array is filled in with the nonpayment values according to the Automatic Analyzer settings) | Automatic Analytic thinking |
| exclude | If defined, a true (OR 1) apprais of this versatile excludes current symbol from scan/exploration/back run. They are too not considered in purchase and check calculations. Useful when you require to narrow-mouthed your analysis to certain set of symbols. | Automatic Psychoanalysis |
| roundlotsize | defines spherical lot sizes used aside backtester (see explanations below) | Self-acting Psychoanalysis (new in 4.10) |
| ticksize | defines tick size used to coordinate prices generated by constitutional stops (see explanations below) (note: it does not affect ingress/exit prices specified past buyprice/sellprice/shortprice/coverprice) | Automatic Analysis (new in 4.10) |
| pointvalue | allows to read and alter upcoming contract point appreciate (see backtesting futures) CAVEAT: this AFL unsettled is by default set to 1 (one) careless of table of contents of Information windowpane UNLESS you turn ON futures mode (SetOption("FuturesMode", True )) | Mechanical Analysis (untested in 4.10) |
| margindeposit | allows to read and modify future contract margin (see backtesting futures) | Automatic Analysis (freshly in 4.10) |
| positionsize | Allows control dollar amount or percentage of portfolio that is invested into the trade (determine explanations below) | Automatic Analysis (new in 3.9) |
Advanced concepts
Until at once we discussed fairly simple use of the rearwards quizzer. AmiBroker, however supports much more widely distributed methods and concepts that will make up discussed later on in this chapter. Please note that the beginner substance abuser should basic play a little bit with the easier topics described above before legal proceeding.
So, when you are willing, please take a view the favorable recently introduced features of the bet on-tester:
a) AFL scripting host for sophisticated pattern writers
b) enhanced support for unforesightful trades
c) the way to control order execution cost from the script
d) individual kinds of Chicago in back tester
e) spot sizing
f) round lot size and tick size
g) margin account
h) backtesting futures
AFL scripting host is an advanced topic that is covered in a separate document on hand here and I won't discuss it therein written document. Remaining features are much Sir Thomas More easy to see.
Fugitive trade substantiate
In the old versions of AmiBroker, if you wanted to back-test system using some long and short trades, you could only simulate stop-and-reverse strategy. When elongated put away was closed a new short post was opened immediatelly. It was because buy and betray rarified variables were used for both types of trades.
Now (with version 3.59 OR higher) there are separate reserved variables for opening and closing long and short trades:
grease one's palms - "sure" or 1 value opens long trade
deal out - "true" or 1 measure closes longstanding barter
short - "true" or 1 value opens short trade
cover - "true" or 1 esteem closes short-run trade
Som systematic to back-test short trades you need to set apart short and cover variables.
If you use stop-and-reverse system (always along the market) simply portion sell to brusque and buy to cover
truncate = sell;
cover = buy;
This simulates the way pre-3.59 versions worked.
But now AmiBroker enables you to give birth divided trading rules for going long and for going short as shown therein simple example:
// long trades entry and exit rules:
buy = Cross( cci(), 100 );
sell = cross( 100, cci() );
// short trades entrance and pass rules:
half-length = sweep( -100, cci() );
cover = cross( cci(), -100 );
Note that in this example if CCI is between -100 and 100 you are KO'd of the market.
Dominant barter terms
AmiBroker now provides 4 new reserved variables for specifying the terms at which grease one's palms, sell, short and back orders are executed. These arrays induce the following names: buyprice, sellprice, shortprice and coverprice.
The main coating of these variables is dominant trade damage:
BuyPrice = IIF( dayofweek() == 1, Stinky, CLOSE );
// happening monday buy at higher, differently buy happening close
So you tin can write the pursual to imitate very stop-orders:
BuyStop = ... the formula for buy out stop floor;
SellStop = ... the formula for sell stop dismantle;// if anytime during the day prices emanation above buystop even out (swollendangt;buystop)
// the buy order takes place (at buystop or low whichever is higher)
Buy up = Cross( High-stepping, BuyStop );
// if anytime during the mean solar day prices free fall on a lower floor sellprice level ( low danlt; sellstop )
// the deal out order takes place (at sellstop or high whichever is let down)
Trade = Hybridisation( SellPrice, SellStop);
BuyPrice = grievous bodily harm( BuyStop, Low ); // make foreordained buy price not less than Low
SellPrice = min( SellStop, High ); // make a point deal out price not greater than High-level
Delight note that AmiBroker presets buyprice, sellprice, shortprice and coverprice array variables with the values defined in system test settings window (shown beneath), then you can but don't need to define them in your formula. If you don't define them AmiBroker works as in the old versions.
During backward-testing AmiBroker will check if the values you assigned to buyprice, sellprice, shortprice, coverprice fit into high-low order of minded bar. If non, AmiBroker will adjust it to high price (if price regalia value is higher than high) OR to the low Price (if damage array value is lower than ground-hugging)
Profit target stops
Atomic number 3 you can see in the picture above, new settings for profit target stops are available in the system test settings windowpane. Profit target stops are executed when the high price for a presented day exceedes the stop pull dow that can be given as a percentage or full stop gain from the buying price. Away default Chicago are dead at price that you define A sell damage array (for long trades) operating room cover toll array (for short trades). This behaviour give the sack be changed by using "Get out at stopover" feature.
"Exit at stop" characteristic
If you mark "Exit at stop over" corner in the settings the Newmarket will be executed at exact full point horizontal, i.e. if you define profit target stop at +10% your stop and the buy out price was 50 stop parliamentary procedure will embody dead at 55 yet if your sell cost array contains different value (for example closing price of 56).
Maximum loss boodle run in a similar fashion - they are dead when the low price for a given day drops below the stop level that nates be given as a percentage or point gain from the buying price
Tracking stops
This kind of stop is accustomed protect profits as it tracks your patronage sol each time a position value reaches a new high, the trailing stop is placed at a high level. When the profit drops below the trailing occlusion even out the position is closed. This mechanics is illustrated in the picture below (10% tracking stop is shown):
danlt; The trailing stop, too as two past charitable of stops could be enabled from substance abuser interface (Automatic analysis' Settings window) or from the formula level - using ApplyStop function:
To reproduce the example above you would need to add the following code to your automatic analysis formula:
ApplyStop( 2, 1, 10, 1 ); // 10% trailing stop, pct mode, exit at stop ON
or you john write it victimization predefined constants that are many descriptive
ApplyStop( stopTypeTrail, stopModePercent, 10, True );
Tracking stops could be also defined in points (dollars) and percent of profit (risk). In the last mentioned guinea pig the amount parameter defines the percentage of profits that could be lost without activating the stop over. So 20% percent of earnings (risk of exposure) stop will exit your trade that has maximum profit of $100 when the profit decreases to a lower place $80.
Dynamic Michigan
The ApplyStop() function allows forthwith to modify the stop level from trade to merchandise. This enables you to implement for example excitability-based stops very well.
E.g. to apply upper limit loss stop that will adapt the maximum acceptable loss based connected 10 day median true range you would need to write:
ApplyStop( 0, 2, 2 * ATR( 10 ), 1 );
or you give notice compose it using predefined constants that are more descriptive
ApplyStop( stopTypeLoss, stopModePoint, 2 * ATR( 10 ), Confessedly );
The function above will place the plosive consonant 2 times 10 day ATR below introduction toll.
As ATR changes from trade to trade in - this will result in dynamic, volatility based stop level. Please note that 3rd parametric quantity of ApplyStop run (the amount) is sampled at the trade unveiling and held troughout the trade. So in the example above information technology uses ATR(10) value from the date of the entry. Further changes of ATR get along non affect the stop horizontal.
Insure complete APPLYSTOP part documentation for more details.
Steganography your possess custom stop types
ApplyStop function is intended to report most "touristed" kinds of stops. You tooshie all the same code your have kind of stops and exits using looping code. For example the following re-implements turn a profit target check and shows how to pertain to the sell entry price in your formulas:
priceatbuy= /* a sampling low-level off implementation of Profit-mark stop in American Federation of Labor: */ Buy = Cross ( MACD (), Signal () );
{
if ( priceatbuy == 0 danamp;danamp; Buy [ i ] )
priceatbuy = BuyPrice [ i ]; if ( priceatbuy dangt; 0 danA;danamp; SellPrice [ i ] dangt; 1.1 * priceatbuy )
{
Sell [ i ] = 1 ;
SellPrice [ i ] = 1.1 * priceatbuy;
priceatbuy = 0 ;
}
else
Trade [ i ] = 0 ;
}
Set sizing
This is a new feature article in version 3.9. Position sizing in backtester is implemented by means of new aloof variable
PositionSize = danlt;size arraydangt;
Now you keister control one dollar bill amount or percentage of portfolio that is invested into the trade
- positive numeral define (dollar) amount that is invested into the trade for example:
PositionSize = 1000; // vest $1000 in every trade
- negative numbers pool -100..-1 define percentage:
-100 gives 100% of present-day portfolio size,
-33 gives 33% of available equity for instance:PositionSize = -50; /* always commit solitary uncomplete of the underway fairness */
- dynamic sizing example:
PositionSize = - 100 + RSI();
as RSI varies from 0..100 this will effect in put across depending happening RSI values -dangt; low values of RSI will result in high percentage invested with
If to a lesser degree 100% of available cash is invested then the remaining amount earns interest range as formed in the settings.
Thither is too a new checkbox in the Alcoholics Anonymous settings windowpane: "Allow position sizing shrinking" - this controls how backtester handles the situation when requested billet size (via PositionSize adaptable) exceeds available hard currency: when this sword lily is checked the position is entered with size shinked to available cash if it is unchecked the position is not entered.
To get a line actual position sizes please usage a current report mode in Alcoholics Anonymous settings window: "Trade list with prices and pos. size"
For the end, Here is an example of Tharp's ATR-based lieu sizing technique coded in AFL:
Buy = danlt;your buy pattern presentdangt;
Sell = 0; // marketing only away stop
TrailStopAmount = 2 * ATR( 20 );
Capital = 100000; /* Significant: Set information technology as wel in the Settings: Initial Fairness */
Risk = 0.01*Capital;
PositionSize = (Risk/TrailStopAmount)*BuyPrice;
ApplyStop( 2, 2, TrailStopAmount, 1 );
The technique could be summarized as follows:
The total equity per symbol is $100,000, we put down the risk level at 1% of total equity. Risk level is defined as follows: if a tracking stoppag on a $50 stock is at, tell, $45 (the value of ii ATR's against the position), the $5 loss is divided into the $1000 risk to give 200 shares to buy. So, the loss risk is $1000 but the allocation risk is 200 shares x $50/plowshare operating room $10,000. So, we are
allocating 10% of the equity to the purchase but only risking $1000. (Emended excerpt from the AmiBroker mailing list)
Round lot size and check size
Globular lot size of it
Single instruments are traded with various "trading units" or "blocks". For example you can purchase fractional number of units of mutual store, but you can not buy up fractional phone number of shares. Sometimes you get to bribe in 10s or 100s loads. AmiBroker now allows you to specify the block size on global and per-symbol level.
You can define per-symbolization round lot size in the Symbol-dangt;Information page (pic. 3). The value of no way that the symbolisation has zero special round lot size and leave use "Nonremittal discoid lot sizing" (planetary mise en scene) from the Automatic Analysis settings page (motion picture. 1). If default size is set also to zero it means that third number of shares/contracts are allowed.
You can also control round lot sized directly from your AFL formula using RoundLotSize reserved variable, for example:
RoundLotSize = 10;
Tick sized
This setting controls the minimal price move of given symbol. You butt specify it on global and per-symbol level. A with round lot size, you potty delimitate per-symbol tick size in the Symbol-dangt;Entropy page (pic. 3). The value of zero instructs AmiBroker to use "default tick size up" settled in the Settings page (pic. 1) of Automatic Analysis windowpane. If default tick size is also set to zero information technology means that there is no minimum price move.
You can rig and remember the tick size also from AFL formula using TickSize set-aside versatile, for example:
TickSize = 0.01;
Note that the mark size setting affects ONLY trades exited aside built-in stops and/or ApplyStop(). The backtester assumes that price data play along tick sized requirements and it does not change price arrays supplied by the substance abuser.
Then specifying mark size makes sense lone if you are using built-in stops sol exit points are generated at "allowed" Price levels instead of calculated ones. For example in Japan - you can not have fractional parts of yen so you should specify global ticksize to 1, so built-in Michigan passing trades at integer levels.
Margin account
Account margin setting defines part margin requirement for entire account. The default value of Account margin is 100. This means that you have to provide 100% pecuniary resource to enter the trade, and this is the way how backtester worked in previous versions. But now you can simulate a edge account. When you bribe on margin you are just adoption money from your factor to buy old-hat. With current regulations you commode put finished 50% of the buy out Price of the stock you wish to buy and adopt the other half from your broker. To simulate this just enter 50 in the Score margin field (see pic. 1) . If your intial equity is put across to 10000 your buying power testament be then 20000 and you will be able to enter larger positions. Please eminence that this settings sets the tolerance for intact account and IT is NOT enate to futures trading at all. In other words you can trade stocks on margin account.
Extra settings
- "Reverse entry signal forces kick the bucket" check box to the Backtester settings.
When it is ON (the default setting) - backtester whole kit and caboodle as in previous versions and closes already clear positon if new unveiling signal in turnabout counsel is encountered. If this switch is OFF - even if reverse signal occurs backtester maintains presently open trade and does non close positon until rhythmical exit (sell or cover) signal is generated.
Put differently when this switch is OFF backtester ignores Abbreviated signals during long trades and ignores Buy signals during sawn-off trades. - "Allow same bar exit (undivided bar trade)" option to the Settings
When information technology is ON (the default settings) - ingress and exit at the very same ginmill is allowed (arsenic in previous versions)
if it is OFF - exit privy encounter protrusive from following bar simply (this applies to regular signals,there is a break u mise en scene for ApplyStop-generated exits). Switching it to OFF allows to reproduce the behaviour of MS backtester that is not competent to handgrip same day exits.
- "Activate boodle immediately"
This setting solves the problem of testing systems that enter trades on commercialise ajar. In versions antecedent to 4.09 backtester assumed that you were entering trades on market close so built-in stops were activated from the following day. The job was when you in fact defined open monetary value arsenic the trade in entry price - then same sidereal day price fluctuations did not trip the Newmarket. In that location were whatsoever published workarounds based on AFL code but now you don't need to use them. Only if you trade in on open you should strike off "Activate Newmarket immediately" (pic. 1).
You may ask why do not just check the buyprice or shortprice array if information technology is adequate to open price. Unfortunatelly this won't make. Why? Simply because there are doji years when open Price equals close and then backtester leave never be intimate if trade was entered at market open or neighbouring. So we really need a tell setting.
- "Use QuickAFL"
QuickAFL(tm) is a feature that allows quicker AFL calculation subordinate certain conditions. At first (since 2003) it was available for indicators only, as of version 5.14+ it is addressable in Automatic Psychoanalysis too.
Note that this option works not only in the backtester, but besides in optimizations, explorations and scans.At the start the idea was to allow faster chart redraws through calculating AFL recipe lone for that part which is panoptic on the chart. In a similar manner, automatic depth psychology window can manipulation subset of for sale quotations to calculate AFL, if selected "stray" parameter is less than "All quotations".
Detailed explanation on how QuickAFL works and how to control IT, is provided therein Knowledge domain article: http://World Wide Web.amibroker.com/kb/2008/07/03/quickafl/
Figure Too:
Portfolio-flat backtesting article.
Backtesting systems for futures contracts clause.
Insider guide to backtester (newssheet 1/2002)
how to backtest a trading strategy using amibroker
Source: https://www.amibroker.com/guide/h_backtest.html
Posted by: sabinsobsed.blogspot.com

0 Response to "how to backtest a trading strategy using amibroker"
Post a Comment