AdaptiveMoving AverageThe Adaptive Moving Average can be programmed into any spreadsheet or strategy-testing software. The following examples show thecodes for Quattro Pro (very similar to Lotus), Telerate's TeleTrac, andOmega's TradeStation. Signals should not begin for 25 days, because thefilter requires 20 days of AMA trendline changes, and the AMA needsan additional 5 days to start up.Spreadsheet InstructionsBox 8-3 and Table 8-1 give the spreadsheet instructions and sampleresults. All constants have been placed in row 2. The recent AMA highsand lows are recorded in columns L and M.Telerate's TeleTracThe TeleTrac code (Box 8-4) uses the alternate buy and sell signal calculation, comparing 3 days of AMA changes separately. It also uses theMACD study ("SIGNAL") to calculate an exponential moving averagewith a changing smoothing constant. This code can be used to trade livedata. Realized profits and losses are shown in the last line.Omega's
Easy
Language
The TradeStation code is the same for both System Writer and other Omegaproducts (Box 8-5). Figure 8-8 shows the TradeStation display using the"AMA" system (Part 1) to give signals, the "AMA" indicator (Part 2),scaled to price, to plot the AMA trendline with the price chart, and "AMAsmooth" (Part 3) to place the smoothing constant along the bottom of thegraph.
148
Using Old and New Trading Tools for Reasonable Objectives
Box 8-3. CALCULATING THE ADAPTIVE MOVINGAVERAGE USING A SPREADSHEETThe Adaptive Moving Average can be easily calculated using a spreadsheet. In Table 8-1, columns B and C are input and the rest are calculated. Values begin in row 5. Repeated calculations are shown for row 15(row 5 is for initialization). The AMA calculations (E-H) begin in row 15,because they require 10 days of data for the first value.Cell
Title
Description
Formula
2-day smoothing constant30-day smoothing constantFilter percentage factor
=2/(2+1)=2/(30+1).10
Daily dateDeutsche mark price(Use price C5* until row 15)Recent AMA lowsRecent AMA highs
[Input data][Input data][Input data]+15+15
10-day momentumPositive 1-day volatility10-day volatilityEfficiency RatioSmoothing constantAdaptive Moving AverageDifference in AMAEntry/exit filterRecent AMA lowRecent AMA highNew buy signalNew sell signal
+C15-C5@ABS(C6-C5)@SUM(E6..E15)@ABS(D15/F15)(G15*($C$2 -$D$2)+$D$2) A2+I14+H15*(C15-I14)+I6-I5@STD(J15..J6)*$J$2@IF(I6<I5,I6,L5)@IF(I6>I5,I6,M5)@IF(I15-L16>K15,'BUY7')@IF(M15-I15>K15,'SELL',")
Constants:
C2D2J2Initial Values:
B5C515L5M5
DateDMZ92AMA(t)LowsHighs
Repeated Formulas:D15*E6*F15*G15*H15*115*J6*K15*L6*M6*N15*015*
D(t)1DPV(t)ER(t)C(t)AMA(t)DAMAFilterLowsHighBuySell
'Indicates to copy the contents of the cell down.@ Indicates a Quattro function.
Smarter Trend-Following
149
Table 8-1. Spreadsheet Values for the Adaptive Moving AverageBLine
C0.66667
34DATE5 9206016 9206027 9206038 9206049 92060510 92060811 92060912 92061013 92061114 92061215 92061516 92061617 92061718 92061819 92061920 92062221 92062322 92062423 92062524 92062625 92062926 92063027 92070128 92070229 92070630 92070731 92070832 92070933 92071034 92071335 92071436 92071537 92071638 92071739 92072040 92072141 92072242 92072343 92072444 920727
DMZ926063604160656078611461216106610161666169619562226186621461856209622162786326634764206394640064466442654365506442651665976568658066106682653765526563657364986593
D
E
0.064510-Day AbsD(t) 1DP
22241336715565326132.027181.0121.036136.02871.0292488.012115.057177.048160.0178.021225.073172.026214.06232.046.4257.0334.0 101329.07164.0 10874190.0250.08129148.012186.0210.03072236.095.0 1459.0151113.0131.010218.07524.095
F
G
10-Day 10-DayV(t)ER(t)
216221233248241258255307290308355354324342317394389440466526482468492518659573577479480494
H
SmoothC(t)
0.610.1870.820.3110.520.1420.550.1560.290.0590.340.0730.450.1130.580.1690.550.1570.580.1700.630.1990.490.1280.660.2140.680.2240.810.3050.3310.850.850.3290.370.0830.410.0960.480.1230.0620.310.0920.400.430.1030.460.1150.140.0230.020.0050.02 • 0.0060.270.0530.040.0080.010.005
I
A M A ( t)60636041606560786114612161066101616661696173.96188.86188.46192.46192.06193.26196.46210.26228.46248.66282.76296.96318.96347.46376.36431.46470.46468.16472.76488.06492.96501.06512.36531.76531.96532.06532.26534.36534.06534.3
J
K
0.151st DiffDAMA
Filter
-222413367-15-56534.915.0-0.4
4.0-0.4
1.23.113.818.220.234.114.222.028.428.955.139.1-2.4
4.615.3
5.08.011.319.5
0.10.10.22.1-0.3
0.3
E/X
3.63.23.33.33.13.12.92.81.01.11.61.61.61.61.52.01.82.22.42.42.52.52.62.52.61.81.01.01.00.9
L
AMA(t)Lows6063.06041.0604 1.0604 1.0604 1.06041.061 06.06101 .06101.06101.06101.06101.06188.46188.46192.06192.06192.06192.06192.06192.06192.06192.06192.06192.06192.06192.06192.06468.16468.16468.16468.16468.16468.16468.16468.16468.16468.16468.16534.06534.0
M
N
AMA(t) TradeHighs6063.06063.06065.06078.06114.06121.06121.06121.06166.06169.06173.96188.86188.86192.46192.46193.26196.46210.26228.46248.66282.76296.96318.96347.46376.36431.46470.46470.46472.76488.06492.96501.06512.36531.76531.96532.06532.26534.36534.36534.3
Signal
6195
64426516
150
Using Old and New Trading Tools for Reasonable Objectives
Box 8-4. TELETRAC CODE FOR THEADAPTIVE MOVING AVERAGEitemdateopenhighlowclosevoloiperioddiffnoisesignalefratiosmoothmacdamadamadama2dama3sdaysfiltersdamabuyifbuysellifsellstrategyrealized
"DEUTSCHMRK_3/93DATA(dat,e,first,last,item)"DATA(open,item)"DATA(high,item)"DATA(low,item)"DATA(close,item)"DATA(vol,item)"DATA(oiJtem)10Abs_val(close-close[1 ])Sum(diff,period)close-close[period]Abs_val(signal)/noisePower(ef ratio*(.666- .0645)+.0645,2)closeSignal(macd,smooth)ama-ama[1]ama-ama[2]ama-ama[3]20.10Std_dv(dama,sdays)*filterdama>sdamaldama2>sdamaldama3>sdamadama>=0&buyifdama<-sdamaldama2<-sdamaldama3<-sdamadama<0&sellifTrade(buy,sell,sell,buy)Clos_PL(strategy,close,.0001,.0002)M
The TeleTrac code uses a special function, Signal, to calculate a trendlinebased on a changing exponential smoothing constant. This code alsocompares three days of accumulated trend changes to avoid a gradualchange that might not give a new signal. Period, filter, and sdays areentered as "coefficients" to allow for optimization.
Smarter Trend-Following
151
Box 8-5. OMEGA EASY LANGUAGE CODE FOR THEADAPTIVE MOVING AVERAGE*Part 1: Enter as a "system."inputs: period(10), filter(.1);vars: noise(O), signal(O), diff(O), efratio(O), extlow(O), exthigh(O),smooth(1), fastend(.666), slowend(.0645), AMA(O);{ CALCULATE EFFICIENCY RATIO }diff = @AbsValue(close - close[1]);if(currentbar < = period) then AMA = close;if(currentbar > period) then beginsignal = @AbsValue(close - close[period]);noise = @Summation(diff, period);efratio = signal/noise;smooth = @Power(efratio*(fastend - slowend) + slowend,2);{ADAPTIVE MOVING AVERAGE }AMA = AMA[1) + smooth*(close - AMA[1]);{TREND CHANGE FILTER FROM LAST TURN }if (AM A > AMA[1] and AMA[1] < AMA[2]) then extlow = AMA[1];if (AMA < AMA[1] and AMA[1] > AMA[2]) then exthigh = AMA[1];{TRADING SIGNALS}if(currentbar > period + 5) then beginif (AMA > AMA[1] and AMA - extlow > filter) then buy on close;if(AMA < AMA[1] and exthigh - AMA > filter) then sell on close;end;end;Note that this code saves the most recent trend turning points as extlowand exthigh. It can then use those points to compare the accumulatedchange of direction against the filter and avoid missing a signal due toa very slow trend change.
152
Using Old and New Trading Tools for Reasonable Objectives
Box 8-5. (Continued)Part 2: Enter as an "indicator" to see the trendline on the chart page.inputs: period(10);vars: noise(O), signal(O), diff(O), efratio(O),smooth(1), fastend(.666), slowend(.0645), AMA(O);{ CALCULATE EFFICIENCY RATIO }diff = @AbsValue(close - close[1]);if(currentbar < = period) then AMA = close;if(currentbar > period) then beginsignal = @AbsValue(close - close[period]);noise = @Summation(diff,period);efratio = signal/noise;smooth = @Power(efratio*(fastend - slowend) + slowend,2);{ ADAPTIVE MOVING AVERAGE }AMA = AMA[1] + smooth*(close - AMA[1]);Plot1(AMA,"AMA");end;
Part 3: Enter as an "indicator" to plot the smoothing constant on thechart page.inputs: period(10);vars: noise(O), signal(O), diff(O), efratio(O),smooth(1), fastend(.666), slowend(.0645);{ CALCULATE EFFICIENCY RATIO }diff = @AbsValue(close - close[1]);if(currentbar < = period) then AMA = close;if(currentbar > period) then beginsignal = @ AbsValue(close - close[period]);noise = @Summation(diff, period);efratio = signal/noise;smooth = @Power(efratio*(fastend - slowend) + slowend,2);Plot1(smooth,"AMA smooth");end;Copyright 1993, P. J. Kaufman, All rights reserved.
Smarter Trend-Following
gage
Chart
153
Omega IradeStation Chart 4/?B 10:?1 am [AMA: Adaptive MovinlIools Analysis QuIcfcEdhor Options Window Help
Figure 8-8. Adaptive Moving Average for the Eurodollar on TradeStation.
I
9
Computer Learning,Neural Networks,and New TechnologyUsing a computer develops special skills in the same sense as driving acar or learning a new language. The process is more intimidating than itis difficult. New computer applications are much more user-friendlythan they were five years ago. Most programs allow you to use a"mouse," provide pop-up help screens, and explain each option on thescreen whenever you point the mouse at a special icon symbol. To ourrelief, it is also harder to destroy a program by hitting the wrong keys.This removes some of the concerns about learning. If you press the Enterinstead of the Esc key, the computer may tell you ENTRY INVALID. TRYAGAIN, or just ignore you.Teaching a computer the rules for a trading strategy is a learningprocess for both you and the computer. Unlike the human brain, thecomputer cannot infer a meaning, it must be told precisely. We oftenthink that we are very clear about giving instructions, but the section on"fuzzy logic" will show how many of our expressions are vague. Thefollowing section is intended to emphasize how exact you must be inspecifying rules to get the computer to give the right answer. If youhave never programmed trading rules, it will be well worth your timeto follow this process through the next few pages.
155
156
Using Old and New Trading Tools for Reasonable Objectives
The Teaching Process:First the TrainerBecause some important new technologies "teach" the computer how tosolve a problem, and strategy-testing programs allow you to define specific rules, this chapter will show how human this process can be. Anearly marvel of engineering skill, the Erector Set, will be used to illustrate the steps (Box 9-1).The basic Erector Set has flat metal pieces, screws, and bolts. Our sample set uses only nine pieces, conveniently designed to fit together, asshown in Figure 9-1, with the pieces numbered for reference. It has 18sets of bolts and nuts, exactly Vi the number of total corners.Your task is to build a flat, narrow 4-inch bridge long enough to covera 33-inch span. You must write the rules for constructing the bridgeclearly enough for someone else to follow them exactly. You can startwith the five rules given in the first panel of Box 9-1.
Applying Prices tothe Training GameWhen we apply the same process to finding a sequence of prices thatresults in a net move of +50 points in the DJIA, some interesting similarities and differences appear. If we think of each "piece" as a price, wecan restate some of the rules:RULE A. Begin with a partially constructed bridge of length I (theoriginal investment).RULE B. Decide on the length of the final bridge before starting.RULE C. You must take the prices ("pieces") in the order they come,but you may discard them if they are too small (but only if you havedecided in advance, what is "too small").Discarding a small piece is a threshold criterion that will be used later inthis chapter in the section, "Neural Networks." It allows us to decide thata very small price is not relevant for determining a new trading signal.RULE D. Prices that exceed the threshold are always attached at thesame end (of the price series).RULEE. A price piece can either add or remove (positive or negative)length.RULE F. The length cannot become less than V2 the original size (maximum loss rule).
Computer Learning, Neural Networks, and New Technology
187
RULE G. The bridge must be constructed by a certain time using afixed number of pieces (return on investment rule).Some additional considerations are:• Price changes come in more sizes. Some are exceptionally big, andothers are very small and can be ignored. When a very large positivepiece appears, the goal is successfully reached; when a very largenegative piece appears, the game is lost. The frequency of catastrophic loss is based on the number of occurrences of large negativepieces, or price shocks. Chapter 7 shows that there is no way to avoidthese events, but there are ways to survive them.• If too many small pieces are used, the time spent is no longer costeffective.• You cannot reach the goal in the scheduled time if too many piecestake away from its length.Most important, when using prices instead of playing games,• There may not be a solution within the limits of the rules, time, andobjectives.Once again: There may not be a solution. Forcing an answer from pricepatterns and data is not a solution. It may be necessary to look at theproblem from an entirely different perspective.Computers do not think; they simply follow your instructions.Writing the rules requires practice. When an instruction is missing, theanswer is wrong, even when the results appear to be good. The onlyway to know that the computer has calculated everything correctly is tocheck the results manually for a few different cases. The more complexthe trading strategy, the longer it will take to verify.It is easy to make mistakes when specifying rules and typing formulas. It is not likely that any system has been written that did not requirecareful computer debugging. The following sections on new technologies will describe a number of interesting approaches to defining rulesand making decisions.
Artificial Intelligence andPattern RecognitionThe field of artificial intelligence (AI) includes many new technologiesfor prices forecasting, such as expert systems, neural networks, and
Box 9-1. THE ERECTOR SET PIECES
„o
o ooooo ooo ooooo oooooooooooooooooooooooooooooooo ooooooooooooooooooooooooooooooooooo ooooooooooooooooooooooooooooo oooooooo oooooooooo
12
3
6
7
9
Bolts
Nuts
Figure 9 - 1 . Erector set piece*.
Erector set piecesThere are nine pieces, forming four sets of plates each with an area of4" X 8". Each plate is fully covered with holes. There are 18 bolts and18 nuts.ObjectivesCan you construct a bridge that is 33" long and 4" wide at all points?Can you teach someone else by writing the exact rules for doing thisthe first time? The following five rules will get you started:RULE 1. You must take the pieces in any order.RULE 2. Two flat pieces can be attached by inserting a bolt througha hole in each of the two pieces, and fastening it with a nut.RULE 3. The bridge must be 4" wide at all places.RULE 4. All corners must be fastened except the four at the twoends of the bridge.RULE 5. The bridge must reach across a 33" span.Teaching YourselfTo follow the rules, you select each piece with your eyes closed. Youmust write an unambiguous rule for using any piece before you see it.This is important because, when you test stock or futures prices, you donot know what will come next.You take the first piece and look at it. You realize immediately thatthe five rules do not include instructions for the first piece. The rulesrequire at least two pieces. You cannot continue without adding:158
RULE 6. Start with two pieces; after the first move, take one pieceat a time.Starting again, you take two pieces and fasten them together byapplying Rule 2. You realize that you do not know which holes to fasten.RULE 7. Fasten the shortest sides together by overlapping theedges (Figure 9-2) so that the holes nearest the edges align; if theshorter edges are the same size, then attach them so that they arealigned at the ends; if they are different lengths, attach them sothat one end is aligned.Rule 7 will prevent bolting a small piece in the middle of a big piece,and will prevent the bridge from going around in a circle.Beginning again, we draw pieces 8 and 4 and attach them end to end,into an "L"-shaped form, as in Figure 9-3. Notice that the total length is% inch less than the sum of the two pieces, because they overlap. Piece1 comes next, but there are two choices: It can be attached to the end ofpiece 8 or the end of piece 4. This suggests two more problems thatneed rules:RULE 8. Continue to add pieces in the same direction.RULE 9. Before adding a piece at the very end of the ramp, firstcheck to see if the piece fits a missing slot to finish the 4" width.This process of adding rules based on experience is called learning byfeedback. By continuing, we will eventually complete a bridge thatspans the 33 inches with 1 inch overlapping each end. This lengthyprocess is identical to "teaching" the computer.
Figure 9-2. Overlapping pieces.Bolting two pieces together takes awayVt" from the total length.
Figure 9 - 3 . Attaching the firstthree pieces together. Extra rulesare needed.
159
160
Using Old and New Trading Tools for Reasonable Objectives
fuzzy logic. There is still a lot to learn from the first AI methods, whichcentered around basic pattern recognition.Think about price changes as direction only:up, up, down, up, unchanged, up, up, down,...
What comes next? If you were taking a school test, the answer would beup. If you were investing in the market, how much would you risk onthe next day being up? Nothing, because the pattern was not repeatedenough times, and markets are not expected to perform with such regularity.The existence of a previous pattern that is identical to the current oneis not enough to risk an investment. For example, you test 10 years ofdata and find 74 cases of identical 5-day patterns, either up, up, down,up, up or down, down, up, down, down. If the results are random, then thispattern will be followed by 37 up days and 37 down days. If there are 42up days and 32 down days, would you consider buying each time thispattern appears? There may be an edge, but a very small one. Or theremay not have been enough cases in the 10 years for the random distribution to have appeared.Simple pattern recognition is a difficult tool to use in trading. Its success is entirely an issue of statistics, and must be treated in that light.The following methods of artificial intelligence are much more likely toproduce good results.
Applications ofExpert SystemsApplications of artificial intelligence are intended to have computersoperate the way humans think. It may not be clear that the process isreally desirable, but science considers the unachievable as a challenge,and sometimes pursues it without understanding why. The development of the following concepts began long before everyday technologycould support them.Expert systems have the very sensible goal of duplicating expert adviceand decisions. This approach has had remarkable success in medicaldiagnosis and could be equally applicable to financial issues.New technology tends to create terminology to express the ideas, andexpert systems are no exception. Having the proper words seems to bepart of the process:• Teaching the computer refers to the act of entering data and rules intothe machine, such as:
Computer Learning, Neural Networks, and New Technology
FACT1
Bob's parents are George and Martha.
FACT 2
Mary's parents are George and Martha.
RULE1
If you drive faster, you will get there sooner.
RULE 2
You can't drive faster than the speed limit.
RULE 3
If there is more traffic, you must drive slower.
161
• Inference means creating new facts from existing ones. Using facts 1and 2, we getINFERENCE:
Bob and Mary are brother and sister.
• Pruning is the sorting through of all the information to find the mostrelevant. Because the brain and the machine are filled with data andrules, it is necessary to select the ones that apply to the current problem. You would not want to answer the question, "Why did the stockmarket drop?" with "Because of the earthquake in Armenia." Aninteresting item, but unrelated.• An expert system is one that deals with a special area, such as medicaldiagnosis, oil spills, or stock market forecasting. By listing all thefacts and rules in the specialized domain, the system is expected tosubstitute for the benefits of a team of experts.To create an expert system to make stock market decisions, first writethe relationships that are facts, in any order. For example, Table 9-1gives a set of 10 rules.Forward ChainingThe definitions and rules in Table 9-1 combine to form a knowledge base. Forconvenience, the shortened names referring to data are explained in thelist of variable names. Using a process called forward chaining, start with animportant piece of information and follow one rule to another until youfind your answer. For example, The Wall Street Journal front page reads:FED CUTS RATE H A L F P O I N T TO 4V4and you want to know how the stock market should react. Rule 1 statesthat, IF interest FALLS, THEN stocks RISE. Therefore, expect the stockmarket to rally.If the Journal had said:
DOLLAR DROPS AGAINST THE YENThen Rule 2 gives IF dollar FALLS, THEN interest RISE. That is chainedto Rule 1, which states, IF interest RISE, THEN stocks FALL.
162
Using Old and New Trading Tools for Reasonable Objectives
Table 9-1. Expert System Rules for Stock Market DecisionsRule1
Statement of Rule (a)
Opposite Rule (b)
IFTHENIFTHENIFTHEN
intereststocksU.S. dollarinterestinflatior iinterest
FALLRISEFALLRISE
intereststocksU.S. doUarinterest
RISEFALLRISEFALL
RISERISE
IFTHENIFTHENIFTHEN
inflationinterest
FALLFALL
4
IFTHEN
GNPinterest
FALLFALL
IFTHEN
GNPinterest
RISERISE
5
IFTHENIFTHEN
Ger Bund rateinterest
IFTHEN
Ger Bund rateinterest
p/cap spendinventories
FALLFALLRISEFALL
IFTHEN
p/cap spendinventories
RISERISEFALL