100% found this document useful (1 vote)
234 views113 pages

BandyHowtoBuildTradingSys PDF

Uploaded by

haginile
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
234 views113 pages

BandyHowtoBuildTradingSys PDF

Uploaded by

haginile
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
  • Introduction and Title
  • Disclaimer
  • Overview
  • The Problem
  • The Solution
  • Our Premises
  • Historical Insight
  • Trading System Development Steps
  • Defining Best – Objective Function
  • What is Important?
  • Drawdown
  • Expectancy
  • Objective Function Choices
  • Good Objectives
  • Translated Objectives
  • Verify Your Objective Function
  • Typical Equity Curves
  • Data and Issues
  • About Financial Data
  • How to Trade
  • Models and Modeling
  • Models and Reality
  • What to Model – Something Easy
  • Survivor Bias
  • What to Trade – Something Profitable and Liquid
  • Liquidity
  • 50 Most Liquid Issues
  • Profitability
  • XLF ZigZag
  • XLFComponents.afl

How to Build an Effective

Trading System
(and Build Confidence that It Will Be Profitable)

Howard Bandy
NAAIM 2008

Copyright 2008 by Howard Bandy. Distribution rights are granted to NAAIM


1
Disclaimer
This is an educational presentation
The purpose is to explain the authors
method for developing trading systems
This is not a trading system presentation
Neither the author and presenter, Howard
Bandy, nor the conference organizer,
NAAIM, is liable for losses resulting from
application of techniques described in this
presentation
2
The Problem

The Solution

Practical Implementation

3
The Problem

Will the newly developed trading system


be profitable when traded?

How confident can we be?

4
The Solution
In a word
Practice
In more detail
Tomorrow is out-of-sample
Study simulated out-of-sample trades made by
the system
Every transition from in-sample to out-of-sample
increases our confidence
If the out-of-sample results are satisfactory, trade
the system
5
Our Premises
Mechanical systems
Markets are somewhat inefficient
We can detect patterns in historical data
that precede profitable opportunities
Those patterns persist long enough to
make profitable trades

6
Lord Kelvin - 1891
When you can measure what you are
speaking about, and express it in
numbers, you know something about it;
but when you cannot measure it, when
you cannot express it in numbers, your
knowledge is of a meager and
unsatisfactory kind

7
Trading System Development
1. Define the objective function
2. Decide what to trade and how to trade it
3. Design the trading system
4. Determine the in-sample period
5. Determine the out-of-sample period
6. Decide what to optimize
7. Perform walk forward runs
8. Evaluate out-of-sample results
9. Trade the system
10. Monitor the results
8
Defining Best Objective Function
Psychology of trading experts have it
backwards
Cognitive dissonance
Start by identifying what is important to
you
Create an objective function that
incorporates those features
Use this to compare alternative systems
9
Defining Best Objective Function
A function that gives single-valued score
A measure of the system
Incorporates important features
Score is reported for every test run
Will be used during walk forward
You select the objective function
Take your time and get it right
Dont start designing and testing without it
10
What is Important?
Drawdown Percent winners
Annual percentage Win to loss ratio
gain Recovery
Holding period Thoughts from the
Trading frequency audience
Exposure
Expectancy
Equity smoothness

11
Drawdown
In a single trade, it is the maximum amount of
loss at any time, relative to the best price
In a system, it is the maximum decline in the
accounts equity at any time, measured from
maximum equity up to that point
Drawdown is probably the single most important
metric excessive drawdown is the most
common reason traders stop using a system
Given a smooth equity curve, add leverage as
desired to the point where drawdown becomes
limiting 12
Expectancy
Expectancy is the amount or percentage that is
gained or lost by the average trade
Expectancy = % winners * average profit per win
+ % losers * average loss per loss
Expectancy must be positive
No money management scheme can turn a
system with negative expectancy into a winning
system
Poor money management can turn any system
into a losing system
13
Objective Function Choices
Net Profit
Often the default
Usually a poor choice

Reward equity growth and equity


smoothness
Penalize drawdowns
Examples:
K-ratio CAR/MDD
Ulcer Performance Index RAR/MDD
14
Good Objectives
Specific; Measurable; Realistic

My goal is to make a 15% annual profit


trading common stocks, control
drawdowns, cherry-pick trades, hold about
one week, and be tradable without
interfering with my day job.

15
Translated
Compound Annual Return > 15%
Maximum System Drawdown < 15%
Exposure ~ 30%
Holding 3 to 7 days
Use end-of-day data
Evaluate in the evening
Trade Market on Open

16
Verify Your Objective Function
Choose metrics that best fit your trading style
and personality
Run some optimizations
Plot the equity curves of several variations
Sort the results into order by ObFn
You should prefer them in order by ObFn
If not, modify the objective function until they
are ranked correctly
Will be used during walk forward
17
Typical Equity Curves

Buy and Hold Breakout

Reversal Cherry Pick


18
Data and Issues
Historical data for backtesting
Current data for trading
Liquidity
Price reasonable
Data cleanliness
Bad quotes
Unadjusted splits, distributions, restatements

Visual inspection

Consistency
19
About Financial Data
It is non-stationary
Cannot be made stationary
Autocorrelation is very weak

Data = trends + cycles + patterns + noise


Trading system is designed to recognize
some signal portion
Low signal to noise ratio
Noise is everything the system does not
model 20
How to Trade
End-of-day, intraday
MOO, MOC, limit orders, stops

Single issues
Portfolios

Position size
Risk management
21
Models and Modeling
1. Build a model 2. Validate that the
Trial and error model represents
Deduction signal, not noise
(reasoning) (out-of-sample
Induction (analysis of testing)
data)
3. Monitor to determine
Loop of
whether the model
Conjecture
Experiment
and the underlying
Observe are in sync
Modify (statistical tests)
22
Models and Reality
Our trading models are static
The reality we are trying to model is
dynamic
Our hope:
We can build a model of the data,
That recognizes some inefficiency,

And use that model to trade profitably,

As long as the model and reality stay in sync.

23
What to Model
Something Easy

Sector ETFs
Sector Mutual Funds
Indices
Industry Monitor ID Groups
Custom Indices (AddToComposite)
Beware survivor bias
24
Survivor Bias
Companies that fail disappear
Mergers and acquisitions change the
characteristics of companies
Companies currently in a list, group, fund,
industry, or index may not have always
been there
Others that used to be members may be
missing
25
What to Trade
Something Profitable and Liquid

Stocks, funds, ETFs, futures


Single issue
Portfolio
Model one thing trade another

26
Liquidity
$100M per day
500 issues
300 of the S&P500

$0.01 $0.02 spread

Very few gaps on 1 minute chart

$20M per day


1500 issues
$0.01 - $0.04 spread

27
50 Most Liquid Issues

Daily average dollar volume for 20 days in early 2008


28
Profitability
Model XLF
Run [Link] to see potential
Trade components
Use WatchList XLFComponents
Run [Link] to see potential

XLF is easier to model


The components are more profitable to
trade
29
XLF ZigZag

30
[Link]

31
Trading XLF Components

32
Creating a system
A model is a combination of:
One or more entry methods
One or more exit methods

A trading system is a combination of:


One or more models
One or more data series

that, together, give buy and sell signals for


some tradable issue or portfolio.
33
Types of Systems
Trend following Every trade is a trend-
Breakout following trade while
Moving average you are in it
Mean reversion
Pattern
Seasonality
Cycle
Others?

34
Entries
Signals
Indicators

Patterns

Seasonality

Cycles

Setups
Filters
Random for comparison
35
Exits
Signals Indicators, patterns, seasonality,
cycles
Same as entry other direction
Same logic different parameter values

Different logic

Timed holding period


Profit target
Trailing stop
Maximum loss stop 36
Indicator Exits
Indicators introduce lag
No need to be symmetric
Rises look different than falls

37
Stops are Not Reasons to Sell
Best exits come from signals and
indicators
Mean reversion (short holding periods)
profit targets and timed holding periods
Trend following (longer holding periods)
trailing stops
Maximum loss stop is for emergency
protection only
Stops hurt systems 38
Short Holding Periods
Advantages:
Drawdown increases as square root of
holding period
Allows selective trading

Gives many trading opportunities

Tighter distribution of trade results

More data points for statistics

39
Short Holding Periods
Disadvantages:
Increased trading
Higher commissions

Tax consequences

Fund restrictions

Portfolio restrictions

40
Terminal Relative Wealth
The value of a trading account after some
time, expressed as a ratio to its starting
value
Depends on exactly two numbers:
n
TRW = (1+e)
e == expectancy as a decimal fraction
n == number of trades
(Drawdowns may vary considerably)

41
Code Signals First, Then Stops
Begin by coding your entry
If you use more than one entry, test each
separately
Add your exit using logic appropriate for
the type of system
If you use more than one exit, test each
separately
Add stops only for protection
42
Reality Check

Be certain the system is tradable


Allthe data is available when you need it
There is enough time to compute signals

Assumptions about liquidity and slippage are


realistic
No future leak

43
Brains? Or Bull Market?
Beware of long-only systems in strong bull
markets
Safeguards:
Look for profitable shorts
Look at periods or tickers when price is flat or falling

44
Simulated Trading
An automated series of:
1. Evaluate alternatives in-sample
2. Select the best alternative
3. Simulate trading out-of-sample
Move forward in time and repeat steps
1, 2, and 3
If out-of-sample results are satisfactory,
trade the system
45
In-Sample
In-sample the period of time (and the
data and trades associated with it) where
the alternatives of logic and parameter
values are evaluated
In-sample results are always good
In-sample results have no value in
estimating the future performance of the
system
46
Out-of-Sample
Out-of-sample the period of time (and
the data and trades associated with it)
where the trading system is tested on data
it has never seen before
Immediately follows the in-sample period
Caution making decisions based on out-
of-sample data results in that data
becoming part of the in-sample data
47
In-sample Out-of-sample

48
In-sample Period Length
How long should the in-sample period be?
Opinions include:
A long time period
Pro: Include many different conditions
Con: Cannot accurately model everything
A short time period
Pro: Stay synchronized with current conditions
Con: Learn noise instead of signal
Experiment
My recommendation as short as practical 49
Out-of-Sample Period Length
As long as the model and the market
remain in sync
Unrelated to length of in-sample period

50
Optimization
A search for the best values for logic and
parameters
Any time two or more alternatives are
considered, you might as well consider
thousands
Rough runs to determine ranges
Thorough runs to locate maxima

51
Which Way is Up?

The Model

52
How to Optimize
One dimension at time
Takes less time
Can get stuck

Finds local maxima

Multiple dimensions
Exhaustive search
Long runs
Detect interactions and global maxima

Use preliminary runs to select the range 53


Reoptimization
Length of out-of-sample period determines
reoptimization schedule
You may reoptimize at any time

54
Degrees of Freedom
Every data point contributes one degree of
freedom
Every alternative considered uses up one
degree of freedom
Curve-fit or over-fit means there are no
degrees of freedom left over

55
Fit the Signal
5 data points 2 coefficients three residual degrees of freedom

Y = a + b*x

56
Fit the Noise Curve-fit
5 data points 5 coefficients zero residual degrees of freedom

Y = a + b*x + c*x2 + d*x3 + e*x4

57
Walk Forward
A sequence of steps, each consisting of
optimizing over an in-sample period and
testing over an out-of-sample period
Automatically, advancing dates each step:
Optimize in-sample
Choose best

Test out-of-sample

Accumulate out-of-sample results


Best chosen strictly by objective function
58
The Walk Forward Process

59
Decision to Trade

60
Validation
Evaluate out-of-sample results
Decide whether to trade the system or not

Out-of-sample results indicate how the


system will react to various conditions
In-sample results have no value in
determining the likely profitability of the
system
61
Trading
Next Day Open (NDO)
Updatedata after close
Compute signals in evening

Trade on Close of signal bar


Real time data feed
Compute price ahead

Anticipate signals

62
Monitor Results
Compare real time results with out-of-
sample test results
All systems fail
Use statistical tests to determine if the
system is broken
Use statistical process control techniques,
if possible
When to reoptimize
63
5 Wins in a Row Now What?
After a long string of winning trades, do
you change anything?

Probably not
Your system and the market are in sync
This is just what you hoped for, stay with it

Do not penalize good results

64
4 Losses in a Row Now What?
Review the trade statistics from your out-
of-sample runs.
What is the typical ratio of winning trades
to losing trades?
Is this unusual?
Use the runs test for a statistical answer
Or use the binomial distribution

65
The Binomial Distribution
Assume your out-of-sample shows 60%
winners, 40% losers
The probability of any trade being a loser is
0.40
The probability of two successive losers is
0.40 * 0.40 = 0.16 Expect this regularly
Three losers in a row = 0.064 Start to worry
Four losers in a row = 0.0256 It is broken
66
Practical
Implementation

67
Everything You Need
Everything you need is available today

AmiBroker trading system development


platform
Any end-of-day and most real-time data
sources
Quotes Plus is a good data vendor

68
Trading System Development
1. Define the objective function
2. Decide what to trade and how to trade it
3. Design the trading system
4. Determine the in-sample period
5. Determine the out-of-sample period
6. Decide what to optimize
7. Perform walk forward runs
8. Evaluate out-of-sample results
9. Trade the system
10. Monitor the results
69
Metrics Available
Search the AmiBroker Users Guide for getperformancestats

10000.00 "InitialCapital 13 "WinnersQty"


16925.16 "EndingCapital 56.52 "WinnersPercent"
6925.16 "NetProfit 10888.27 "WinnersTotalProfit"
837.56 "WinnersAvgProfit"
69.25 "NetProfitPercent" 6.51 "WinnersAvgProfitPercent"
16.91 "ExposurePercent" 6.00 "WinnersAvgBarsHeld"
409.52 "NetRAR" 4 "WinnersMaxConsecutive"
24.00 "CAR" 3254.77 "WinnersLargestWin"
6 "WinnersLargestWinBars"
141.90 "RAR"

23 "AllQty"
100.00 "AllPercent"
Typical Metric
301.09 "AllAvgProfitLoss"
value name
2.57 "AllAvgProfitLossPercent"
5.52 "AllAvgBarsHeld"
70
Metrics Available
10 "LosersQty" -1707.12 "MaxTradeDrawdown
43.48 "LosersPercent" -11.66 "MaxTradeDrawdownPercent"
-3963.11 "LosersTotalLoss" -2071.76 "MaxSystemDrawdown"
-396.31 "LosersAvgLoss" -13.80 "MaxSystemDrawdownPercent"
-2.55 "LosersAvgLossPercent" 3.34 "RecoveryFactor"
4.90 "LosersAvgBarsHeld" , 1.74 "CAR/MDD"
2 "LosersMaxConsecutive" 10.28 "RAR/MDD"
-1210.84 "LosersLargestLoss" 2.75 "ProfitFactor"
4 "LosersLargestLossBar" 2.11 "PayoffRatio
883.56 "StandardError
3.39 "RRR
5.37 "UlcerIndex"
3.46 "UlcerPerformanceIndex"
2.31 "SharpeRatio
0.0967 "KRatio" 71
Buy on Open of Next Bar

SetTradeDelays(1,1,1,1);
BuyPrice = Open;

Sometimes called Next Day Open (NDO)


Normal when using end-of-day data,
Processing in the evening,
Trading market on open
72
Buy on Close of Current Bar

SetTradeDelays(0,0,0,0);
BuyPrice = Close;

Often the best entry


Must anticipate the signal

73
Designing Entries

Start with an indicator


Pickan entry method
Hold 2 days
--- or ---
Start with desirable result
Identifygood entry points
Look for leading indicators

74
Lag
Lag makes entries late
Low lag indicators:
AMA

ZeroLag MACD
Regression

Zero lag indicators:


Patterns

Statistics

Seasonality
75
Be Wary of In-sample Results
The next few slides illustrate the in-sample
and out-of-sample results of several
systems
It is impossible to tell whether results are
in-sample or out-of-sample without
performing the validation yourself

76
System 1 In-Sample

77
System 1 Out-Of-Sample

78
System 2 In-Sample

79
System 2 Out-Of-Sample

80
System 3 In-Sample

81
System 3 Out-Of-Sample

(CMO Oscillator)

82
An Optimization Example

Search for the


best values for
these three
variables

83
Equity Curve Before

Backtest using default values


84
Optimization Settings

To begin, Click Optimize


85
Optimization Results

Three variables

Sorted by Objective Function 86


Optimal Values Entered

87
Equity Curve After

This is In-Sample, and it looks good

88
Settings to Test OOS

Set to date later

89
Equity Curve Out-Of-Sample
2005 and 2006 are Out-
Of-Sample, and look
good

90
Walk Forward Example

AmiBroker has native walk forward testing


from Version 5.05

91
Install Plot InSample [Link]
Copy to AmiBroker\Formulas\Custom

92
Select the System to Test
Automatic Analysis > Pick as usual

93
Note Optimization Statements

94
Settings

Settings
Walk Forward
Set Dates
Select Objective
OK

95
Start Walk Forward Run
Optimize
Walk Forward

96
Results Window

97
Two Tabs
Minimize Optimizing window to reveal these

98
Walk Forward Tab
Displays in-sample and out-of-sample results for each step
Best values for parms
Based on RAR/MDD

99
Chart Tab

100
I.S. and O.O.S. Equity Curves

101
Just for NAAIM

A system using weekly data

102
ETF Selection Example
Nine S&P Sector ETFs
Weekly data Hold 1 to 3 sectors
Compute signals after Fridays close
Trade Mondays open
Two methods in one system
Trendfollowing
Mean reversion

6 mo in-sample, 6 mo out-of-sample
103
ETF Selection Code
Optimize:

Number to hold

Three Variables

104
ETF Selection Walk forward

105
EFT Selection Equity Curves
In-sample
Out-of-sample results equity curve
73% gain in 4.5 years
62% exposed
21% annualized (RAR)
~30 day holding period

Out-of-sample
equity curve

106
How to Build an Effective
Trading System
(and Build Confidence that It Will Be Profitable)

107
Trading System Development
1. Define the objective function
2. Decide what to trade and how to trade it
3. Design the trading system
4. Determine the in-sample period
5. Determine the out-of-sample period
6. Decide what to optimize
7. Perform walk forward runs
8. Evaluate out-of-sample results
9. Trade the system
10. Monitor the results
108
Questions and Comments

109
Quantitative Trading Systems
Expands on topics
presented today
Subtitled Practical
Methods for Design,
Testing, and
Validation
Published in 2007
Very well received
Shipped to over 35
countries
110
Contact Information
To discuss or schedule a seminar,
workshop, custom programming, or
consulting:

Dr. Howard B. Bandy


(520) 705-1239 (cell)
howard@[Link]

111
Resources
AmiBroker [Link]
Quotes Plus [Link]
Quantitative Trading Systems
[Link]

[Link]/resources

112
The End

113

Common questions

Powered by AI

Differentiating between in-sample and out-of-sample results is crucial because in-sample results generally appear optimized due to fitting the model on known data, thus offering little insight into future performance. In contrast, out-of-sample testing provides a more realistic assessment of a system's viability, as it evaluates performance on new, unseen data, simulating actual trading conditions. Mistakenly using out-of-sample results for system optimization could turn them into in-sample data and bias the evaluation process .

When coding entry and exit signals for a trading system, key considerations include first establishing a clear entry signal that aligns with the overall trading strategy, testing each potential entry individually, and selecting exits that logically complement the entry strategy, whether aiming for short-term profits or long-term trends. Stops should be added solely for protection rather than as primary sell signals. It's also crucial to use low lag or zero lag indicators to avoid delayed entries and exits, ensuring that trading signals are responsive to market conditions .

Comprehensive data points are important in trading system design because they provide a robust foundation for testing and optimizing the system across various conditions. Every data point contributes a degree of freedom, which is essential for maintaining the flexibility of the system design. However, each alternative or parameter considered consumes a degree of freedom, so maximizing data points helps avoid overfitting, allowing for a more generalized and adaptable model. Effective use of degrees of freedom ensures that the system remains robust without being overly tailored to specific historical conditions .

After a string of winning trades, a trader should probably maintain the current system approach, as this indicates the system and the market are working well together. The system's consistent performance should not be penalized. During periods of consecutive losses, traders should review trade statistics from out-of-sample runs and use statistical tools such as the runs test or the binomial distribution to determine if the losses fall within expected probabilistic ranges, or if they suggest a breakdown in system integrity that requires reassessment .

The objective function critically determines the design and evaluation of a trading system by providing a single-valued score that incorporates the features most important to the developer. It guides comparisons between alternative systems, helping to identify which system might best meet the trader's goals. The objective function reflects the user's priorities, such as minimizing drawdowns or maximizing returns, and ensures that these elements are quantitatively measurable and comparable across test runs. Getting the objective function right before designing and testing is emphasized as it tailors the trading system to align with specific trading goals .

When deciding on in-sample and out-of-sample period lengths, several factors should be considered: a longer in-sample period may include many market conditions increasing the robustness, but there is a risk of overfitting to noise rather than signal, whereas a shorter period keeps the system more aligned with current market conditions. The out-of-sample period should be long enough for the model to align with market dynamics without being tied to the length of the in-sample period, ensuring that transitions between market phases are adequately captured .

Short holding periods in trading provide several benefits, including reducing drawdowns by the square root of the holding period, allowing for selective trading, providing numerous trading opportunities, and ensuring a tighter distribution of trade results which offers more data points for statistical analysis. However, there are drawbacks such as increased trading frequency leading to higher commissions and tax consequences, and potential fund and portfolio restrictions due to the short interventions .

Using a maximum loss stop in trading serves as an emergency protection strategy rather than a primary exit strategy. Its effective integration into a trading system involves setting it as a backstop to limit severe losses without interfering with the primary logic of trade exits, which should ideally derive from a combination of indicators and signals. This ensures the stop only activates in atypical market conditions, preserving the trading system's intended strategy and minimizing disruption to normal operation .

Out-of-sample testing plays a crucial role in assessing a trading system's potential performance under real market conditions it hasn't encountered before. It involves evaluating the system using data and events not included in the initial model development (in-sample), effectively simulating future performance. This process helps ensure the robustness and reliability of the system by exposing it to 'fresh' data, reducing the risk of overfitting to historical data patterns that may not persist. Consistent positive out-of-sample results increase confidence in the system's viability under actual trading conditions .

Walk forward optimization contributes to the validation of a trading system by implementing a sequence of optimizing the system over an in-sample period, then testing it on an out-of-sample period. This process is repeated as the time frame is advanced, thus simulating real-world application and providing continuous insights into the system's capabilities. It accumulates out-of-sample results to evaluate overall system performance strictly based on the defined objective function, highlighting both robustness and adaptability over time .

You might also like