Академический Документы
Профессиональный Документы
Культура Документы
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.
3
Course Objectives
4
Course Objectives
5
Course Objectives
6
Class Preparation
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
9
Let’s Get Started!
10
AmiBroker From 10,000 Feet
11
AmiBroker From 10,000 Feet
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
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
16
Data Sources
17
Data Sources
18
Data Sources
• 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
23
The Auto Analysis Window
24
Auto Analysis
25
Auto Analysis
26
Auto Analysis
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.
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
33
Coding Scans
34
Coding Scans
35
Coding Scans
• Syntax highlighting
• Context-sensitive help via F1
• Access to all AmiBroker Help
• Auto-save before running an analysis
• Syntax Verification
36
Coding Scans
• No block indent
• No Ctrl-F3 search
• Double-click selects text plus following space
• Other pet peeves or “missing” features
37
Coding Scans
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.
39
Coding Scans
Arrays
Arrays in AmiBroker are different than in most other
languages, because every array has the same
number of elements.
40
Coding Scans
41
Coding Scans
• Ref()
• MA()
42
Coding Scans
44
Coding Scans
45
Coding Scans
RETURNS ARRAY
46
Coding Scans
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.
48
Coding Scans
Scan
To execute a Scan, open the AFL file from Formula
bar in the Auto Analysis window.
49
Exercise: Running a Scan
50
Exercise: Running a Scan
51
Exercise: Running a Scan
52
Coding Explorations:
Adding Flexibility To A Scan
53
Coding Explorations
54
Coding Explorations
New Variables
55
Coding Explorations
New Functions
See full details in the AmiBroker Help file.
56
Coding Explorations
New Functions
See full details in the AmiBroker Help file.
57
Coding Explorations
58
Coding Explorations
Exploration
An AmiBroker Exploration is similar to a Scan,
except that it provides a lot more flexibility.
59
Coding Explorations
Explore
To execute an Exploration, open the AFL file from
Formula bar in the Auto Analysis window.
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.
62
Exercise: Running an Exploration
63
Exercise: Running an Exploration
64
Coding Indicators:
Enhancing Your Charts
65
Coding Indicators
66
Coding Indicators
New Functions
See full details in the AmiBroker Help file.
67
Coding Indicators
Examples
We will now review two examples of custom
indicators:
• ConnorsRSI.afl
• Historical Volatility.afl
68
Coding Indicators
69
Exercise: Adding Custom
Indicators
70
Exercise: Adding Custom Indicators
71
Exercise: Adding Custom Indicators
72
Coding: Additional
Concepts
73
Coding: Additional Concepts
74
Coding: Additional Concepts
75
Coding: Additional Concepts
76
Coding: Additional Concepts
77
Coding: Additional Concepts
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.
Conditionals
Conditional statements allow you to execute code
only when a defined set of conditions is true at run
time.
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:
84
Coding: Additional Concepts
Iteration: for()
A typical for loop might look like this:
85
Back Testing Mechanics
86
Back Testing Mechanics
87
Back Testing Mechanics
88
Back Testing Mechanics
89
Back Testing Mechanics
90
Back Testing Mechanics
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.
93
Exercise: Running a
Back Test
94
Exercise: Running a Back Test
95
Exercise: Running a Back Test
96
Exercise: Running a Back Test
97
Exercise: Running a Back Test
98
Exercise: Running a Back Test
1. Trade List
2. Back Test Report
99
More Back Testing
Techniques
100
Back Testing Techniques
101
Back Testing Techniques
• All Trades
• Portfolio
102
Back Testing Techniques
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.
104
Back Testing Techniques
105
Back Testing Techniques
Curve Fitting
Some people claim that back testing is just an
elaborate exercise in curve fitting.
106
Back Testing Techniques
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.
108
Back Testing Techniques
109
Common Mistakes
110
Common Mistakes
111
Common Mistakes
• 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
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.
116