Вы находитесь на странице: 1из 116

Introduction to

AmiBroker Coding

June 5, 2014
Disclaimer:

The Connors Group, Inc. ("Company") is not an investment advisory service, nor a registered investment advisor or broker-dealer and does not
purport to tell or suggest which securities customers should buy or sell for themselves. The analysts and employees or affiliates of Company may
hold positions in the stocks or industries discussed here. You understand and acknowledge that there is a very high degree of risk involved in trading
securities. The Company, the authors, the publisher, and all affiliates of Company assume no responsibility or liability for your trading and investment
results. Factual statements on the Company's website, or in its publications, are made as of the date stated and are subject to change without notice.

It should not be assumed that the methods, techniques, or indicators presented in these products will be profitable or that they will not result in losses.
Past results of any individual trader or trading system published by Company are not indicative of future returns by that trader or system, and are not
indicative of future returns which be realized by you. In addition, the indicators, strategies, columns, articles and all other features of Company's
products (collectively, the "Information") are provided for informational and educational purposes only and should not be construed as investment
advice. Examples presented on Company's website are for educational purposes only. Such set-ups are not solicitations of any order to buy or sell.
Accordingly, you should not rely solely on the Information in making any investment. Rather, you should use the Information only as a starting point
for doing additional independent research in order to allow you to form your own opinion regarding investments. You should always check with your
licensed financial advisor and tax advisor to determine the suitability of any investment.

HYPOTHETICAL OR SIMULATED PERFORMANCE RESULTS HAVE CERTAIN INHERENT LIMITATIONS. UNLIKE AN ACTUAL
PERFORMANCE RECORD, SIMULATED RESULTS DO NOT REPRESENT ACTUAL TRADING AND MAY NOT BE IMPACTED BY BROKERAGE
AND OTHERSLIPPAGE FEES. ALSO, SINCE THE TRADES HAVE NOT ACTUALLY BEEN EXECUTED, THE RESULTS MAY HAVE UNDER- OR
OVER-COMPENSATED FOR THE IMPACT, IF ANY, OF CERTAIN MARKET FACTORS, SUCH AS LACK OF LIQUIDITY. SIMULATED TRADING
PROGRAMS IN GENERAL ARE ALSO SUBJECT TO THE FACT THAT THEY ARE DESIGNED WITH THE BENEFIT OF HINDSIGHT. NO
REPRESENTATION IS BEING MADE THAT ANY ACCOUNT WILL OR IS LIKELY TO ACHIEVE PROFITS OR LOSSES SIMILAR TO THOSE
SHOWN.

The Connors Group, Inc.


10 Exchange Place, Ste 1800
Jersey City, NJ 07302

Copyright © The Connors Group, Inc., 2014.


Welcome!

3
Course Objectives

AmiBroker is a powerful technical analysis program,


with advanced charting, back-testing and scanning
capabilities. Utilized by traders around the world, it’s
the primary tool used by the Connors Research
team to develop and test our strategies. Most
importantly, it just might be the solution that will help
make you a better, more profitable trader by giving
you the power to validate your own strategies and
find your own trade setups.

4
Course Objectives

This course is designed for traders who want to use


AmiBroker to create simple back tests and/or
generate trading signals, but who have little or no
familiarity with AFL, the AmiBroker scripting
language.

5
Course Objectives

At the completion of this course, you will be able to:

• Create, modify, and execute simple AFL scripts


• Create your own custom indicator, and add it to an
AmiBroker chart
• Use AmiBroker’s “Exploration” functionality for
troubleshooting or data generation
• Run a simple “all trades” back test
• Verify that your back test results are correct
• Generate trading signals

6
Class Preparation

By the time we start the class, you should have


accomplished the following tasks:

• Installed AmiBroker version 5.5 or later.


• Installed a data source and configured it to work
with AmiBroker.
• Downloaded the samples and code templates.

7
Agenda
1. AmiBroker from 10,000 Feet
2. Data Sources
3. Auto Analysis Window
4. Coding Part 1
• Exercise: Running a Scan
5. Coding Part 2
6. Coding: Explorations
• Exercise: Creating an Exploration
7. Coding: Indicators
• Exercise: Adding a Custom Indicator
8. Back Testing
• Exercise: Running a Back Test
9. Common Mistakes
10. Additional Sources and Q&A

8
Agenda

As you can see, we have a very full day ahead of us.

In general, our exercise sessions will serve double-


duty as your opportunity to take a quick break if you
need one.

If time allows, we’ll also take a break midway


through the agenda so people can refuel.

We will have a Q&A session at the end of the day,


but feel free to type in your questions as we go.

9
Let’s Get Started!

10
AmiBroker From 10,000 Feet

11
AmiBroker From 10,000 Feet

AmiBroker is a comprehensive technical analysis


program, with advanced charting, back-testing and
scanning capabilities.

Let’s quickly cover some of the major areas of


functionality:
• Charting
• Auto Analysis
• Preferences
• Help

12
AmiBroker From 10,000 Feet

Charting Demo
1. Create a new chart
2. Change the style from candles to bars
3. Change the time period
4. Add an indicator

13
AmiBroker From 10,000 Feet

Auto Analysis Overview


1. Scan: Generate Trade Signals
2. Explore: Query the Database
3. Backtest: Simulate Actual Trades
4. Optimize: A series of backtests

We will go into much greater detail later in the day!

14
AmiBroker From 10,000 Feet

Preferences Demo
1. Data
2. Intraday
3. AFL
4. Editor

15
AmiBroker From 10,000 Feet

Help Demo
1. Contents
2. Tutorial
3. Search

The AmiBroker Help files are a fantastic resource.


Always go here first when you get stuck!

16
Data Sources

17
Data Sources

AmiBroker does not directly provide any useful price


data. Rather, it is a set of tools which can be used
with data from a variety of providers, including
Norgate, CSI, Telechart, Yahoo and others.

18
Data Sources

When selecting a data provider, you need to


consider the following items:

• Frequency of updates
• Historically adjusted data
• Delisted securities and survivorship bias
• Database speed
• Index constituents
• Watch Lists & Groups
• Price

19
Data Sources

Norgate
• Delisted data available
• Flexibility in how to adjust prices for splits and
dividends
• Member data available for many major indices
• Many watch lists and groups already defined
• Good integration with AmiBroker
• Today’s price data available only after the close
• Moderately priced
• Many of the most helpful features are still in alpha
test

20
Data Sources

CSI Data
• High quality data, very visible customers such as
Yahoo Finance
• Delisted data available
• Split and dividend adjusted prices available via
Unfair Advantage product, which is for personal
use only
• For commercial use, all data is unadjusted
• Relatively expensive compared to other options

21
Data Sources

Telechart
• Delisted data unavailable
• Prices adjusted for splits, but not dividends
• Newer versions of product are not compatible with
AmiBroker
• Delayed data available throughout the day
• Inexpensive

22
Data Sources

Yahoo Finance / Google Finance / MSN Money


• Delisted data unavailable
• Adjusted closing price available, but not other
prices
• Delayed data available throughout the day
• FREE!

23
The Auto Analysis Window

24
Auto Analysis

The Auto Analysis window will be your home base


for any of the analysis tasks that you might wish to
perform in AmiBroker, including scans and back
tests.

25
Auto Analysis

Before you can perform any type of analysis, you


need to make selections for each of the following:
1. Formula: Specify the AFL file containing the
analysis code that you wish to execute
2. Apply To: Will you be analyzing a single symbol,
all symbols, or a filtered list such as a watch list?
3. Range: Set the dates that you want the test
results to cover
4. Settings: Long or Short? Periodicity?
5. Parameters: Depending on how your script is
written, you may be able to specify input
parameters without changing the AFL code.

26
Auto Analysis

Once you’ve defined your testing environment,


you’re ready to execute one of the four types of
analysis:
1. Scan
2. Explore
3. Backtest
4. Optimize

27
Auto Analysis

Backtest Demo
1. Result List: Trade List or Detailed Log
2. Info
3. Report: Test Metrics

28
Auto Analysis

Watch lists
Defining a watch list, or universe, can be helpful for
a variety of reasons, including:
• Limits your analysis to a desired group of
securities which might be impossible to identify
with coding rules, for example “Commodity ETFs”
or “Stocks with Weekly Options”.
• Speeds up your analysis by “prescreening” a set
of securities, for example “stocks with volume
greater than 1M shares”.
• Allows you to compare results of different
analyses with the confidence of knowing that the
same securities were used for each test.
29
Auto Analysis

Watch lists
You can specify a watch list name by selecting Apply
To “Filter”, and then clicking the funnel icon.

Watch lists can be used to Include or Exclude


symbols to test.

30
Auto Analysis

Watch lists
There are three primary ways to create a watch list:
1. Selecting symbols one at a time and adding them
to a new or existing watch list.
2. Right clicking a set of analysis results in the
Result List and selecting Add Results to Watch
List or Replace Watch List with Results.
3. Importing a CSV file as a watch list with
Symbol/Watch List/New… and Symbol/Watch
List/Import…

31
Coding Scans:
Creating and Running Your
First AFL Script

32
Coding Scans

In this session, we will introduce the AFL scripting


language and the tools for creating and running your
first script.

Fortunately, you need only a limited set of


commands to implement a basic script, particularly if
you have a template to start from.

However, AmiBroker contains a rich set of indicators


and other functions that will ultimately allow you to
test a wide variety of trading ideas.

33
Coding Scans

AmiBroker Formula Language, or AFL, is a special


programming language used to define and create
custom indicators, scans, explorations, backtests
and optimizations.

An AFL script is simply a text file with the file


extension “.afl”. AmiBroker interprets this script to
carry out your commands.

34
Coding Scans

Because AFL scripts are text files, you can choose


the editor that you want to use:

1. The built-in Formula Editor (available from the


Analysis menu).
2. An external text editor such as Notepad++ or
your favorite code editor.

35
Coding Scans

AmiBroker Formula Editor


The built-in formula editor contains a number of
helpful features, including:

• Syntax highlighting
• Context-sensitive help via F1
• Access to all AmiBroker Help
• Auto-save before running an analysis
• Syntax Verification

36
Coding Scans

AmiBroker Formula Editor


Unfortunately, it’s not the greatest code/text editor:

• No block indent
• No Ctrl-F3 search
• Double-click selects text plus following space
• Other pet peeves or “missing” features

37
Coding Scans

External Text Editor


If you’re accustomed to another editor, particularly
one that’s optimized for coding, you can use that
instead. I like Notepad++ because:

• Syntax highlighting available by creating a User


Defined Language. See:
http://www.amibroker.com/library/detail.php?id=1414
• Implements many of the keyboard conventions of
various Microsoft editors that I’ve used throughout
the years.

38
Coding Scans

Basic Elements
Now that we’ve selected a tool to use, we can start
to look at the basic elements that comprise a script.

Like many programming languages, AFL allows you


to assign values to variables and to call functions
that perform specific actions.

There are 3 types of variables in AmiBroker:


1. Strings (text)
2. Scalars (a single floating point number)
3. Arrays (a set of floating point numbers)

39
Coding Scans

Arrays
Arrays in AmiBroker are different than in most other
languages, because every array has the same
number of elements.

There is one element for each bar in the test. If your


test is being run on daily bars, this means there is
one element for each trading day in the test.

Also, you can perform operations on arrays as if


they were scalars. We will see examples of this
when we review the code templates.

40
Coding Scans

Standard Array Variables


AmiBroker defines a set of standard array variables
that are used to control the behavior of your analysis.
Some of the most common ones are:

• Open(0) / High(H) / Low(L) / Close (C)


• Volume (V), Open Interest (OI), Aux 1 (1), Aux 2 (2)
• Buy / Sell / Short / Cover
• BuyPrice / SellPrice / ShortPrice / CoverPrice

41
Coding Scans

Your First Functions


So that you’re able to write an interesting scan, we will
introduce just two basic functions:

• Ref()
• MA()

42
Coding Scans

The Ref() Function


References past or future values in an array. The
AmiBroker User’s Guide says:

SYNTAX Ref( ARRAY, period )


RETURNS ARRAY
FUNCTION References a previous or subsequent element in an ARRAY. A
positive period references "n" periods in the future; a
negative period references "n" periods ago. The function
accepts period parameter that can be constant as well as
time-variant (array).
EXAMPLE The formula "ref( CLOSE, -14 )" returns the closing price 14
periods ago. Thus, you could write the 14-day price rate-of-
change (expressed in points) as "C - ref( C, -14 )." The
formula "ref( C, 12 )" returns the closing price 12 periods
ahead (this means looking up the future) .
43
Coding Scans

The Ref() Function – Example


If we wanted to find all the days on which today’s
close is less than the previous day’s close, we could
use this AFL:
LowerClose = C < Ref(C,-1);

The result would be an array of true/false values, as


seen on the next slide.

44
Coding Scans

The Ref() Function – Example

Bar C Ref(C,-1) C < Ref(C,-1)


0 $12.27 {Empty} False
1 $12.50 $12.27 False
2 $12.42 $12.50 True
3 $11.98 $12.42 True
4 $12.21 $11.98 False
5 $12.35 $12.21 False
6 $12.40 $12.35 False
7 $12.25 $12.40 True

45
Coding Scans

The MA() Function


Calculates the simple moving average. The AmiBroker
User’s Guide says:

SYNTAX ma( ARRAY, periods)

RETURNS ARRAY

FUNCTION Calculates a periods simple moving average of ARRAY. The


function accepts periods parameter that can be constant as
well as time-variant (array).
EXAMPLE ma(CLOSE, 5 )

46
Coding Scans

The MA() Function – Example

Bar C MA(C,3)
0 $2 {Empty}
1 $3 ${Empty}
2 $4 $3
3 $11 $6
4 $6 $7
5 $10 $9

47
Coding Scans

Scan
A Scan is the quickest, easiest way to generate a set
of signals from your trading rules.

For a long strategy, all you really need to do is define


two variables: Buy and Sell.

Before we begin, let’s review the code template for a


scan: AFL-Scan.afl

48
Coding Scans

Scan
To execute a Scan, open the AFL file from Formula
bar in the Auto Analysis window.

Set up your environment, including the “Apply To”


and “Range” fields.

Press the “Scan” button.

49
Exercise: Running a Scan

50
Exercise: Running a Scan

For this exercise, please modify the AFL-Scan.afl file


to implement the following rules:

Buy SPY when today’s close is lower than the


previous day’s close.

Sell the position when today’s close is above the


5-day moving average, or MA(5).

Use the AmiBroker Scan feature to find all Buy and


Sell signals from the month of April 2014.

51
Exercise: Running a Scan

Let’s review the results and verify that they look


correct.

52
Coding Explorations:
Adding Flexibility To A Scan

53
Coding Explorations

AmiBroker Explorations allow you to easily extract


data, format and present that data in AmiBroker, and
export it to a CSV file that can be opened with Excel.

In this session we will discuss the variables and


functions used to create an Exploration, as well as
how to execute an Exploration and export the data.

54
Coding Explorations

New Variables

• Filter: When this variable is True, the exploration


will output one row of data

55
Coding Explorations

New Functions
See full details in the AmiBroker Help file.

• AddColumn(): Adds a new numeric column to the


exploration result list.

• AddTextColumn(): Adds a new text column to the


exploration result list.

56
Coding Explorations

New Functions
See full details in the AmiBroker Help file.

• SetSortColumns: Controls the order of the output.

• ExRem(): Removes extra non-zero values in an


array. For example, the AFL:
Buy = ExRem(Buy, Sell);

Will remove extra Buy signals between the initial


occurrence of a Buy Signal (i.e. the first Buy after a
Sell) and the matching Sell signal.

57
Coding Explorations

The ExRem() Function – Example

Bar Buy Sell ExRem(Buy,Sell) ExRem(Sell,Buy)


0 True False True False
1 True False False False
2 False True False True
3 True False True False
4 False False False False
5 False True False True
6 False True False False
7 True True True False
8 False True False True

58
Coding Explorations

Exploration
An AmiBroker Exploration is similar to a Scan,
except that it provides a lot more flexibility.

Define the Filter variable as well as any other values


that you wish to display as part of the Exploration.

Use AddColumn() to format and display the values.

Before we begin, let’s review the code template for


an Exploration: AFL-Explore.afl

59
Coding Explorations

Explore
To execute an Exploration, open the AFL file from
Formula bar in the Auto Analysis window.

Set up your environment, including the “Apply To”


and “Range” fields.

Press the “Explore” button.

60
Exercise: Running an
Exploration

61
Exercise: Running an Exploration

For this exercise, we will use the same Buy and Sell
rules that we defined for the Scan exercise:
Buy SPY when today’s close is lower than the
previous day’s close.

Sell the position when today’s close is above the


5-day moving average, or MA(5).

62
Exercise: Running an Exploration

Use the AmiBroker Explore feature to display all Buy


and Sell signals from the month of April 2014.

In addition, display the closing price for SPY and the


5-day moving average of the closing price.

63
Exercise: Running an Exploration

Let’s review and verify the results.

64
Coding Indicators:
Enhancing Your Charts

65
Coding Indicators

AmiBroker allows you to easily add built-in indicators


like RSI and Moving Averages to your charts. But
what if you want to plot a custom indicator like
ConnorsRSI?

In this coding session, we will discuss the AFL


commands that are required for creating a custom
indicator, as well as how to add that indicator to the
AmiBroker environment.

66
Coding Indicators

New Functions
See full details in the AmiBroker Help file.

• Plot(): Draws the data points for an array on a chart.

• Param(): Adds a new user-definable parameter,


which will be accessible via Parameters dialog.

67
Coding Indicators

Examples
We will now review two examples of custom
indicators:

• ConnorsRSI.afl

• Historical Volatility.afl

68
Coding Indicators

Accessing a Custom Indicator


To make a custom indicator accessible from an
AmiBroker chart, either copy an existing AFL file or
save a new file into the …/Formulas/Custom directory
within your AmiBroker installation directory.

The new indicators should now appear under the


Custom folder of the Charts pane on the left side of
the AmiBroker window.

69
Exercise: Adding Custom
Indicators

70
Exercise: Adding Custom Indicators

During this hands-on exercise, you will add the


ConnorsRSI and Historical Volatility indicators to
your AmiBroker environment.

71
Exercise: Adding Custom Indicators

Find the ConnorsRSI.afl and Historical Volatility.afl


files and copy them to your Formulas\Custom
directory.

Open an AmiBroker chart and verify that you can


display ConnorsRSI as a blue line using the default
input parameters.

Now add both HV(100) and HV(50) to a single chart


pane, using different colors for each.

72
Coding: Additional
Concepts

73
Coding: Additional Concepts

In this coding session, we will introduce several


more common AFL functions, as well as standard
constructs like conditionals (if-then-else) and loops.

We will then move on to some typical trading


strategy concepts like setups, limit orders, stop
losses and profit targets.

74
Coding: Additional Concepts

New Functions: AB Environment

• SetOption() & GetOption(): These functions


allow you to control many aspects of the AB
environment that are available in the Settings
dialog.
• Status(): Provides run-time status of the analysis
engine.
• BarIndex(): Returns the zero-based bar number.

75
Coding: Additional Concepts

New Functions: Math

• Min() & Max(): Minimum and Maximum of two


values or two arrays.
• HHV() & LLV(): Highest High Value and Lowest
Low Value of N previous values in an array
• StDev(): Standard Deviation
• Sum(): Sum of N previous values in an array
• Cum(): Cumulative sum of all values in an array
• LastValue(): The final value in an array

76
Coding: Additional Concepts

New Functions: Array References

• Ref(): References a previous or subsequent


element in an array.
• BarsSince(): Returns the number of bars since
an array contained a non-zero value.
• IIf(): Conditionally assigns values to the elements
of an array based on a conditional expression.

77
Coding: Additional Concepts

New Functions: Indicators


These are the indicators most commonly used in our
swing trading strategies. There are many others
available.

• MA(): Simple Moving Average


• EMA(): Exponential Moving Average
• RSIa(): Wilder’s RSI
• ROC(): Rate of Change over N periods
• PercentRank(): Percentile Ranking
• ATR(): Average True Range

78
Coding: Additional Concepts

Arithmetic Operators
In addition to the standard +, -, *, / operators, you
may wish to use the following:

• = Assignment.
• ++ Increment. ++var is equivalent to var = var+1
• -- Decrement. --var is equivalent to var = var-1
• += Compound assignment. v1 += v2 is equivalent
to v1 = v1+ v2 Similarly for -=, *=, /=
• ^ Exponentiation.
• % Modulus (remainder)
• | Bitwise OR
• & Bitwise AND 79
Coding: Additional Concepts

Logical Operators
These are operators that return a logical value (True
or False). Some will be familiar, others may not be.

• <, <=, >, >= : The standards from algebra


• == : True if the operands are equal
• != : True if the operands are not equal
• NOT: True when the operand is false, and vice
versa
• AND: True when both operands are True
• OR: True when either of the operands are True

Do not confuse == (equality) with = (assignment)! 80


Coding: Additional Concepts

Conditionals
Conditional statements allow you to execute code
only when a defined set of conditions is true at run
time.

The most common conditional statements are:


• if – else
• iif (discussed previously)
• switch

81
Coding: Additional Concepts

Conditionals: if-else
Here is the format for an if-else statement. Note that
the entire “else” clause is optional.

if (logical expression)
{
code to execute if logical expression is true
}
else
{
code to execute if logical expression is false
}

82
Coding: Additional Concepts

Conditionals: switch
A switch statement executes one of N different code
blocks based on the value of the input expression.

switch (expression)
{
case 1:
code executed if expression is equal to 1
break;
case 2:
code executed if expression is equal to 2
break;
default:
code executed if expression is not equal to any of
the previous case statements
break;
}
83
Coding: Additional Concepts

Iteration (Looping)
AmiBroker looping constructs include:

• for: Repeat a block of code a specified number of


times.
• while: Repeat a block of code until a specified
condition becomes false. The condition is
evaluated before the block of code.
• do-while: Repeat a block of code until a specified
condition becomes false. The condition is
evaluated after the block of code.

84
Coding: Additional Concepts

Iteration: for()
A typical for loop might look like this:

for (bar=0; bar < BarCount; ++bar)


{
code to execute each time through the loop
}

85
Back Testing Mechanics

86
Back Testing Mechanics

A back test allows us to see how a trading strategy


might have performed over some time period in the
past when applied to a specific set of securities.

Although the historical results produced by a back


test are no guarantee of how the strategy will
perform in the future, they can still provide valuable
insights into the strategy’s strengths and
weaknesses.

87
Back Testing Mechanics

Setting Up the Environment

• Auto Analysis Settings


• Range: Specify the date range to test
• Apply To: Set the watch list or current symbol

88
Back Testing Mechanics

How a Back Test Works

AmiBroker does a lot of work behind the scenes


when you execute a back test. However, the high-
level process is not too complex.

89
Back Testing Mechanics

How a Back Test Works – Major Phases

• One pass through your main AFL for each security


that’s included in the back test. Arrays are sized
and aligned according to the bars of data
available for the currently active symbol.
• All trade signals are consolidated and ranked
according to PositionScore. Arrays are aligned to
the dates specified for the back test.
• Trade signals are processed.
• Output of results (trade list, detailed log, report)

90
Back Testing Mechanics

Back Testing – Viewing Results


After you’ve run a back test, results will be available
in three different places:

• Result List Tab: The primary output from the


back test, which can be a trade list, detailed log,
or summary, depending on the Report settings.
• Info Tab: Provides minimal summary information
including number of rows of output, timing, etc.
• Back Test Report: Summary metrics for the test.

91
Back Testing Mechanics

Troubleshooting
If your back test does not seem to be performing
correctly, consider using Scan or Explore to track
down the problem.

• Scan: You can run a Scan without modifying your


back testing AFL at all. However, you will get
limited debugging information (trade signals only).
• Exploration: By adding a Filter and some
AddColumn statements to your AFL, you can drill
down on specific entry/exit conditions. Leaving
these additional statements in your back test will
not hurt anything.
92
Back Testing Mechanics

Let’s now review the back testing code template.

93
Exercise: Running a
Back Test

94
Exercise: Running a Back Test

This hands-on exercise will give you an opportunity


to run a back test on the strategy described in the
Strategy Guidebook provided with the course
materials.

You may implement the strategy rules yourself, or


use the fully functional version of the AFL included
with the other code samples.

This version can be used to verify your own results,


or as a template from which to make modifications to
the strategy.

95
Exercise: Running a Back Test

ConnorsRSI Selective: Buy Setup

1. The average volume over the past 21 days must


be at least 250,000 shares.
2. The closing price must be at least $5 per share.
3. The average value of ConnorsRSI (3,2,100) over
2 days is less than 15.
4. The value of ConnorsRSI on the day the Setup is
completed is the lowest value of ConnorsRSI in 2
days.
5. On the day the Setup is completed, the stock
closes above its 200-day moving average.

96
Exercise: Running a Back Test

ConnorsRSI Selective: Buy

6. Buy the stock at the close on the day all Setup


conditions are met.

ConnorsRSI Selective: Sell

7. Sell the stock when it closes with a ConnorsRSI


value greater than 70.

97
Exercise: Running a Back Test

Running the Back Test:

1. Open your AFL file from the Auto Analysis window.


2. Set the date range from January 2014 through
present
3. If available, specify an appropriate watch list.
4. Click the Back Test button to execute the test.

98
Exercise: Running a Back Test

Now let’s review the results:

1. Trade List
2. Back Test Report

99
More Back Testing
Techniques

100
Back Testing Techniques

In this session we will discuss additional concepts


that can enhance and expand your back testing
repertoire.

101
Back Testing Techniques

All Trades vs. Portfolio Tests

At Connors Research, most of our tests fall into one


of two categories:

• All Trades
• Portfolio

102
Back Testing Techniques

All Trades Tests


All Trades Tests are designed to find all trading
signals without regard to portfolio constraints. The
results provide metrics like Average % P/L, Average
Hold Time, and Win Rate (% Winners).

• 1 share per trade


• No commissions
• No Interest on cash
• Unlimited open positions

103
Back Testing Techniques

Portfolio Tests
Portfolio Tests attempt to model the way someone
would actually trade a strategy. In addition to the
“per trade” metrics, we can calculate things like
CAR, Sharpe Ratio, and Max Drawdown.

• Position sizing model determines the dollars


allocated to each trade.
• Commissions included, typically $0.01/share.
• Interest on cash determined by T-Bill rate.
• Open positions limited by position sizing model.

104
Back Testing Techniques

As we discussed during an earlier session, it’s very


important to consider each of the following:

• Adjusted prices: when to use them

• Delisted securities: no survivorship bias

• Historical index constituents: important if your


trading universe will the a major index like the
S&P 500

105
Back Testing Techniques

Curve Fitting
Some people claim that back testing is just an
elaborate exercise in curve fitting.

We believe that back testing performs a useful


function by providing information on how a strategy
has performed in the past, although of course that’s
no guarantee of how it will perform in the future.

To avoid curve fitting, you should always begin with


a solid thesis that you wish to test. You should also
see predictable patterns in your results when you
vary the input parameters.

106
Back Testing Techniques

Additional Testing Concepts


Today we’ve focused on the basics of the various
types of analysis available through AmiBroker.

You may also wish to explore some of the following:


• Limit Orders
• Stop Losses
• Profit Targets

107
Back Testing Techniques

Limit Orders
Buying on a limit order means that you only enter
the trade when the price falls below some
predetermined limit, typically a percentage below the
previous day’s close.

Let’s review the AFL for the Limit version of the


CRSI Selective strategy to see how the code has to
change to accommodate limit entries.

108
Back Testing Techniques

Stop Losses and Profit Targets


Stop losses and profit targets are an alternative form
of exiting a trade.

AmiBroker provides a variety of options for


evaluating when these stop conditions have been
met, and also when to exit the trade.

See the ApplyStop() function in the Help file.

109
Common Mistakes

110
Common Mistakes

Some mistakes quickly become obvious because your


AFL doesn’t work as expected. Others are more subtle.

111
Common Mistakes

Things to watch out for include:

• Using = instead of ==
• Using “if” instead of “iff”
• Not exiting when a security stops trading
• Looking into the future, for example using today’s
closing price when entering a trade intraday
• Using incorrect entry/exit prices
• Not setting Max Positions appropriately

112
Additional Sources

Additional Sources of Information

• AmiBroker web site


• Yahoo Discussion Boards
• “Quantitative Trading Systems” by Howard Bandy
• “Introduction To AmiBroker” by Howard Bandy

Send questions to: mradtke@connorsresearch.com

113
Q&A

114
Thank You!

115
Disclaimer:

Connors Research, LLC ("Company") is not an investment advisory service, nor a registered investment advisor or broker-dealer and does not
purport to tell or suggest which securities customers should buy or sell for themselves. The analysts and employees or affiliates of Company may
hold positions in the stocks or industries discussed here. You understand and acknowledge that there is a very high degree of risk involved in trading
securities. The Company, the authors, the publisher, and all affiliates of Company assume no responsibility or liability for your trading and investment
results. Factual statements on the Company's website, or in its publications, are made as of the date stated and are subject to change without notice.

It should not be assumed that the methods, techniques, or indicators presented in these products will be profitable or that they will not result in losses.
Past results of any individual trader or trading system published by Company are not indicative of future returns by that trader or system, and are not
indicative of future returns which be realized by you. In addition, the indicators, strategies, columns, articles and all other features of Company's
products (collectively, the "Information") are provided for informational and educational purposes only and should not be construed as investment
advice. Examples presented on Company's website are for educational purposes only. Such set-ups are not solicitations of any order to buy or sell.
Accordingly, you should not rely solely on the Information in making any investment. Rather, you should use the Information only as a starting point
for doing additional independent research in order to allow you to form your own opinion regarding investments. You should always check with your
licensed financial advisor and tax advisor to determine the suitability of any investment.

HYPOTHETICAL OR SIMULATED PERFORMANCE RESULTS HAVE CERTAIN INHERENT LIMITATIONS. UNLIKE AN ACTUAL
PERFORMANCE RECORD, SIMULATED RESULTS DO NOT REPRESENT ACTUAL TRADING AND MAY NOT BE IMPACTED BY BROKERAGE
AND OTHERSLIPPAGE FEES. ALSO, SINCE THE TRADES HAVE NOT ACTUALLY BEEN EXECUTED, THE RESULTS MAY HAVE UNDER- OR
OVER-COMPENSATED FOR THE IMPACT, IF ANY, OF CERTAIN MARKET FACTORS, SUCH AS LACK OF LIQUIDITY. SIMULATED TRADING
PROGRAMS IN GENERAL ARE ALSO SUBJECT TO THE FACT THAT THEY ARE DESIGNED WITH THE BENEFIT OF HINDSIGHT. NO
REPRESENTATION IS BEING MADE THAT ANY ACCOUNT WILL OR IS LIKELY TO ACHIEVE PROFITS OR LOSSES SIMILAR TO THOSE
SHOWN.

Connors Research, LLC


10 Exchange Place, Ste 1800
Jersey City, NJ 07302

Copyright © The Connors Group, Inc., 2014.

116

Вам также может понравиться