amibroker

HomeKnowledge Base

How to print result list from Analysis window

As far as backtest results are considered, they can be printed directly from Report Viewer.

Report printing

But sometimes we may want to print just the result list of scan, exploration or optimization. In order to print out the results list from Analysis window it is necessary to store the results list into a file first. This can be achieved by using File->Export HTML/CSV option from the main menu of the program (Export option is available when Analysis window is open):

Export

I recommend saving in HTML format as only then color output will be preserved.

Export as HTML

Once the result list is saved to a HTML file, you can double click on the file to open it with your default web browser. From web browser you can choose Print option.

If you prefer to modify the file prior to printing you can also save the result list in CSV format that can be open with Excel or any other application of your choice.

An alternative solution is to use system clipboard and to copy the results (using Ctrl+C keyboard shortcut or Copy option from the context menu available under right-mouse button), paste to the application like MS Excel for example and printing the results there.

Too small / unreadable Profit Table in the backtest report

Some of users may observe that their Profit table is too small, so the numbers get truncated or the text is too small.

First let me tell you that profit table in the backtest report is not really a table, but a bitmap image with fixed dimensions. Profit table, like any other user-definable report chart, is created by running an AFL formula present in the “Report charts” subfolder. The chart is rendered into bitmap image that gets later embedded in the backtest report.

The size of backtest report images depends on Analysis window settings. In order to increase the size of generated images, it is necessary to go to Analysis -> Settings, Report tab and increase the picture dimensions:

reportchartdim

Once you change it, newly generated reports will use enlarged image dimensions. Adjusted settings will affect new backtests only, but not the old reports that have already been generated.

Tip: You can create your own report charts by placing your own AFL formula in the “Report charts” subfolder.

Why do backtest results change?

From time to time we receive questions about why you can get different results back-testing the same code.

There are many reasons for differences in backtest results:

  1. Different data

    For example if past history is updated/changed due to splits for example or backfill or external data update.

  2. Different settings / parameters

    May happen if your formula uses Param() functions that output values that may be changed from the Parameter window.

    Note that Parameters in Analysis window use shared ChartID=0, which means that if two formulas use same parameter names they would share parameter values as well.

  3. Different formula

    Sometimes even slight change to the formula causes big change in the results, for example if your formula uses #include and included code has changed

  4. The formula that self-references its previously generated results.

    Such code produces some data that is later used to produce next run output (for example your code produces composites that are later used – if those composites change – the input data change so the results change, or if your formula uses previous backtest equity or if your formula uses STATIC variables without deleting/clearing them at the beginning)

  5. The formula uses random number generator

    This occurs when your formula directly or indirectly calls any function that produces random numbers such as Random or mtRandom

  6. The formula reads external files/data that might have changed

    This occurs when your formula directly or indirectly calls any functions that read external files or data that have changed between backtests. It can be as trivial as using current time in your formula.

  7. The formula sets global (per-backtest) settings to non-constant value – for example sets global option differently for each symbol.

    This one is subtle and can be easily overlooked by non-experienced users. One has to understand that global (per-backtest) settings are applied to entire portfolio. If one changes those settings on per-symbol basis, then “last write” counts, and it means that result of your backtest will depend on which execution thread ended last. In Windows OS, it is generally unpredicatable which thread ends first because of so many factors that affect execution time. So your backtest may use different settings in different runs as a result of this. Bottom line: never change global settings in your formula to non-constant value.

Using Zig-Zag in trading systems

Zig-zag indicator, as well as other functions using it (Peak/Trough, PeakBars, Troughbars), inherently look into the future. As such they should not be used in trading system formulas without taking precautions. The only way to fix the ‘problem’ is to delay the signal as long as it takes for zig/zag to stabilise last ‘leg’. The delay is variable and depends how much time it takes for defined percentage change to occur in the price series since last peak/trough.

Ready-to-use solution is presented in the Traders’ Tips section of the AmiBroker members area:
http://www.amibroker.com/members/traders/11-2003.html

(NOTE: access to members’ area is limited to licensed users only, if you forgot your password use reminder at http://www.amibroker.com/login.html)

Points-only backtest

Some users coming from Metastock ask for “points-only” test.

One needs to know that AmiBroker features way more sophisticated futures mode than MS ever had: http://www.amibroker.com/guide/h_futbacktest.html
It provides full support for futures trading, handling margin deposit, point value, etc.

“Points-only” test is kind of the simplest possible case, but if you want to do just that, it can be implemented using these two lines:

SetOption("FuturesMode"True );
SetPostionSize1spsShares ); // trade just 1 contrac

That is all what you need to add to your formula to get point-only test.

QuickAFL facts

QuickAFL(tm) is a feature that allows faster AFL calculation under certain conditions. Initially (since 2003) it was available for indicators only, as of version 5.14+ it is available in Automatic Analysis too.

Initially the idea was to allow faster chart redraws through calculating AFL formula only for that part which is visible on the chart. In a similar manner, automatic analysis window can use subset of available quotations to calculate AFL, if selected “range” parameter is less than “All quotations”.

So, in short QuickAFL works so it calculates only part of the array that is currently visible (indicator) or within selected range (Automatic Analysis).

Your formulas, under QuickAFL, may or may NOT use all data bars available, but only visible (or “in-range”) bars (plus some extra to ensure calculation of used indicators), so when you are using Close[ 0 ] it represents not first bar in entire data set but first bar in array currently used (which is just a bit longer than visible, or ‘in-range’ area).

The QuickAFL is designed to be transparent, i.e. do not require any changes to the formulas you are using. To achieve this goal, AmiBroker in the first execution of given formula “learns” how many bars are really needed to calculate it correctly.

To find out the number of bars required to calculate formula AmiBroker internally uses two variables ‘backward ref’ and ‘forward ref’.

‘backward ref’ describes how many PREVIOUS bars are needed to calculate the value for today, and ‘forward ref’ tells how many FUTURE bars are needed to calculate value for today.

If these numbers are known, during execution of given formula AmiBroker takes FIRST visible (or in-range) bar and subtracts ‘backward ref” and takes LAST visible (or in-range) bar and adds ‘forward ref’ to calculate first and last bar needed for calculation of the formula.

Now, how does AmiBroker know a correct “backward ref” and “forward ref” for the entire formula?
Well, every AmiBroker’s built-in function is written so that it knows its own requirements and adds them to global “backward ref” and “forward ref” each time given function is called from your formula.

The whole process starts with setting initial BackwardRef to 30 and ForwardRef to zero. These initial values are used to give “safety margin” for simple loops/scripts.

Next, when parser scans the formula like this:

Buy Ref MAC40 ), -)

it analyses it and “sees” the MA with parameter 40. It knows that simple moving average of period 40 requires 40 past bars and zero future bars to calculate correctly so it does the following (all internally):

BackwardRef BackwardRef 40;
ForwardRef ForwardRef 0

So now, the value of BackwardRef will be 70 (40+30(initial)), and ForwardRef will be zero.

Next the parser sees Ref( .., -1 );

It knows that Ref with shift of -1 requires 1 past bar and zero future bars so it “accumulates” requirements this way:

BackwardRef BackwardRef 1;
ForwardRef ForwardRef 0

So it ends up with:

BackwardRef 71;
ForwardRef 0

The BackwardRef and ForwardRef numbers are displayed by AFL Editor’s Tools->Check and Profile as well as on charts when “Display chart timing” is selected in the preferences.

If you use Check and Profile tool, it will tell you that the formula

Buy Ref MAC40 ), -)

requires 71 past bars and 0 future bars.

You can modify it to

Buy Ref MAC50 ), -)

and it will tell you that it requires 82 past bars (30+50+2) and zero future bars.

If you modify it to

Buy Ref MAC50 ), )

It will tell you that it needs 80 past bars (30+50) and ONE future bar (from Ref).

Thanks to that your formula will use 80 bars prior to first visible (or in-range) bar leading to correct calculation result, while improving the speed of execution by not using bars preceding required ones.

IMPORTANT NOTES

It is very important to understand, that the above estimate requirements while fairly conservative,
and working fine in majority of cases, may NOT give you identical results with QuickAFL enabled, if your formulas use:
a) JScript/VBScript scripting
b) for/while/do loops using more than 30 past bars
c) any functions from external indicator DLLs
d) certain functions that use recursive calculation such as very long exponential averages or TimeFrame functions with much higher intervals than base interval

In these cases, you may need to use SetBarsRequired() function to set initial requirements to value higher than default 30. For example, by placing

SetBarsRequired1000)

at the TOP of your formula you are telling AmiBroker to add 1000 bars PRIOR to first visible (or in-range) bar to ensure more data to stabilise indicators.

You can also effectively turn OFF QuickAFL by adding:

SetBarsRequiredsbrAllsbrAll )

at the top of your formula. It tells AmiBroker to use ALL bars all the time.

It is also worth noting that certain functions like cumulative sum (Cum()) by default request ALL past bars to guarantee the same results when QuickAFL is enabled. But when using such a function, you may or may NOT want to use all bars. So SetBarsRequired() gives you also ability to DECREASE the requirements of formula. This is done by placing SetBarsRequired at the END of your formula, as any call to SetBarsRequired effectively overwrites previously calculated estimate. So
if you write

Cum);
SetBarsRequired1000); // use 1000 past bars DESPITE using Cum(

You may force AmiBroker to use only 1000 bars prior first visible even though Cum() by itself would require all bars.

It is also worth noting that when QuickAFL is used, BarIndex() function does NOT represent elements of the AFL array, but rather the indexes of ENTIRE quotation array. With QuickAFL turned on, an AFL array is usually shorter than quotation array, as illustrated in this picture:

QuickAFL, BarIndex and BarCount

SPECIAL CASE: AddToComposite function

Since AddToComposite creates artificial stock data it is desirable that it works the same regardless of how many ‘visible’ bars there are or how many bars are needed by other parts of the formula.

For this reason internally AddToComposite does this:

SetBarsRequiredsbrAllsbrAll )

which effectivelly means “use all available bars” for the formula. AddToComposite function simply tells the AFL engine to use all available bars (from the very first to the very last) regardless of how formula looks like. This is to ensure that AddToComposite updates ALL bars of the composite

The side-effect is that “Check And Profile” feature will see that it needs to reference future bars and display a warning even though this is false alert because AddToComposite itself has no impact on trading system at all.

Now why this shows only when flag atcFlagEnableInBacktest is on ??
It is simple: this is so because it means that AddToComposite is ACTIVE in BACKTEST.
http://www.amibroker.com/guide/afl/afl_view.php?name=ADDTOCOMPOSITE

Since “Check And Profile” uses “BACKTEST” state you get such result.

If atcFlagEnableInBacktest is not specified AddToComposite is not enabled in Backtest and hence does not affect calculation of BackwardRef and ForwardRef during “Check And Profile”.

BACKWARD COMPATIBILITY NOTES

a) QuickAFL is available in Automatic Analysis in version 5.14.0 or higher
b) sbrAll constant is available in Automatic Analysis in version 5.14.0 or higher. If you are using older versions you should use numeric constant of: 1000000 instead.

Historical portfolio backtest metrics

Recently on the AmiBroker mailing list some users expressed wish to have access to some of portfolio backtest metrics available in “historical” form (i.e. as date series, as opposed to scalars), so they can be plotted as an indicator.

Implementing such functionality is actually easy with existing tools and does not require any OLE scripts. Everything you need is small custom-backtester procedure that just reads built-in stats every bar and puts them into composite ticker.
In the accompanying indicator code all you need to do is simply use Foreign() function to access the historical metrics data generated during backtest.

The code below shows the BACKTEST formula with custom backtester part:

// Replace lines below with YOUR TRADING SYSTEM
EnableRotationalTrading();
PositionScore 1/RSI(14);
PositionSize = -25;
SetOption("WorstRankHeld");
SetOption("MaxOpenPositions"); 

////////////////////////////////////////
// BELOW IS ACTUAL CUSTOM BACKTESTER PART
// that can read any built-in metric (in this example UlcerIndex)
// and store it into composite ticker for further
// retrieval as data series

SetOption("UseCustomBacktestProc"True ); 

if( 
Status("action") == actionPortfolio )
{
  
bo GetBacktesterObject();

  
bo.PreProcess(); // Initialize backtester

  // initialize with null
  // you can have as many historical metrics as you want
  // (just duplicate line below for many metrics you want)
  
MyHistStat1 Null;
  
MyHistStat2 Null// add your own 

  
for(bar=0bar BarCountbar++)
  {
   
bo.ProcessTradeSignalsbar );
  
   
// recalculate built-in stats on EACH BAR
   
stats bo.GetPerformanceStats); 
 
   
// the line below reads the metric and stores it as array element
   // you can add many lines for each metric of your choice
   
MyHistStat1bar ] = stats.GetValue("UlcerIndex"); // get ulcer index value calculated this bar
   
MyHistStat2bar ] = stats.GetValue("WinnersPercent"); // add your own

  
}

  
bo.PostProcess(); // Finalize backtester

  // now STORE the historical data series representing the metric of your choice
  // duplicate the line below for as many metrics as you want
  
AddToCompositeMyHistStat1"~~~UI_HISTORICAL""X"atcFlagEnableInPortfolio atcFlagDefaults );

  
// you can add your own as shown below
  
AddToCompositeMyHistStat2"~~~WP_HISTORICAL""X"atcFlagEnableInPortfolio atcFlagDefaults ); 

In the code above, for illustration purposes, we are exporting UlcerIndex and Winners Percent metrics as data series. They are stored in composite tickers for easy retrieval from indicator level.
You can easily extend code to include ANY number of metrics you want.

Now in order to Plot metrics as indicators, use this simple formula:

PlotForeign("~~~UI_HISTORICAL""UlcerIndex Historical"colorRedstyleLine );
PlotForeign("~~~WP_HISTORICAL""Winners Percent"colorBluestyleLine styleOwnScale )

As you can see with one Foreign function call you can read the historical value of any metric generated by the backtester.

NOTE: when running backtest please setup a filter in AA that EXCLUDES composites (group 253) from backtest set.

Getting started with automatic Walk-Forward optimization

Recently released AmiBroker 5.05 BETA features the automatic Walk-Forward Optimization mode.

The automatic Walk forward optimization is a system design and validation technique in which you optimize the parameter values on a past segment of market data (“in-sample”), then test the system forward in time on data following the optimization segment (“out-of-sample”). You evaluate the system based on how well it performs on the test data (“out-of-sample”), not the data it was optimized on.

To use Walk-Forward optimization please follow these steps:

  1. Goto Tools->Automatic Analysis
  2. Click Settings button, then switch to “Walk-Forward tab”
  3. Here you can see Walk forward settings for In-sample optimization, out-of-sample backtest
    “Start” and “End” dates mark initial period begin / end
    This period will be moved forward by “Step” until the “End” reaches the “Last” date.
    The “Start” date can move forward by “step” too, or can be anchored (constant) if “Anchored” check is on.
    If you mark “Use today” then “Last” date entered will be ignored and TODAY (current date) will be used instead

    By default an “EASY MODE” is selected which simplifies the process of setting up WF parameters.
    It assumes that:
    a) Out-of-sample segment immediatelly follows in-sample segment
    b) the length of out-of-sample segment equals to the walk-forward step

    Based on these two assumptions the “EASY” mode takes in-sample END date and sets
    out-of-sample START date to the following day. Then adds in-sample STEP and this becomes out-of-sample END date.
    In-sample and Out-of-sample step values are set to the same values.

    The “EASY” mode guarantees correctness of WF procedure settings.

    In the “ADVANCED” mode, the user has complete control over all values, to the extent that
    they may not constitute valid WF procedure.
    The interface allows to selectivelly disable in-sample and out-of-sample phases using checkboxes at top
    (for special things like runnign sequential backtests without optimization).

    All settings are immediatelly reflected in the PREVIEW list that shows all generated IS/OOS segments and their dates.

    The “Optimization target” field defines the optimization raport COLUMN NAME that
    will be used for sorting results and finding the BEST one. Any built-in column can be used
    (as appears in the optimization output), or you can use any custom metric that you define
    in custom backtester. The default is CAR/MDD, you can however select any other built-in metric from the combo.
    You can also TYPE-IN any custom metric that you have added via custom backtester interface.

  4. Once you defined Walk-Forward settings, please go to Automatic Analysis and
  5. press the dropdown ARROW on the Optimize button and select “Walk Forward Optimization”

This will run sequence of optimizaitons and backtest and the results will be displayed in the “Walk Forward” document that is open in the main application frame.
When optimization is running you can click “MINIMIZE” button on the Progress dialog to minimize it – this allows to see the Walk Forward output during the optimization steps.

IN-SAMPLE and OUT-OF-SAMPLE combined equity

Combined in-sample and out-sample equities are available by
~~~ISEQUITY and ~~~OSEQUITY composite tickers (consecutive periods of IS and OOS are concatenated and scaled to
maintain continuity of equity line – this approach assumes that you generally speaking are compounding profits)
To display IS and OOS equity you may use for example this:

PlotForeign("~~~ISEQUITY","In-Sample Equity"colorRedstyleLine);
PlotForeign("~~~OSEQUITY","Out-Of-Sample Equity"colorGreenstyleLine);
Title "{{NAME}} - {{INTERVAL}} {{DATE}} {{VALUES}}"

How to detect the study crossover for multiple symbols with use of SCAN

It’s possible to use Automatic Analysis window to search for trendline (or other study) crossovers for multiple symbols at once. It’s necessary to do the following:

1. Draw trendlines on the chart and assidn them a STUDY ID – two letter code that allows to recognise the particular study. To do this, go to study properties (Alt+Enter) after you draw the line (in this example – StudyID = “RE”).

study1.gif

2. Repeat the process for other symbols (remember to draw the trendlines in the same chart pane).

3. Check the CHART ID (in order to call this particular chart pane from the SCAN). To check the ChartID – click on the chart with right mouse button, go to: PARAMETERS -> Axes&Grid (in this example – CHARTID = 1023).

study2.gif

4. Now we can write the formula:
– Analysis -> Formula Editor
– enter:

Buy = Cross( Close, Study(“RE”, 1023) );

(note that we use the same StudyID and ChartID in the formula)
– Tools -> Send to analysis.
– Apply To: All Symbols, All Quotations
– press SCAN

How to close open positions at the end of the day (for daytraders)

If we are backtesting the intraday strategy and we do not want to keep open positions overnight – then it’s necessary to force closing all the open positions before the session end. In order to code it in AFL – the easiest is to use TimeNum() function for that purpose. (more…)

« Previous PageNext Page »