Perry J. Kaufman. Smarter Trading. Improving Perfomance in Changing Markets
Home My photos Forex My trading Contacts
   
 

books about online stock trading, forex, futures, stock investing, market, trading systems
Smarter
Trend-Following

If you could achieve only one goal in price analysis, it should be identi­ fying the price direction, or trend. It you take positions in the direction of the trend, then you should capture the biggest price moves and have reasonable control over risk. When you use a trend to select trades or set hedge positions by confirming the correct trend direction, your trading performance must improve.

Forecasting and Following Finding the Trend

There are two ways to find trend. By analyzing major economic fac­ tors, you can conclude that prices should go higher. Greater demand, good management, better technology, and cheaper money may all con­tribute to long-term growth, higher dividends, and higher share prices. Energy prices may be pushed up by greater consumption, a unified OPEC position to cut production, or supply disruption in Siberia . But basic fundamental evaluation is difficult and dependent on reliable information. The conclusion may change if new factors are introduced. Changes must be constantly monitored and weighed.

Many traders supplement or substitute a moving average to identify the trend. There may seem to be no relationship between a simple mathematical formula and the result of events that drive prices, but that is not the case. A moving average creates a trend by smoothing erratic price movement. Because it is an average of past prices, it reduces the effects of outliers that appear to have been extreme reactions to news.

Averaging longer periods of data gives smoother trends. The result is often a good representation of long-term market direction, and a valid parallel to government monetary or interest rate policy. Moving averages are also used in econometrics to remove known seasonal or cyclic effects. For many years, stock market analysts have used a 200-day moving average as their benchmark.

A moving average is exactly what it seems to be: the average value of a prior data period. A 3-day moving average is simply

average = (price + price[1] + price[2])/3

Most computer trading software, even spreadsheets, will have the mov­ ing average formulas preprogrammed, so that it is only necessary to enter

@average(price,n)

where price is the data to be averaged, and n is the number of periods (e.g., days or hours). There are many variations on a moving average:

¦ A weighted average may assign different importance to each data item.
A 3-day weighted average typically values 60 percent of the most
recent price and 30 percent of each prior day:

@weighted_average(price,3) = .60 x price + .30 x price[1] + .30 x price[2]

¦ An exponential moving average (called an "exponential") is a special
type of weighted average, in which each data item is reduced in value
by a constant percentage as it becomes older:

exponential = exponential^] + percentage xj(price - exponential[1])

which may also be entered

@exp_ma(price,smoothing_constant)

where smoothing_constant is the percentage weighting.

In most of this book, whenever a moving average is needed, an expo­ nential moving average ("exponential") will be used. It is the simplest calculation because it does not require all the past data, and the results are nearly identical to other moving averages.

Fundamental Analysis and Trend Following

Economic or fundamental analysis forecasts, and trend evaluation follows. Fundamental analysis attempts to anticipate events by assessing the reaction to current factors and weighing the impact of probable events. Trend calculations look at past data, reduce price movement to a net direction, and assume that prices will continue to do the same as in the past. Trend-following systems respond to events, rather than anticipate them.

Both fundamental analysis and trend following are good methods, but neither are simple nor are they foolproof. This chapter is concerned with trend-following methods and computer applications. New, high- powered graphics equipment has made looking backward much easier, and computerized strategy testing packages have made searching for successful systems painless. But it is not that easy. What worked in the past does not seem to work in the future;—at least not as well, or not all the time.

Trend Trading Noise

Trading in the direction of the trend is a safe, conservative approach. An important feature of trending systems is that they let profits run and cut losses short. Financial analysts call this "conservation of capital." The most reliable trends are slower ones, capturing the long-term direction of interest rates or the decline of the U.S. dollar. Long-term trends should reflect the same direction as government policy.

Trend systems should not be expected to work with data periods shorter than 1 hour. As you look at prices over intervals such as 5 min­ utes, you see mostly "noise." Noise is caused by buy and sell orders from all over the world entering the market for different reasons. Liquidation of stocks for personal reasons, trading objectives that focus on different time periods, currency transactions that hedge internation­ al business exposure, all come in a steady flow into the marketplace. Orders vary in size, and some larger orders find periods of low volume. This results in price gaps and short, fast moves that may appear to be a new price direction.

The level of volatility that occurs during a sustained sideways, direc­ tionless period is a convenient measure of intrinsic noise. A price trend will be unreliable if it is signaled by a move that is no greater than the intrinsic level of market noise (see Figure 8-1).

Slow Trends and Lags

Although longer-term trends are the most dependable, they respond very slowly to changing market conditions. A 200-day moving average

figure 8-1. Intrinsic noise in the Dow Jones Industrial Average, (a) Intrinsic noise can be seen as the lowest normal level of volatility. In the year before the October 1987 plunge, the DOW showed remarkably uniform volatility. The dally trading range of about 25 points makes a stop-loss of 25 points likely to be exe­ cuted without any expectation that prices would continue in one direction, (b) Because of noise, small changes in the daily closing price cannot be considered important Price changes, from close to close, show that over 2 to 3 days, prices could move up or down 30 points. A trend system that buys when prices move up by only 20 DOW points will be unreliable. (Charts courtesy TeleTfac.)

barely reacts to a 10-day burst of energy in a stock issue. If the price of IBM ran from $50 to $70 per share in 20 days, a 200-day moving average would have moved up by no more than $2. It is difficult to consider a method as "trend-following" when a moving average is catching up to a price move that is already over.

Adaptive Approach

To avoid false signals due to noise, yet eliminate some of the lag inher­ent in long-term trends, an adaptive method is needed—a moving aver­ age that will speed up when markets move and do nothing when there is no direction. "Adaptive" is the term given to techniques that self- adjust to market conditions. But again, it is not always clear what patterns will signal the moving average to change speeds.

The Traditional Solution

The most popular way of finding the "best" moving average speed is simply to test all possible trend speeds using historical data. The answer given by the computer depends on the amount of data tested. If you use a long data history, the best choice will be a very slow moving average. If short time periods are tested, the computer will find a number of highly profitable fast and slow solutions; often it will hone in on a sin­ gle large price move to capture all its profits. Because these patterns do not continue, faster trends rarely succeed.

Typically, the more data tested, the more likely the results will be a very slow trend-following system. And that solution is correct. Short-term price bursts are erratic and unpredictable, but the long-term trend is stable. Unfortunately, large equity swings are associated with holding a trade for weeks or months. Everyone wants a short-term, fast-trading trend that works without large losses. That combination does not exist.

Another popular solution is using a computer frequently to retest the speed of the trend. By including the most recent data, the trend speed is always expected to be the best. This still requires decisions such as how often to retest and how much data to use for retesting. Jumping from one fast trend speed to another creates two additional problems. The computer may want you to get into a trade that it entered some time ago and is already highly profitable. That should worry you. It may also result in "overfitting," isolating a very short-term pattern that does not work anymore. If the "best" choice changes frequently, it is because the last choice was not the best.

Adapting to Different Market Trends

A trend-following method is needed that adapts to different market conditions. It must be slow when prices are drifting aimlessly and fast when it is necessary to capture profits. Frequent retesting cannot find this trend because an emerging pattern is only a small piece of the total data.

A solution can be found by remembering how certain market patterns affect trends. To begin, what do we know about price movement that would help an analysis?

•  Fast-moving averages are best when the market is moving quickly in
one direction.

•  Slow-moving averages are best when prices are going nowhere in
choppy markets.

Therefore, the system would be "smart" if it changed speeds accord­ ing to a combination of market direction and speed. Figure 8-2 shows four cases that explain the transition.

Another important principle to remember is that analyzing a lot of data produces robust results. It may give less profitable solutions, but these tend to be more dependable. Analyzing small amounts of data results in many solutions that appear to be good but rarely work.

Moving from Specific Cases to a General Solution

The best choice for a moving average will be the fastest one that can be used for a situation. What, then, do these four cases have in common? Each one shows that the fastest trend that can be used is limited by the amount of noise, or unpredictable price movements. As the market pat­ tern goes from ideally smooth to very noisy (from (a) to (c) in Figure 8-3) the trend speed must get slower to avoid whipsaw losses.

When prices move faster in one direction, the market speed makes the noise less important. Therefore, the choice of a trend speed is based on both noise and direction. A price move that is either cleaner or faster can use a faster trend. What is needed is a mechanism to sense market speed and choppiness; this information can then be fed back into the moving average to adjust the speed of its smoothing.

The Efficiency Ratio combines these features. This ratio divides the net price movement by the total price movement (the sum of each of the indi­ vidual moves taken as a positive number). It can also be considered a ratio of the price direction to its volatility. The more efficient, the faster the trend. A safety factor is built in to the selection of the right trend. If there is any uncertainty, a slower trend is picked. Some readers will recognize the Efficiency Ratio as being what has been recently named generalized fractal efficiency.

(a) Runaway markets: Very fast Markets that break out and never look back can be traded using the fastest practical speed.

(b) Fast markets: Fast speeds.

Fast markets may have some sharp reversals within a prolonged direc­ tional move. A moving average must lag enough to avoid getting caught by the short reversals. The faster the market is rising (falling), the less impact the reversals have on the speed of the trend.


(c) Congested markets: Very slow.

Markets that enter, or are already in, a sideways pattern, cannot be actively traded. A slow trend speed with a large trend change criteria will hold the same position, therefore it will avoid getting whipsawed.

(d) Middle-trends with some vola­ tility: Slightly faster sometimes. As markets start to trend after a sideways period, the speed of the trend can increase. This only works if the level of noise declines; other­ wise, a slow speed is still necessary.

Figure 8-2. Observing price patterns and trends.

The Efficiency Ratio has values ranging from 0, when markets are very noisy for the current amount of direction, to +1 when prices are highly directional. This notation is convenient because it fits perfectly as an exponential smoothing constant. A small transformation scales the value and increases stability (see Box 8-1 ).


Price

Slightly Lagged Trend

(a) No Nois*.

Any trend speed will work.

(b) More Noise.

A slower trend must be used.


Price

Trend

(c) Lots of Noise.

The slowest trend is best.

Figure 8-3. What do these situations have in common? Figure 8-2 shows two characteristics In common: the speed of the price change and the amount of noise associated with that move. Look at the same price change with different amounts of noise.

Defining the Range of Trend Speeds

The range of the Efficiency Ratio (ER), from 0 to 1, can be mapped onto a range of trend speeds using a simple formula. Let ER = 0 be the slowest speed and let ER = 1 be the fastest speed. Then the ratio itself can be used as a percentage that moves between the slowest and the fastest. If the trend speed, in days, is converted to a smoothing constant approxi­ mation using sc = 2/(N + 1), then the slowest speeds have the smallest values. The formula for scaling the smoothing constant becomes

Scaled smoothing constant = ER x (fast sc - slow sc) + slow sc

The range of fast to slow is selected as 2 to 30 days, which is the same as the smoothing constants .6667 and .0645. The scaled speed formula is then

MEASUREMENT

There are three popular ways to measure volatility. The method chosen may differ for specific applications. Figure 8-4 (a)-(c) shows the three approaches. The first (a) is simply the net change in price from the first to the last point. This tends to be the most conservative measurement, because it smooths any price movement that occurs between the begin­ ning and end. The high-low range (b) is more descriptive of any extremes that might have occurred within the period. The sum of all changes (c) is the most encompassing measurement because it distin­ guishes the number of times a price moves from high to low. The Efficiency Ratio uses the last method because a low value of this sum is consistent with the strictest idea of "efficiency."

 


@ABS(P 2 -P 1 )

V(2) = High - Low

V(3) = 1+2+3+. + 15+16

Figure 8-4. Volatility measurement, (a) Positive change in price, (b) High-low range, (c) Sum of all positive changes.

Scaled smoothing constant: sc = ER x (.6667 - .0645) + .0645

= ER X .6022 + .0645

One last step is necessary because the longer-term 30-day moving average will still move slowly up and down, even in a sideways market. The Adaptive Moving Average will be best if it can stop moving when the direction of the market is uncertain. To accomplish this, the final speed is the result of squaring the scaled speed value.

c = sc x sc =

The Adaptive Moving Average

The smoothing constant c is calculated every day and used in the expo­ nential moving average formula. This becomes an Adaptive Moving Average:

Adaptive Moving Average:

AMA = AMA[1] + smoothing_constant x (price - AMA[1])

The complete calculation of the AMA can be found in Box 8-2 . This trend- line has special features:

•  It uses a small number of days (always fixed at 10 in this book) to
assign a trend range from very fast to very slow.

•  The AMA trendline appears to stop when markets have no direction.

•  When prices make a significant move, the AMA trendline catches up,
resulting in a very small lag.

•  Only one parameter may be changed. The Efficiency Ratio can be
based on a 10-day calculation, and that time period may be used for
all markets. The filter size (discussed later) allows some flexibility for
different trading speeds.

•  The AMA was based on analysis rather than testing.

Stock and Forex Examples

Castrol is used to compare the Adaptive Moving Average with a 30-day standard and a 30-day exponential moving average. Comments on trad­ ing are also included. The Deutsche mark is used to show how the AMA

Smarter Trend-Following 139

can produce a smooth trendline through a period of changing market patterns and speed. They also show the adaptability of the AMA, inde­pendent of the market selected.

Castrol

The Castrol chart (Figure 8-5) shows that the three trendlines come together at key points. The AMA does not necessarily turn up or down ahead of the others, but it shows much less lag. Notice the two periods, December 1992 and March 1993. In the first case, the AMA moves up in a few days, then sideways for the next IV2 months until the other trend- lines catch up. A similar situation occurs in March, although the AMA continues to move slowly lower, based on a slightly directional market.

Trending versus Lagging. During December 1992, the Castrol chart shows that the standard trendlines successfully stayed in the upward move until after the peak near the end of February. But during the month of December, there was no trend. December was highly volatile. Had the market continued lower in mid-December, the standard and exponential moving averages would have lost all their profits.

A serious problem with any trend that is fixed at one speed is that it spends most of the time catching up to a price move that has ended. In December and March, the price moves took only a few days, but the trendlines needed another month to catch up. When a trending indica­ tor tells you that the trend is down, it really means that the trendline is going down, even though prices may be going up.

Profit-Taking. The selection of the fastest AMA trend speeds, seen during the sharp rise and fall of the trendline in December and March, pre­cede the end of a significant price move. For reasons discussed in detail in Chapter 5, this becomes an excellent point to exit the position. The December peak above 1000, and the first March low at 800 are near, or bet­ ter, than the exit price that would have been achieved by waiting for the end of the trend. Combined with better executions and lower volatility, covered later, profit-taking is strongly recommended based on a high value of the Efficiency Ratio.

Deutsche Mark: Efficiency Ratio and AMA Trendline

Figure 8-6 uses an arbitrary period for the Deutsche mark to show the Efficiency Ratio and the corresponding AMA trendline. In the middle of November 1992, the Efficency Ratio declines to 0, indicating a period

To create the Adaptive Moving Average, it is first necessary to calculate an Efficiency Ratio, then convert that ratio to a trend speed.

Step 1: Price Direction

Price direction is expressed as the net price change over time. For example, using the time interval of M-days (or n-hours):

direction = price - price[n] or direction = @momentum(price,n)

where direction is the current price difference, or directional value price is current price (daily close or hourly price) price[n] is the close n-days ago (or n-periods ago)

Step 2: Volatility

Volatility is the amount of market "noise." It can be defined a number of different ways, but this calculation uses the sum of all the day-to-day or hour-to-hour price changes (each taken as a positive number), over the same n periods. It is expressed as

volatility = @sum(@abs(price - price[1]),n)

where volatility is today's volatility value

@abs is the absolute value (positive value of any number) @sum(value,n) is the sum of "value" over n periods

Step 3: Efficiency Ratio

These two components are combined to express the ratio of directional movement to noise, called the Efficiency Ratio, ER:

Efficiency_Ratio = direction/volatility

By dividing the directionality by the noise, the ratio varies from 0 to 1. When the market moves in the same direction for all n-days, then direc­ tion = volatility and Efficiency_Ratio = 1. If volatility increases for the same price move, volatility gets larger and the ratio ER moves away from 1. If prices go nowhere, then direction = 0 and ER = 0.

This result is convenient as an exponential smoothing constant, which changes the trendline by a percentage each day. ER = 1 is equiv­ alent to 100 percent, the fastest moving average, which should work because prices moved in one direction without a retracement. When ER = 0, a very slow moving average is best to avoid getting stopped out while the market goes nowhere.

Step 4: Transforming the Ratio into the Trend Speed

The ratio will be changed into a smoothing constant c, for use in an exponential moving average. By using this formula, the trend speed can change each day by simply changing the smoothing constant. It becomes adaptive. The formula for this is

@exp_ma - @exp_ma[1] + c x (price - @exp_ma[1])

which shows that the exponential moving average gets closer to today's close by a percentage, c, of yesterday's gap. The constant c relates closely to the number of days in a standard moving average by the relationship 2/(n - 1), where n is the number of days.

Tests show that squaring the value of the smoothing constant great­ ly improves the results by virtually stopping the trendline from mov­ ing during a sideways market. This process selects very slow trends during sideways markets, and speeds up to a very fast trend (but not 100%) during highly trending periods. The smoothing constant is then

fastest = 2/(N + 1) = 2/(2 + 1) = .6667 slowest = 2/(N + 1) = 2/(30 + 1) = .0645 smooth = ER x (fastest - slowest) + slowest c = smooth x smooth = smooth A 2

Squaring smooth forces the value of c toward zero. This means that slower moving averages will be used more often than fast ones. That is the same as being more conservative when you are uncertain.

AMA = AMA[1] + c x (price - AMA[1])

more noise relative to trend direction. The AMA trendline becomes nearly horizontal for this period (see Figure 8-6(a)), indicating a side­ ways period and allowing the system to hold its long position, or to stand aside, depending on your rules.

During the months of October 1992 and June 1993, clear trends cause the AMA trendline to begin slowly, then increase its speed as the trend develops. In both cases, the Efficiency Ratio peaks over .80 (see Figure 8-6(b)). The Efficiency Ratio may vary from 0 to .40 without the speed of the trendline changing by much. The period from March through May


(b)

(c)

Figure 8-6. Deutsche mark on TeleTrac. (a) Deutsche mark prices with AMA trendline. (b) Efficiency ratio, (c) Moving average days corresponding to the changing AMA smoothing constant. (Charts courtesy TeleTrac.)

1993 shows a relatively noisy but low level for the Efficiency Ratio, resulting in a very slow trend for the AMA.

Figure 8-6(c) shows the moving average days corresponding to the smoothing constant. The days appear upside down relative to the Efficiency Ratio because the trendline slows as the days increase. The days also move in a more extreme manner than the Efficiency Ratio, remaining at its peak level (the program cuts the tops off at 40 days) longer but moving from fast to slow quickly. This is due to the squaring of the smoothing constant after all other calculations are done.

Trading Rules

A basic trend-following system should not be confused with a complete trading strategy. There are no subtleties in the selection of entry and exit timing, nor are there special techniques for entering multiple positions, taking profits, or using other risk controls. Those features must be ana­ lyzed separately to maintain their integrity in a lateral solution. To know if one trend-following method is better than another, it is neces­ sary to simply enter and hold a long position when the trendline moves up, and reverse to a short position when the trendline turns down.

Basic Buy and Sell Signals

The trading rules for the Adaptive Moving Average are:

•  Buy when the Adaptive Moving Average turns up.

•  Sell when the Adaptive Moving Average turns down.

Because the trendline is the result of netting all the price moves, it should represent the best evaluation of the trend. Therefore, the buy and sell signals are based on the direction of the trendline, rather than the price penetration of the trendline.

When exponential smoothing is used, the trendline always turns up and down at the same time the price penetrates the line. The benefit of using the trendline for the Adaptive Moving Average signal is that the formula limits the amount of change in the trendline, making it easy to increase reliability by using a small entry filter.

A Filter for False Signals

A filter is needed for any trending system to avoid false signals caused by noise when prices are moving sideways. During a nondirectional period, prices will move back and forth through the smoothed trendline value. This affects all moving average systems in the same way, but it is more obvious with faster trends. The trendline must move higher or lower by the amount of the filter to qualify for a trading signal.

The Adaptive Moving Average produces a very slow trend during noisy market periods. The 30-day maximum, or .0645 smoothing con­ stant, becomes .0041 when squared, equivalent to a 486-day moving average. When prices move through the AMA, the trendline makes only a very small change. Therefore, only a small filter is needed to avoid most whipsaws.

Self-Adjusting Filter. To be consistent with the adaptive nature of the system, the filter will be also get larger and smaller when prices become more or less volatile. To accomplish this, the filter is defined as a small per­ centage of the changes in the AMA trendline:

filter = percentage x @std_dev(AMA - AMA[1],n)

where percentage is the percentage of 1 standard deviation, @std_dev(series,n) is the standard deviation of series over n periods, and AMA - is the 1-day change in the AMA trendline.

The. smallest filter percentages of .01 can be used for faster trading, while the larger percentages of 1.0 select those trades that have had a more significant price move. Typically, forex and futures markets trade faster, stock and interest rate markets trade slower. Normally, the filter is calculated over a period of 20 days.

Adding the Filter to the Rules. Using the filter, the one-period change in the AMA trendline must be bigger or smaller than the filter size to get a buy or sell signal. This works well for selecting trades and elimi­ nating false signals. One problem occurs, however, when the trendline very gradually changes direction. The change in the AMA trendline may not be greater than the filter on the first or the second or the third day. That may be good, because a slow trend change may reverse to be a continua­tion of the opposite trend direction. But if those small changes continue, the trend could have reversed without giving a new trading signal.

If the new buy and sell signals are based on comparing the one-period changes in the AMA trendline with the filter, a signal could occur well after the new trend begins. To eliminate this possibility, the most recent lowest and highest points on the AMA are recorded. Instead of comparing the one-period changes with the filter, the total change in the AMA since its recent high and low is compared against the filter.

Price

Low Point of AMA

 

Figure 8-7. Filtering a slow trend change. Because a slow trend change may result In a series of days which fail to pene­trate the filter, the net change over 1 to 3 days is substituted for a single day.


The first day of the trend change, marked "1" in Figure 8-7, is very small, therefore no buy signal occurs. The changes on days 2 and 3, taken separately, are also smaller than the filter. Instead, on day 2 the total change from the 2nd day of the trend change to the recent low is compared with the filter, but that is still too small. A signal occurs on the third day, when the total difference from the low is greater than the filter, AMA(low + 3 days) > Filter.

The new rules for trading signals are

Buy when AMA - @lowest(AMA,n) > filter Sell when @highest(AMA,n) - AMA > filter

When programming a computer, the sell signal may also be written Sell when AMA - @highest(AMA,n) < -filter

Alternate Bay and Sell Rules. It is difficult to record the recent high and low trend points on some computers and programmable trading machines. A simple, practical substitute is to compare the last three accu­ mulated trend changes against the filter to generate a buy or sell signal.

This approach should work as well in all cases. For example,

Buy when AMA - AMA[1 ] > filter or

Buy when AMA - AMA[2] > filter or

Buy when AMA - AMA[3] > filter

Testing the AMA

Before using the Adaptive Moving Average, it will be necessary to test each market. The following points should help:

•  The primary parameter is the number of days used to calculate the
Efficiency Ratio. This will be near 10 for the fast trader. Using a value
below 5 will cause the ratio to jump from 0 to 1 quickly. Using a
much larger value will cause the ratio to be more stable noise rela­
tionship that can be very attractive to the position trader.

•  The filter value is expressed as a percentage of the standard devia­
tion of the trend changes; therefore, it is independent of price.
However, a larger or smaller filter percentage is used to change the
length of a trade. A small value allows an entry sooner, while a larg­
er percentage will delay entry.

•  The number of days in the standard deviation, which determines the
filter, could be fixed at 20. A statistical measure requires at least 20
days to have some stability.

Testing for short-term trading could fix the AMA days at 10 and the standard deviation days at 20, and test only the filter. Fewer parameters mean a more dependable solution. Longer-term positions are not affect­ ed by the filter; therefore it can be fixed at some value under 1.0.

Profit-Taking. Another look at Figure 8-6 shows that the Efficiency Ratio peaks over .80 (panel b) and the moving average days drops under 10 (in panel c) at points that would be good for taking profits. It is a characteristic of the Adaptive Moving Average that a high value for the Efficiency Ratio cannot be sustained and will be followed by a reversal. It would be best simply to take profits whenever the value exceeds a preset level. That threshold will vary based on the intrinsic noise of the market.

Programming the Adaptive Moving Average

The Adaptive Moving Average can be programmed into any spread­ sheet or strategy-testing software. The following examples show the codes for Quattro Pro (very similar to Lotus), Telerate's TeleTrac, and Omega's TradeStation. Signals should not begin for 25 days, because the filter requires 20 days of AMA trendline changes, and the AMA needs an additional 5 days to start up.

Spreadsheet Instructions

Box 8-3 and Table 8-1 give the spreadsheet instructions and sample results. All constants have been placed in row 2. The recent AMA highs and lows are recorded in columns L and M.

Telerate's TeleTrac

The TeleTrac code ( Box 8-4 ) uses the alternate buy and sell signal calcu­ lation, comparing 3 days of AMA changes separately. It also uses the MACD study ("SIGNAL") to calculate an exponential moving average with a changing smoothing constant. This code can be used to trade live data. 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 Omega products ( 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 "AMA smooth" (Part 3) to place the smoothing constant along the bottom of the graph.

OMEGA EASY LANGUAGE CODE FOR THE ADAPTIVE 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 begin

signal = @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 begin

if (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 extlow and exthigh. It can then use those points to compare the accumulated change of direction against the filter and avoid missing a signal due to a very slow trend change.

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 begin

signal = @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 the chart 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 begin

signal = @ AbsValue(close - close[period]);

noise = @Summation(diff,period);

efratio = signal/noise;

smooth = @Power(efratio*(fastend - slowend) + slowend,2);

Plot1(smooth,"AMA smooth");

end;

 
 

 Back to contents page

stock market
stock investing
online stock trading  
©2007 Olesia HomeMy photosForexNewsMy tradingContacts