<<

. 4
( 9)



>>

the moving average, a fixed normalization did not seem sound. We replaced the stan-
dard deviation divided by the normalizing factor (used by Chande) with a ratio of
two measures of volatility: one shorter term and one longer term. The relative
volatility required for adjusting c, and hence the period of the adaptive moving aver-
age, was obtained by dividing the shorter term volatility measure by the longer term
volatility measure. The volatility measures were exponential moving averages of the
squared differences between successive data points. The shorter moving average of
squared deviations was set to a period of p, an adjustable parameter, while the peri-
od of the longer moving average was set top multiplied by four. If the longer term
volatility is equal to the most recent volatility (i.e., if their ratio is 1). then the adap-
tive moving average behaves identically to a standard exponential moving average
with period m; however, the effective period of the exponential moving average is
monotonically reduced with an increasing ratio of short-term to long-term volatility,
and increased with a declining ratio of short-term to long-term volatility.

TYPES OF MOVING AVERAGE ENTRY MODELS
A moving average entry model generates entries using simple relationships
between a moving average and price, or between one moving average and another.
Trend-following and countertrend models exist. The most popular models follow
the trend and lag the market. Conversely, countertrend moving average models
anticipate reversals and lead, or coincide with, the market. This is not to imply that
countertrend systems trade better than trend-following ones. Consistently entering
trends, even if late in their course, may be a more reliable way to make money than
anticipating reversals that only sometimes occur when expected. Because of the
need for a standard exit, and because no serious trader would trade without the pro-
tection of money management stops, simple moving average models that are
always in the market are not tested. This kind of moving average reversal model
will, however, be fairly well-approximated when fast moving averages are used,
causing reversal signals to occur before the standard exit closes out the trades.
Trend-following entries may be generated in many ways using moving aver-
ages. One simple model is the ntoving average C˜SSDWE The trader buys when
prices cross above the moving average and sells when they cross below. Instead of
waiting for the raw prices to cross a moving average, the trader can wait for a faster
moving average to cross a slower one: A buy signal occurs when the faster moving
average crosses above the slower moving average, and a sell is signalled when the
crossover is in the other direction. Smoothing the raw price series with a fast mov-
ing average reduces spurious crossovers and, consequently, minimizes whipsaws.
Moving averages can also be used to generate countemend entries. Stock prices
often react to a moving average line as they would to the forces of support or resis-
tance; this forms the basis of one countertrend entry model. The rules are to buy when
prices touch or penetrate the moving average from above, and to sell when penetration
is from below. Prices should bounce off the moving average, reversing direction.
Countertrend entries can also be achieved by responding in a contrary manner to a
standard crossover: A long position is taken in response to prices crossing below a
moving average, and a short position taken when prices cross above. Being contrary-
doing the opposite of what seems “right”+ften works when trading: It can be prof-
itable to sell into demand and buy when prices drop in the face of heavy selling. Since
moving averages lag the market, by the time a traditional buy signal is given, the mar-
ket may be just about to reverse direction, making it time to sell, and vice versa.
Using a moving average in a counter&end model based on support and resis-
tance is not original. Alexander (1993) discussed retracement to moving average sup
port after a crossover as one way to set up an entry. Tilley™s (1998) discussion of a
two parameter moving average model, which uses the idea of support and resistance
to trade mutual funds, is also relevant. Finally, Sweeney (1998) described the use of
an end-of-day moving average to define inuaday levels of support and resistance.

CHARACTERISTICS OF MOVING AVERAGE
ENTRIES
A trend-following moving average entry is like a breakout: Intuitively appealing
and certain to get the trader aboard any major trend: it is also a traditional, readily
available approach that is easy to understand and implement, even in a spreadsheet.
However, as with most trend-following methods, moving averages lag the market,
i.e., the trader is late entering into any move. Faster moving averages can reduce lag
or delay, but at the expense of more numerous whipsaws.
A countertrend moving average entry gets one into the market when others
are getting out, before a new trend begins. This means better fills, better entry
prices, and greater potential profits. Lag is not an issue in countertrend systems.
The danger, however, is entering too early, before the market slows down and turns
around. When trading a countertrend model, a good risk-limiting exit strategy is
essential; one cannot wait for the system to generate an entry in the opposite direc-
tion. Some countertrend models have strong logical appeal, such as when they
employ the concept of support and resistance.

ORDERS USED TO EFFECT ENTRIES
Entries based on moving averages may be effected with stops, limits, or market
orders, While a particular entry order may work especially well with a particular
model, any entry may be used with any model. Sometimes the entry order can
form part of the entry signal or model. A basic crossover system can use a stop
order priced at tomorrow™s expected moving average value. To avoid intraday
whipsaws, only a buy stop or a sell stop (not both) is issued for the next day. If the
close is above, a sell stop is posted; if below, a buy stop.
Entry orders have their own advantages and disadvantages. A market order
will never miss a signalled entry. A stop order will never miss a significant trend
(in a trend-following model), and entry will never occur without contirmation by
movement in favor of the trade; the disadvantages are greater slippage and less
favorable entry prices. A limit order will get the best price and minimize transac-
tion costs, but important trends may be missed while waiting for a retracement to
the limit price. In countertrend models, a limit order may occasionally worsen the
entry price: The entry order may be filled at the limit price, rather than at a price
determined by the negative slippage that sometimes occurs when the market
moves against the trade at the time of entry!

TEST METHODOLOGY
In all tests that follow, the standard portfolio is used. The number of contracts to
buy or sell on entry, in any market, at any time, was chosen to approximate the dol-
lar volatility of two S&P 500 contracts at the end of 1998. Exits are the standard
ones. All tests are performed using the C-Trader toolkit. The portfolios, exit strate-
gies, and test platform are identical to those used previously, making all results
comparable. The tests are divided into trend-following and counter&end ones.
They were run using a script containing instructions to set parameters, run
Moving-Average Models
CHAPTER 6


optimizations, and generate output for each combination of moving average type,
model, and entry order.
The code below is more complex than for breakouts: Instead of a different
routine for each combination of moving average, entry rule, and trading order,
there is one larger routine in which parameters control the selection of system ele-
ments. This technique is required when systems are genetically evolved. Although
no genetics are used here, such algorithms are employed in later chapters. This
code uses parameters to control model elements, making it easier to handle all the
combinations tested in a clean, systematic way.




local variables for clearer reference
// period for faster moving average
// period for slower moving average
I/ type Of entry model
I/ type of moving average
I/ type Of entry order
I/ maximum holding period
I/ profit target in volatility units
// stop loss in volatility units
116



// skip invalid parameter combinations
if(fastmale" >= slovmlale") {
set-"ector˜eqcls, 1, rib, 0.01;
return;
)
I/ perform whole-series computations using vector routines
// ATR for exit
*"gTr"eRa"ses(exitatr, hi, 10, ClS, 50, "b);
switchbvgtype) ( // select type of moving average
case 1: // simple moving averages
A"erageS˜fastma, cls, fastmale", "b);
AverageSislovmla, ClS, slowmale*, nbl;
break;
,, exponential mo"i"g averages
case 2:
xA"erageS(fastma, ClS, fastmale", "b, ;
xA"erageS˜slowma, CL%, s1ovmden. "b) ;
break;
case 3: // front-weighted triangular moving averages
FwTn"erages˜fastma, ClS, fastmale", nb,;
FwTAverageS ˜slowma, ClS, slowmale", "b, ;
break;
case 4: // "IDYA-style adaptive moving averages
"rn"erages˜fastma, ClS. fastmale". 10, "b, ;
"IA"erageS˜slowma, ClS. *lowmale", 10. &I;
break;
default: "rerror˜"I""alid mo"i"g average selected");
1;




// avoid placing orders on possibly limit-locked days
if (hi L&+11 == lo L&+11 1 continue;

,, generate entry signals, stop prices and limit prices
// using the specified moving average entry model
// enter trades using specified order type
ifCts.positionO c= 0 && signal == 1) (
switch(ordertype1 ( // select desired order type
case 1: ts.b"yopen˜˜1'. ncontracts,; break;
case 2: ts.buylimitC˜Z', limprice, ncontracts); break;
The code contains three segments. The first segment calculates moving aver-
ages. A parameter (avgrype) selects the kind of average: 1 = simple; 2 = expo-
nential: 3 = front-weighted triangular; and 4 = the modified VIDYA. Even if the
model requires only one moving average, two of the same type are computed, this
allows the selection of the moving average to be independent of model selection.
The average true range is also computed and is required for setting stop-losses and
profit targets in the standard exit strategy. Two additional parameters, fastmalen
and slowmalen, specify the period of the faster and the slower moving averages,
respectively. The moving averages are saved in the vectors,fismzma and slowma.
The next block uses the selected model to generate entry signals, stop prices,
and limit prices. First, simple relationships (CrossesAbove, CrossesBelow,
TurnsUp, and TurnsDown) are defined. Depending on modeltype, one of four mov-
ing average models then generates the signals: 1 = the classic, trend-following dual
moving average crossover; 2 = a slope-based trend-following model; 3 = a coun-
tertrend crossover model; and 4 = a countertrend support/resistance model. In the
classic, trend-following dual moving average crossover, the trader goes long if a
faster moving average of the closing price crosses above a slower moving average,
and goes short if the faster moving average crosses below the slower one. As a spe-
cial case, this model contains the classic crossover that compares prices to a mov-
ing average. The special case is achieved when the period of the shorter moving
average is set to 1, causing that moving average to decay to the original series, i.e.,
the closing prices. With a slope-based trend-following model, the trader buys when
the moving average was decreasing on previous bars but increases on the current
bar (slope turns up), and sells when the opposite occurs. This model requires only
the fast moving average. The countertrend model is the opposite of the classic
trend-following crossover: The trader buys when the shorter moving average (or the
price itself) crosses below the longer moving average, and sells when it crosses
above. This model is the contnuian™s delight: Doing exactly the opposite of the
trend-followers. Last is a crude countertrend support/resistance model in which
prices are expected to bounce off the moving average, as if off a line of support or
resistance. The rules are almost identical to the countertrend crossover model,
except that the slower moving average must be moving in the direction of the entry:
If the slower moving average is trending upward, and prices (or the faster moving
average) move from above that slower moving average into or below it, the trader
buys; conversely, if prices (or the faster moving average) are currently below a
downward trending slower moving average, and prices bump into or penetrate that
moving average from below, then the trader sells. The additional trend rule prevents
an immediate reversal of position after contact or penetration. Without the trend
rule, a quick penetration followed by a reversal would trigger two entries: The fast
would be the desired countertrend entry, occurring when the prices penetrate the
moving average, and the second entry (in the opposite direction) would occur as the
prices bounce back, again crossing the moving average. The trend check only
allows entries to be taken in one direction at a time. A penetration, followed by a
bounce in an up-trending market, will take the long entry; a penetration and rever-
sal in a down-trending market will result in a short entry.
In the last block of code, the entry order to be posted is determined by the
ordertype parameter: 1 = market at open; 2 = limit; 3 = stop. Whether a buy or
sell is posted, or no order at all, is determined by whether any signal was generat-
ed in the previous block of code; a variable called signal carries this information: 1
= buy; - 1 = sell (go short); 0 = do nothing. The limit price (limpn™ce) is com-
puted as the sum of today™s high and low prices divided by two. Because many of
the models have no natural price for setting a stop, a standard stop was used. The
standard entry stop price (stpprice) is obtained by taking the closing price of the
previous bar and adding (if a long position is signalled) or subtracting (if a short is
signalled) the 50-bar average true range multiplied by 0.50; the market must move
at least one-half of its typical daily range, in the direction of the desired entry, for
the entry to occur. This type of stop order adds a breakout test to the moving aver-
age system: Once a signal is given, the market must move a certain amount in the
direction of the trade to trigger an entry. Because of the large number of tests, sta-
tistical significances were not reported unless something notable occurred.

TESTS OF TREND-FOLLOWING MODELS
The group of tests presented here involve moving averages as trend-followers. The
models vary in the kinds of moving average, the rules that generate signals, and
the orders posted to effect entry. The moving averages tested include the simple,
120




the exponential, the front-weighted triangular, and a modification of VIDYA. Both
single and dual moving average crossovers, and models that use slope (rather than
crossover) to determine entry, are examined. Entry orders are market-at-open,
stop, and limit.
Tests 1 through 12 were of the crossover models, Optimization was per-
formed by stepping the length of the shorter moving average from 1 to 5, in incre-
ments of 1, and the longer moving average from 5 to 50, in increments of 5. Only
cases in which the longer moving average was strictly longer than the shorter mov-
ing average were examined. Brute force optimization was used, controlled by the
testing script. The parameters were chosen to maximize the risk-to-reward ratio or,
equivalently, minimize the probability (based on a t-test of daily returns) that any
profitable performance was due to chance. In Tests 13 through 24 (the slope mod-
els), brute-force optimization was performed by stepping the length of the first
and, in this case, only moving average from 3 to 40, in increments of 1. As in Tests
1 through 12, the risk-to-reward ratio was maximized. Optimization was only car-
ried out on in-sample data.
Tables 6-l and 6-2 show, for each of the 24 tests, the specific commodities that
the model traded profitably and those that lost, for the in-sample (Table 1) and out-
of-sample (Table 6-2) runs. The SYM column represents the market being studied;
the first row identifies the test. The data provides relatively detailed information
about which markets were and were not profitable when traded by each of the mod-
els: One dash (-) indicates a moderate loss per trade, i.e., $2,000 to $4,000, two
dashes (- -) represent a large loss per trade, i.e., $4,000 or more; one plus sign (+)
means a moderate profit per trade, i.e., $1,000 to $2,000; two pluses (+ +) indicates
a large gain per trade, i.e., $2,000 or more; a blank cell means that the loss was
between $0 and $1,999 or the profit was between $0 and $1,000 per trade.
Table 6-3 shows, for the entire portfolio, the return-on-account (ROA%) and
average dollar-per-trade ($TRD) broken down by the moving average, model,
entry order, and sample. The last two columns on the right, and the last four rows
of numbers on the bottom, are averages. The numbers at the bottom have been
averaged over all combinations of moving average type and model. The numbers
at the right are averaged over order type.
None of the trend-following moving average models was profitable on a port-
folio basis. More detailed examination reveals that for the crossover models the
limit order resulted in a dramatic benefit on the in-sample data. When compared
with an entry at open or on a stop, the limit cut the loss of the average trade almost
in half. Out-of-sample, the improvement was not as dramatic, but still significant.
The return-on-account showed a similar pattern: The least loss was with the limit
order. For slope models, the limit order worked best out-of-sample in terms of dol-
lars per trade. The return-on-account was slightly better with a stop (due to distor-
tions in the ROA% numbers when evaluating losing systems), and worse for entry
at open. In-sample, the stop order performed best, but only by a trivial amount.
TABLE 6-l

In-Sample Performance Broken Down by Test and Market




In-sample, the simple moving average provided the best results in average
dollars-per-trade. The worst results were for the adaptive moving average. The
other two moving averages fell in-between, with the exponential better in the
crossover models, and the front-weighted triangular in the slope models. Of the
crossover models, the ROA% was also the best for the simple moving average.
Overall, the crossover models did as well or better than the slope models, possi-
bly because of a faster response to market action in the former. Out-of-sample,
the simple moving average was the clear winner for the crossover models, while
the front-weighted triangular was the best for the slope models. In terms of the
TABLE 6-2

Out-of-Sample Performance Broken Down by Test and Market




ROA%, the exponential moving average appeared the best for the crossover
models, with the front-weighted triangular still the best for the slope models.
When looking at individual tests, the particular combination of a front-
weighted triangular moving average, the slope model, and entry on stop (Test 21)
produced the best out-of-sample performance of all the systems tested. The out-of-
sample results for the front-weighted triangular slope models seemed to be better
across all order types. There apparently were some strong interactions between the
various factors across all tests, e.g., for the crossover model on the in-sample data,
entry at the open was consistently close to the worst, entry on stop was somewhere
in between, and entry on limit was always best, regardless of the moving average
6-3
TABLE

Performance of Trend-Following Moving Average Entry Models
Broken Down by Order, Moving Average Type, Model, and Sample




used. Out-of-sample, the findings were much more mixed: With the simple moving
average, the pattern was similar to that for the in-sample period; however, with the
exponential moving average, the limit performed worst, the stop best, and the open
not far behind. Out-of-sample, with the front-weighted triangular average, the stop
performed by far the worst, with the limit back to the best performer. These results
indicate interaction between the moving average, entry order, and time.
The slope model, in-sample, had the entry at open always performing worst;
however, although the results were often quite close, the limit and stop orders were
hvice seen with the limit being favored (simple moving average and adjusted moving
average), and twice with the stop being favored (exponential moving average and
front-weighted triangular moving average). As before, great variation was seen out-
of-sample.
For the simple moving average, the limit order performed best and the stop
worst. The more typical pattern was seen for the exponential moving average: The
entry at open performed worst, the limit best, and the stop was on the heels of the
limit. As already stated, the front-weighted triangular moving average performed
very unusually when combined with the stop order. The limit was best for the
adaptive moving average, the stop was worst, and the open was slightly better
albeit very close to the stop.
As a whole, these models lost on most markets. Only the JapaneseYen and Pork
Bellies were profitable both in- and out-of-sample; no other markets were profitable
in-sample. Out-of-sample, some profits were observed for Heating Oil, Unleaded
Gasoline, Palladium, Live Hogs, Soybean Meal, Wheat, and Coffee. The strong out-
of-sample profit for Coffee can probably be explained by the major run-up during the
drought around that time. On an individual model-order basis, many highly profitable
combinations could be found for Live Hogs, JapaneseYen, Pork Bellies, Coffee, and
Lumber. No combinations were profitable in either sample for Oats.
In terms of equity averaged over all averages and models, entry at the open
performed, by far, the worst. Entry on limit or stop produced results that were
close, with the limit doing somewhat better, especially early in the test period. It
should be noted that, with the equity curves of losing systems, a distortion takes
place in their reflection of how well a system trades. (In our analyses of these los-
ing systems, we focused, therefore, on the average return-per-trade, rather than on
risk-reward ratios, return-on-account, or overall net profits.) The distortion
involves the number of trades taken: A losing system that takes fewer trades will
appear to be better than a losing system that takes more trades, even if the better
appearing system takes trades that lose more on a per-trade basis. The very heavy
losses with entry at open may not be a reflection of the bad quality of this order;
it may simply be reflecting that more trades were taken with an entry at the open
than when a stop or limit order was used.
Figure 6-l presents the equity curves for all eight model and moving average
combinations. The equity curves were averaged across order type. Figure 6-l pro-
vides a useful understanding of how the systems interact with time. Most of the sys-
tems had their heaviest losses between late 1988 and early 1995. The best
performance occurred before 1988, with the performance in the most recent period
being intermediate. In Curve 3, the simple moving average crossover model was the
most outstanding: This pattern was greatly exaggerated, making the equity curve
appear very distinct; it actually showed a profit in the early period, a heavier rela-
tive loss in the middle period, and levelled off (with a potential return to flat or prof-
itable behavior) toward the end of the third period. Finally, it is dramatically evident
that the crossover systems (Curves 1 through 4) lost much less heavily than the
FIGURE 6-1

Equity Curves for Each Model and Moving Average Combination




slope-based models (Curves 5 through S), although this reflects a larger number of
trades, not greater losses on a per trade basis.

TESTS OF COUNTER-TREND MODELS
As with trend-following models, countertrend models vary in the moving averages
used, the rules that generate signals, and the orders posted to effect entry. The
same moving averages used in the trend-following models are studied here. Both
single and dual moving average models are examined. Entry orders studied are the
market-at-open, stop, and limit.
Tests 25 through 36 evaluate the standard moving average crossover model
turned upside-down. As before, entry signals occur when prices cross the average,
or when a shorter average crosses a longer one. In traditional trend-following
crossover models, the trader buys when the price (or a shorter moving average)
crosses above a longer moving average, and sells when it crosses below. In the
contrarian crossover model, the trader sells when prices cross above, and buys
when prices cross below. In these tests, brute force optimization was performed on
the in-sample data by stepping the length of the shorter moving average from 1 to
7, in increments of 1; the longer moving average was stepped from 5 to 50, in
increments of 5. Only cases where the longer moving average was longer than the
shorter moving average were considered. The parameters minimized the probabil-
ity that any observed profitable performance was due to chance. The model was
run on the out-of-sample data using the best parameter set found in-sample.
In tests of the support/resistance model (37 through 48), the trader buys when
prices bounce off a moving average from above, and sells when they hit a moving
average from below. In this way, the moving average serves as a line of support or
resistance where prices tend to reverse. The rules are almost the same as for Tests 25
through 36, except that not every penetration of a moving average results in an entry.
If prices are above the moving average and penetrate it, a buy is generated; howev-
er, when prices bounce back up through the moving average, the second crossover
is not allowed to trigger a sell. If prices arc below the moving average and rise into
it, a sell is triggered, no buy is triggered when the prices bounce back down. This
behavior is achieved by adding one element to the contrarian crossover model: A sig-
nal is generated only if it is in the direction of the slope of the slower moving aver-
age. Performance was brute force optimized on the in-sample data by stepping the
length of the shorter moving average from 1 to 5, in increments of 1, and the longer
moving average from 5 to 50, in increments of 5. A moving average length of 1
caused the shorter moving average to become equivalent to the prices; therefore, in
the optimization, the model in which prices were compared to the moving average
was tested, as was the model in which one moving average was compared to anotb
er. Only cases where the longer moving average was strictly longer than the shorter
moving average were examined. The parameters were chosen to minimize the prob-
ability that any profitable performance was due to chance. The model was then run
on the out-of-sample data using the best parameter set found in-sample.
Tables 6-4 and 6-5 show, for Tests 25 through 48, the commodities that the
model traded profitably and those that lost, in-sample (Table 6-4) and out-of-sam-
ple (Table 6-S). The plus and dash symbols may be interpreted in the same man-
ner as for Tables 6-1 and 6-2.
Table 6-6 provides the results broken down by the moving average, model,
order, and sample. The last two columns on the right, and the last four rows of
numbers on the bottom, are averages. The numbers at the bottom were averaged
over all combinations of moving average type and model. The numbers at the right
were averaged over order type.
Overall, the best models in-sample were the simple moving average sup-
port/resistance and the front-weighted triangular average support/resistance. The
simple average support/resistance with a stop order was unique in that it showed
small profits in both samples: an average trade of $227 and a 4.2% retum-on-
account in-sample, $482 per trade and a 14.8% return-on-account out-of-sample.
The front-weighted triangular average with the stop was profitable in-sample, but
lost heavily out-of-sample. Both models, especially when combined with a stop,
had relatively few trades: consequently, the results are less statistically stable.
TABLE 6-4

In-Sample Performance Broken Down by Test and Market




Overall, in-sample, the stop order was best for contrarian crossovers and for sup-
port/resistance models, in which the stop led to an average profitable result, and
the other two orders led to losses; the market-at-open was the worst order. Out-of-
sample, the market-at-open order was still, overall, worst for both the contrarian
crossover and the support/resistance models; the limit was best. There were much
greater losses out-of-sample than in-sample for both models.
The countertrend models pertormed less well than the trend-following ones;
however, there were outstanding combinations of counter-trend model, average we,
and entry order that performed far better than most other combinations tested.
On the basis of the moving average and breakout results, it appears that,
with trend-following models, a limit order almost always helps performance; for
Out-of-Sample Performance Broken Down by Test and Market




countertrend models, a stop sometimes provides an extra edge. This tendency
might result from trend-following models already having a trend detection ele-
ment: Adding another detection or verification element (such as an entry on a
stop) is redundant, offering no significant benefit; however, the addition of a limit
order provides a countertrend element and a cheaper entry, thus enhancing per-
formance. With countertrend models, the addition of a trend verification element
provides something new to the system and, therefore, improves the results.
Sometimes it is so beneficial that it compensates for the less favorable entry
prices that normally occur when using stops.
On a market-by-market basis, model-order combinations that were strongly
profitable in both samples could be found for T-Bonds, JO-Year Notes, Japanese
Summary of Countertrend Moving Average Entry M o d e l s B r o k e n
Down by Order, Moving Average Type, Model, and Sample




Yen, Deutschemark, Swiss Franc, Light Crude, Unleaded Gasoline, Coffee,
Orange Juice, and Pork Bellies.
Figure 6-2 depicts equity curves broken down by model and moving average
combination; equity was averaged over order type. The best two models were the
front-weighted triangular average support/resistance and the simple average sup-
port/resistance. The best support/resistance models performed remarkably better
than any of the contrarian crossover models. There were three eras of distinct
behavior: the beginning of the sample until October 1987, October 1987 until June
1991, and June 1991 through December 1998, the end of the sample. The worst
performance was in the last period.
FIGURE 6-P

Equity Curves by Model and Moving Average Combination




--sM&CC
----EM*-CC
---mc
-˜-˜AMAZC
. . . . ..*M*-8a
-FwnA&sR
1




On the basis of the equity curves in Figure 6-2, as well as others not
shown, it is evident that the countertrend models were better in the past, while
the trend-following models performed better in recent times. In-sample, the
stop order was best for every model-average combination, and, out-of-sample,
for three of the six (two combinations had no trades so were not considered);
entry at the open was worst in all but two cases. The stop was generally supe-
rior to the limit order, in-sample; out-of-sample, the limit was only marginally
better than the stop.

CONCLUSION
In general, the trend-following models in Tests 1 through 24 performed better than
the countertrend models in Tests 25 through 48, with a number of exceptions dis-
cussed above.
The best models apparently are those that combine both countertrend and
trend-following elements. For example, attempting to buy on a retracement with
a limit, after a moving average crossover or breakout, provides better results than
other combinations. In the countertrend moving average models, those that have
a trend-following element (e.g.. a stop) perform better. Pure countertrend models
and pure trend-following models do not fare as well. Moreover, adding a trend-
following filter to an already trend-following system does not seem beneficial,
but may instead increase entry cost. Traders should try combining one of these
countertrend models with something like the ADX trend filter. Although the ADX
filter may not have helped breakouts (because, liethe stop, it represents anoth-
er trend-following element added to an already trend-following model), in a
countertrend model such an element may provide an edge. As true with break
outs, the limit order performed best, except when the stop was beneficial due to
its trend filtering characteristics,
The results suggest certain generalizations. Sometimes a stop can provide
enough benefit to overcome the extra transaction costs associated with it, although
a limit order generally performs best because of its ability to reduce costs. While
such a generalization might help guide a trader™s choices, one has to watch for
potential interactions within the moving average type-model-order combinations
that may cause these generalizations to fail. The variables interact: Although each
variable may have its own characteristic effect, when put in combination with
other variables, these effects may not maintain their integrity, but may change due
to the coupling; this is demonstrated in the tests above. Sometimes variables do
maintain their integrity, but not always.

WHAT HAVE WE LEARNED?
. When designing an entry model, try to effectively combine a countertrend
element with a trend-following one. This may be done in any number of
ways, e.g., buy on a short-term countertrend move when a longer-term
trend is in progress; look for a breakout when a countertrend move is in
progress; or apply a trend-following filter to a countertrend model.
n If possible, use orders that reduce transaction costs, e.g., a limit order for

entry. But do not be rigid: Certain systems might perform better using
another kind of order, e.g., if a trend-following element is needed, a stop
might be advisable.
n Expect surprises. For the slope-based models, we thought the adaptive,

moving average, with its faster response, would provide the best perfor-
mance; in fact, it provided one of the worst.
. Even though traditional indicators, used in standard ways, usually fail (as
do such time-honored systems as volatility breakouts), classical concepts
like suppoa/resistance may not fail; they may actually be quite useful. In
breakouts, models based on the notion of support/resistance held up bet-
ter than did, e.g., volatility breakouts. Likewise, moving average models
using the concept of support/resistance did better than others. The sup-
port/resistance implementation was rudimentary, yet, in the best combina-
tion, it was one of the best performers; perhaps a more sophisticated
version could provide a larger number of more profitable trades.
Although support/resistance seems to be an important concept, further
research on it will not be easy. There are many variations to consider
when defining levels of support and resistance. Determining those levels
can be quite challenging, especially when doing so mechanically.
CHAPTER 7


Oscillator-Based Entries




0. have been popular among technical traders for many years. Articles
scdlators
that describe oscillators appear quite frequently in such magazines as Technical
Analysis of Stocks and Commodities and Futures. The subject is also covered in
many books on uading.
Most widely used, in both their classic forms and variations, are Appel™s
(1990) Moving Average Convergence Divergence (MACD) oscillator and MACD-
Histogram (MACD-H). Also highly popular are Lane™s Stochastic, and Williams™s
Relative Strength Index (RSI). Many variations on these oscillators have also
appeared in the literature. Other oscillators include Lambert™s Commodities
Channel Index (CCI), the Random Walk Index (which might be considered an
oscillator), and Goedde™s (1997) Regression Channel Oscillator. In this chapter,
the primary focus is on the three most popular oscillators: the MACD, Stochastic&
and the RSI.

WHAT IS AN OSCILLATOR?
An oscillator is an indicator that is usually computed from prices and that tends to
cycle or “oscillate” (hence the name) within a fixed or fairly limited range.
Oscillators are characterized by the normalization of range and the elimination of
long-term trends or price levels. Oscillators extract information about such tran-
sient phenomena as momentum and overextension. Momentum is when prices
move strongly in a given direction. Overextension occurs when prices become
excessively high or low (“overbought” or “oversold”) and are ready to snap back
to more reasonable values.
KINDS OF OSCILLATORS
There are two main forms of oscillators. Linear band-pass filters are one form of
oscillator. They may be analyzed for frequency (periodicity) and phase response.
The MACD and MACD-H are of this class. Another form of oscillator places
some aspect of price behavior into a normalized scale (the RX, Stochastics, and
CC1 belong to this class); unlike the first category, these oscillators are not linear
filters with clearly defined phase and frequency behavior. Both types of oscillators
highlight momentum and cyclical movement, while downplaying trends and elim-
inating long-term offsets: i.e., they both produce plots that tend to oscillate.
The Moving Average Convergence Divergence Oscillator, or MACD (and
MACD-Histogram), operates as a crude band-pass filter, removing both slow
trends and offsets, as well as high-frequency jitter or noise. It does this while pass-
ing through cyclic activity or waves that fall near the center of the pass-band. The
MACD smooths data, as does a moving average; but it also removes some of the
trend, highlighting cycles and sometimes moving in coincidence with the market,
i.e., without lag. Ehlers (1989) is a good source of information on this oscillator.
The MACD is computed by subtracting a longer moving average from a
shorter moving average. It may be implemented using any kind of averages or low-
pass filters (the classic MACD uses exponential moving averages). A number of
variations on the MACD use more advanced moving averages, such as the VIDYA
(discussed in the chapter on moving averages). Triangular moving averages have
also been used to implement the MACD oscillaror. Along with the raw MACD, the
so-called MACD Histogram (MACD-H) is also used by many traders. This is
computed by subtracting from the MACD a moving average of the MACD. In
many cases, the moving average of the MACD is referred to as a signul line.
The Stochastic oscillator is frequently referred to as an overbought/oversold
indicator. According to Lupo (1994), “The stochastic measures the location of the
most recent market action in relation to the highest and lowest prices within the
last ” n bars. In this sense, the Stochastic is a momentum indicator: It answers
the question of whether the market is moving to new highs or new lows or is just
meandering in the middle.
The Stochastic is actually several related indicators: Fast %K, Slow %K
(also known as Fast %D), and Slow %D. Fast %K measures, as a percentage, the
location of the most recent closing price relative to the highest high and lowest low
of the last II bars, where n is the length or period set for the indicator. Slow %K,
which is identical to Fast %D, applies a 3-bar (or 3-day) moving average to both
the numerator and denominator when computing the %K value. Slow %%J is sim-
ply a 3-bar simple moving average of Slow %K; it is occasionally treated as a sig-
nal line in the same way that the moving average of the MACD is used as a signal
line for the MACD.
There have been many variations on the Stochastic reported over the years;
e.g., Blau (1993) discussed a double-smoothing variation. The equations for the
classical Lane™s Stochastic are described in an article by Meibahr (1992). A ver-
sion of those equations appears below:
A(i) = Highest of H(i), H(i - l), H(i - n + 1)
B(i) = Lowest of .5(i), L(i - l), L(i - n + 1)
D(i) = [A(i) + A(i - 1) + A(i - 2)] / 3
E(i) = [B(i) + B(i - 1) + B(i -2)] / 3
F(i) = [C(i) + C(i - 1) + C(i - 2)] ! 3
Fast %K for ith bar = 100 * [C(i) - B(i)] / [A(i) - B(i)]
Slow %K = Fast %D = 100 * [F(i) - E(i)] I [D(i) - E(i)]
Slow %D = 3.bar simple moving average of Slow %K
In these equations, i represents the bar index, H(i) the high of the ith bar, L(i) the
low of the ith bar, and C(i) the close of the ith bar. All other letters refer to derived
data series needed to compute the various Stochastic oscillators. As can be seen
from the equations, the Stochastic oscillators highlight the relative position of the
close in a range set by recent market highs and lows: High numbers (a maximum
of 100) result when the close is near the top of the range of recent price activity
and low numbers (a minimum of 0) when the close is near the bottom of the range.
The Relative Strength Index, or RX is another well-known oscillator that
assesses relative movement up or down, and scales its output to a fixed range, 0 to
100. The classic RSI makes use of what is essentially an exponential moving aver-
age, separately computed for both up movement and down movement, with the
result being up movement as a percentage of total movement. One variation is to
use simple moving averages when computing the up and down movement com-
ponents. The equations for the classic RSI appear below:
C/(i) = Highest of 0, C(i) - C(i - 1)
D(i) = Highest of 0, C(i - 1) - C(i)
AU(i) = [(n - 1) * AU(i - 1) + U(i)] / n
AD(i) = [(n - 1) * AD(i - I) + D(i)] / n
RSl(i) = 100 *AU(i) / [AU(i) + AD(i)]
The indicator™s period is represented by n, upward movement by U, downward
movement by D, average upward movement by AU, and average downward move-
ment by AD. The bars are indexed by i. Traditionally, a 1Cbar RSI (n = 14) would
be calculated. A good discussion of the RSI can be found in Star (1993).
Finally, there is the Commodities Channel Index, or Ccl, which is discussed in
an article by Davies (1993). This oscillator is like a more statistically aware
Stochastic: Instead of placing the closing price within bands defined by recent highs
and lows, the CC1 evaluates the closing price in relation to bands delined by the mean
and mean deviation of recent price activity. Although not discussed further in this
chapter, the equations for this oscillator are presented below for interested readers:
136




X(i) = H(i) + L(i) + C(i)
A(i) = Simple n-bar moving average of X(i)
D(i) = Average of 1X(i - k) - A(i) 1 fork = 0 to n - 1
XI(v) = [X(i) - A(i)] / [0.015 * D(i)]
In the equations for the Commodities Channel Index, X represents the so-called
median price, A the moving average of X, D the mean absolute deviations, II the
period for the indicator, and i the bar index.
Figure 7-l shows a bar chart for the S&P 500. Appearing on the chart are the
three most popular oscillators, along with items normally associated with them,
e.g., signal lines or slower versions of the oscillator. Also drawn on the subgraph
containing the Stochastic are the fixed thresholds of 80 and 20 often used as ref-
erence points. For the RSI, similar thresholds of 70 and 30, traditional numbers for
that oscillator, are shown. This figure illustrates how these three oscillators appear,
how they respond to prices, and what divergence (a concept discussed below)
looks like.

GENERATING ENTRIES WITH OSCILLATORS
There are many ways to generate entry signals using oscillators. In this chapter,
three are discussed.
One popular means of generating entry signals is to treat the oscillator as an
overbought/oversold indicator. A buy is signaled when the oscillator moves below
some threshold, into oversold territory, and then crosses back above that threshold.
A sell is signaled when the oscillator moves above another threshold, into over-
bought territory, and then crosses below that threshold. There are traditional
thresholds that can used for the various oscillators.
A second way oscillators are sometimes used to generate signals is with a
so-called signal line, which is usually a moving average of the oscillator.
Signals to take long or short positions are issued when the oscillator crosses
above or below (respectively) the signal line. The trader can use these signals
on their own in a reversal system or make use of additional, independent exit
rules.
Another common approach is to look for price/oscillator divergences, as
described by McWhorter (1994). Divergence is when prices form a lower low
while the oscillator forms a higher low (suggesting a buy), or when prices form a
higher high while the oscillator forms a lower high (suggesting a loss of momen-
tum and a possible sell). Divergence is sometimes easy to see subjectively, but
almost always difficult to detect accurately using simple roles in a program.
Generating signals mechanically for a divergence model requires algorithmic pat-
tern recognition, making the correct implementation of such models rather com-
plex and, therefore, difficult to test. Generating such signals can be done, however;
FIGURE 7-1

Examples of Oscillators and Price-Oscillator Divergence




a good example is the “Divergengine” software distributed by Ruggiero
Associates. An example of divergence appears in Figure 7- 1.
There are a number of issues to consider when using oscillators to generate
entries, e.g., smoothing of data and timeliness of entry. The MACD, for example,
can sometimes provide the smoothing of a moving average with the timeliness of
raw prices. The combination of timeliness and good smoothing may yield entries
that are more profitable than those obtained when using moving average entry mod-
els. The peaks and valleys in a moving average come significantly after the corre-
sponding peaks and valleys in prices. Consequently, entries generated by looking for
these peaks and valleys, or ˜Yarning points,” are excruciatingly late. Conversely,
when cyclic activity in the market has a periodicity that matches the particular
MACD used, the peaks and valleys in the output from the MACD come at roughly
the same time as the peaks and valleys in the prices; the smoothing of a moving aver-
age is achieved without the lag of a moving average, Because the MACD smooths
the data, numerous noise-induced trades will be eliminated, as happens with moving
averages. Because the MACD can be timely, trades generated may be profitable.
In addition to the MACD, many other oscillators tend to move concurrently
with prices or even lead them. For reasons to be discussed later, leading or coincident
indicators do not necessarily generate more profitable entries than such lagging indi-
cators as moving averages. Having coincident indicators does not necessarily mean
highly profitable signals. The problem is that even though some signals will occur
with precise timing, many spurious signals can result, especially in the context of
developing trends. When strong trends are present, the anticipated or coincident
reversals may simply never take place, leading to entries in the wrong direction.
Timeliness may be gained, but reliability may be lost. The question of which trade-
off provides a more profitable model-getting in reliably but late, or on time but unre-
liably-is a matter for empirical study. Such issues are present with any entry method
or pattern detection or forecasting model: The greater the delay, the more accurate
(but less useful) the detection or indication; the lesser the delay, or the further ahead
a™forecast must be made, the less accurate (but more useful) the detection or indica-
tion, The logic is not unlike that of the Heisenbetg Uncertainty Principle.
As an example of how oscillators may be used to generate entries, consider the
Stochastic: A simple entry model might buy when this indicator drops below the tra-
ditional oversold threshold of 20 and then rises above that threshold. It might sell
when the indicator goes beyond the traditional overbought threshold of 80 and then
drops back under. The trader must not wait for another signal to close out the current
position, as one might do when using a moving average crossover; such a signal
might not occur for a long time, so an independent exit is essential. Traders also look
for the so-called Stochastic hook, a pattern in which the Stochastic reaches a tirst low,
moves up a little, and then reaches a second low at a higher level than the first. A buy
signal is generated as soon as the second low becomes detined. A sell is generated
with the exact same pattern flipped over; i.e., a lower high follows a higher high.
As in the case of breakouts and moving averages, oscillator-generated entries
can be effected using any of several orders, such as a market at open, limit, or stop.
The advantages and disadvantages of these orders have been discussed thorough-
ly in the previous two chapters.

CHARACTERISTICS OF OSCILLATOR ENTRIES
Oscillator-based entries have the positive characteristic of leading or being coin-
cident with price activity; therefore, they lend themselves to countertrend entries
and have the potential to provide a high percentage of winning trades. Oscillators
tend to do best in cycling or nontrending (trading range) markets. When they work,
oscillators have the appeal of getting the trader in the market close to the bottom
or top, before a move has really begun. For trades that work out this way, slippage
is low or even negative, good fills are easily obtained, and the trade turns profitable
with very little adverse excursion. In such cases it becomes easy to capture a good
chunk of the move, even with a suboptimal exit strategy. It is said that the markets
trend only about 30% of the time. Our experience suggests that many markets
trend even less frequently. With appropriate filtering to prevent taking oscillator-
based signals during strong trends, a great entry model could probably be devel-
oped. The kind of filtering is exactly the opposite of what was sought when test-
ing breakout systems, where it was necessary to detect the presence, rather than
the absence, of trends.
The primary weakness of simple oscillator-based entries is that they perform
poorly in sustained trends, often giving many false reversal signals. Some oscilla-
tors can easily become stuck at one of their extremes; it is not uncommon to see
the Stochastic, for instance, pegged near 100 for a long period of time in the course
of a significant market movement. Finally, most oscillator entry models do not
capture trends, unlike moving averages or breakouts, which are virtually guaran-
teed to capture any meaningful trend that comes along. Many traders say that “the
trend is your friend,” that most money is made going after the “big wave,” and that
the profits earned on such trends can make up for the frequent smaller losses of
trend-following systems. Because oscillator entries go after smaller, countertrend
moves, it is essential to have a good exit strategy to minimize the damage that will
occur when a trend goes against the trades.


TEST METHODOLOGY
All the tests that follow were performed using oscillator entries to trade a diversi-
fied portfolio of commodities, Can oscillator entry models result in profitable
trades? How have they fared over time-have they become more or less profitable
in recent years? These questions will be addressed below.
The exits are the standard ones, used throughout this book in the study of
entry models. Entry rules are discussed along with the model code and under the
individual tests. Trades were closed out either when an entry in the opposing direc-
tion took place or when the standard exit closed the trade, whichever came first.
The test platform is also standard.
Over the years, we have coded into C+ + the various oscillators described in
articles from Technical Analysis of Stocks and Commodities and from other sources.
When writing this chapter, we compared the output from our C+ + implementations
of the classic MACD, Stochastic, and RSI oscillators with (when available) equiva-
lent oscillators in TradeStation. In most cases, there was perfect agreement of the
results. However, for one of the Stochastics, the results were extremely different,
specifically for Slow %K. Examining the code revealed that TradeStation was com-
puting Slow %K by taking an exponential moving average of Fast %K. Our code,
however, computes the 3-bar simple moving averages of both the numerator and the
denominator (from which Fast %K would have been computed) to obtain Slow %K.
According to the equations in Meibahr™s (1992) article, and in other sources we have
encountered over the years, our C+ + implementation is the correct one. If the read-
er attempts to replicate some of our work in TradeStation and finds discrepancies,
we strongly suggest checking the indicator functions of TradeStation. In addition,
when attempting to code a correct implementation for Slow %K in TradeStation™s
Easy Language, we ran into problems: It appears that TradeStation can give inaccu-
rate results, without any warning, when one user function calls another. When we
modified our code so intermediate variables were computed (thus avoiding the need
to have nested calls), correct results were obtained. The version of TradeStation used
for those tests was 4.02, dating from July 29, 1996.
The following code implements most of the oscillator-based entry models
that underlie the tests. The actual computation of the oscillators is handled by calls
to external functions.
static “Oid MD&l (float *parms. float l dt, float *opn, float ˜hi,
float *lo, float ˜˜1s. float *vol, float *oi, float +dlrv, int nb,
TRDSIM &tS. float *q&31 {

// Implements the oscillator-based entry models to be tested
,, File = XllmodOl.c
vector II. .MAxPRM, Of parameters
/I wrm=
vector L1. .nbl of dates in WMMDD form
/I dt
“ector [I. .nbl Of opening prices
/I opn
vector II. .rlbl Of high pricea
I/ hi
- vector Ll. .*I Of low prices
// 10
vector [I. .nbl Of closing prices
// ClS
vector 11. .nhl Of volumes
/I vol
vector [I. .x-lb1 Of open interest numbers
/I oi
/I arv vector Cl. .nhl of average dollar volatilities
number Of bars in data series or vectors
// nb
trading simulator class instance
// C6
vector Cl. .*I of closing equity levels
I/ eqc1s

,, declare local GCracCh variables
static int rc, cb, ncontract.9, maxhold, lenl, len2, len3;
static int modeltype, ordertype, osctype. signal, i, j, k;
static float mmatp, ptlim. stpprice, limprice, tmp;
static float exitatr [MAxBAR+ ;
static float sigline mAxBAR+ , oscline wAxBAR+ i
static float upperbandMAXBAR+ll , lowerbandWhXBAR+11 ;
CHAPTER 7 Oscillator-Based Entries




The logic of the code is very similar to the code used to test moving aver-
ages. First, a number of parameters are copied to local variables to make them eas-
ier to understand and refer to in the code that follows. A check is then made for
invalid combinations of parameters; e.g., for the MACD (o&ype = 4), the length
of the shorter moving average must be less than the longer moving average; oth-
erwise the test is skipped. In the next large block of code, osctype selects the type
of oscillator that will be computed (1 = fast Stochastics, 2 = slow Stochastics, 3
= classic RSI, 4 = classic MACD). The oscillator (oscline) is then computed as a
data series or vector; any additional curves associated with it, such as a signal line
(s&dine) or slower version of the oscillator, are generated; and upper (upperband)
144




and lower (lowerband) thresholds are either set or computed. For the Stochastics,
the standard thresholds of 80 and 20 are used. For the RX, 70 and 30 are speci-
tied (also standard). Although the MACD normally has no thresholds, thresholds
placed 1.5 mean deviations above and below zero. Finally, the process of stepping
through the data, bar by bar, is begun.
Two main blocks of code are of interest in the loop for stepping through the
data. The first block generates a buy or sell signal, as well as limit and stop prices
for the specified, oscillator-based entry model. The mod&p parameter selects
the model to use: I = overbought/oversold model, 2 = signal line model, and 3 =
divergence model. The oscillator used by the model to generate the buy and sell
signals is the one computed earlier, as selected by osctype. The final block of code
enters trades using the specified order type. The parameter ordertype determines
the order used: 1 = entry at open, 2 = entry on limit, and 3 = entry on stop.
Finally, the simulator is instructed to use the standard exit model to close out any
open trades.
The exact logic used for entering the market is discussed in the context of the
individual tests below without requiring the reader to refer to or understand the code.

TESTS RESULTS
Tests were performed on three oscillator entry models: Overbought/oversold
(Stochastic and RSI used), signal line (Stochastic and MACD used), and diver-
gence (Stochastic, RX, and MACD used). All individual model-oscillator comhi-
nations were examined with entry at the open, on a limit, and on a stop. The results
for all three orders are discussed together.
Tables 7-l and 7-2 contain, for each of the 21 tests, the specific commodities
the model traded profitably and those that lost in-sample (Table 7-1) and out-of-
sample (Table 7-2). The SYM column represents the market being studied, the first
row identifies the test number. The tables show which markets were, and were not,
profitable when traded by each model: One dash (-) indicates a $2,000 to $4,000
loss per trade: two dashes (- -), a $4,000 or more loss; one plus sign (+) means a
$1,000 to $2,000 profit; two pluses (+ +), a $2,000 or more profit; a blank cell
means a $0 to $1,999 loss or a $0 to $1,000 profit.

TESTS OF OVERBOUGHT/OVERSOLD MODELS
The entries were generated when the oscillator crossed below an upper threshold
or above a lower one. These are countertrend models: The trader buys when the
oscillator shows downward momentum in prices and sells when the oscillator
depicts recent positive momentum. In Tests 1 through 6, the Stochastic and the
RSI were considered since these indicators have traditional thresholds associated
with them and are often used as described above.
TABLE 7-1

In-Sample Performance Broken Down by Test and Market




Tests I through 3: Stochastic Overbought/Oversold Models. These tests
evaluate the model with entry at the open (Test l), on a limit (Test 2), and on a
stop (Test 3). Lane™s original Fast %K was used. The length was stepped from
5 to 25 in increments of 1. The best values for this parameter in-sample were
25, 20, and 16 (Tests 1 through 3, respectively). For the Stochastic, the tradi-
tional thresholds are 20 (lower) and 80 (upper). As a whole, these models lost
heavily in- and out-of-sample (see Table 7-3). As in previous tests, the limit
7-2
TABLE

Out-of-Sample Performance Broken Down by Test and Market




order was the best in both samples, having the least loss per trade; the percent
of winning trades (37% in-sample, 36% out-of-sample) was also highest with
this order. The stop order was intermediate in performance, with the entry at
open being the worst. No markets traded well in either sample. Out-of-sample,
the British Pound and Orange Juice were profitable across all orders, and
Lumber, Soybeans, and Live Hogs made profits with a stop; other small profits
were occasionally noted, hut had no consistency. This model is among the
worst tested.
Tests 4 through 6: RSI Overbought/Oversold Models. The model was tested
with entry at the open (Test 4) on a limit (Test 5), and on a stop (Test 6). The
RSI was computed as suggested by its originator, Larry Williams. The length
was stepped from 5 to 2.5 in increments of 1. Across all tests, 25 was the best
value for this parameter in-sample. The traditional thresholds were used: 30
(lower) and 70 (upper). The model performed more poorly than the Stochastic
overbought/oversold one. The percentage of winning trades was extremely low,
ranging from 26% to 37%, depending on sample and test. The average loss per
trade reached over $7,000. Net profits were better than for the Stochastic
because there were fewer trades; even though the loss per trade was greater, the
total loss was smaller. This model did not capture any market inefficiency. The
limit order was best, while the stop and open were about equal. Significantly
more markets showed positive returns, especially in Test 5 when the limit was
used: Profits occurred in-sample for Bonds, COMEX Gold, Silver, Platinum,
Feeder Cattle, Oats, and Coffee; out-of-sample, Gold, Silver, Platinum, Feeder
Cattle, and Oats still traded profitably. Also profitable out-of-sample were the
NYFE, British Pound, Heating Oil, Corn, Sugar, Orange Juice, and Lumber.


Tests of Signal Line Models
These are essentially moving average crossover models, except that an oscillator
is substituted for prices when searching for crossovers. In this case, the moving
average is called the signal line. A short entry is signalled when the oscillator
crosses from above to below the signal line; when the oscillator does the reverse,
a long entry is generated. Since oscillators show less lag than moving averages and
less noise than raw prices, perhaps more timely and reliable signals can be gener-
ated. In Tests 7 through 12, the Stochastic and MACD are considered. The Slow
%K usually exhibits strong cyclic behavior, appropriate for use with a signal line
entry. The MACD is traditionally plotted with the signal line, even if crossovers
are not a traditional entry criteria.

Tests 7 through 9: Stochastic Signal Line Models. The model was tested with
entry at the open, on a limit, and on a stop (Tests 7 through 9, respectively).
Lane™s original Slow %K Stochastic was used because, in preliminary testing,
Fast %K produced an incredible excess of trades, resulting from very high noise
levels and the indicator pegging near its extremes. The signal line consisted of a
3-bar simple moving average of Slow %K. The length of the Stochastic was
stepped from 5 to 25, in increments of 1. The best values for this parameter in-
sample were 15, 14, and 11 (Tests 7 through 9). Overall, these models lost heav-
ily on a per trade basis. Due to the large number of trades, the losses were
astronomical. The limit order was best, showing the least loss per trade and the
highest percent of winning trades across samples. Entry at the open was worst.
This model likes stops, perhaps because they act as trend filters: After coun-
tertrend activity is detected (triggering an entry signal), before entry can occur,
the market must demonstrate reversal by moving in the direction of the trade.
Stops also performed better in countertrend moving average models, Only two
markets had positive returns in-sample, but not out-of-sample. Out-of-sample, the
stop produced a few small profits; Coffee made more than $2,000 per trade.

Tests 10 through 12: MACD Signal Line Models. Entry at the open (Test lo), on
a limit (Test ll), and on a stop (Test 12) were examined. The classic MACD,
employing exponential moving averages, was used. The shorter moving average was
stepped from a length of 3 to a length of 15 in increments of 2; the longer moving
average was stepped from lengths of 10 through 40 in increments of 5. The moving
average serving as the signal line had a fixed traditional period of 9. This was the
best performing oscillator model thus far. In-sample, the limit order was best and
entry at open was worst. Out-of-sample, the stop was best and the limit order worst.
Out-of-sample, the stop produced the highest percentage of wins (40%) seen so far,
and the smallest loss per trade. In-sample, only Lumber was substantially profitable
with a limit. Live Hogs, Pork Bellies, Coffee, and Sugar were profitable in-sample
with a stop. Lumber, Live Hogs, Pork Bellies, and Coffee held up out-of-sample.
Many markets unprofitable in-sample, were profitable out-of-sample. The highest
number of markets traded profitably with a stop.


TESTS OF DIVERGENCE MODELS
Tests 13 through 21 examine divergences with the Stochastic oscillator, the RSI,
and the MACD. Divergence is a concept used by technical traders to describe
something easily perceived on a chart but hard to precisely define and detect algo-
rithmically. Figure 7-l shows examples of divergence. Divergence occurs when,
e.g., the market forms a lower valley, while the oscillator forms a higher valley of
a pair of valleys, indicating a buy condition; selling is the converse. Because wave
forms may be irregular, quantifying divergence is tricky. Although our detection
algorithm is elementary and imperfect, when examining charts it appears to work
well enough to objectively evaluate the usefulness of divergence.
Only buy signals will be discussed; the sells are the exact opposite. The algo-
rithm™s logic is as follows: Over a look-back (in the code, len3), the lowest bar in
the price series and the lowest bar produced by the oscillator are located. Several
conditions are then checked. First, the lowest bar of the price series must have
occurred at least one bar ago (there has to be a definable valley), but within the
past six bars (this valley should be close to the current bar). The lowest bar in the
price series has to occur at least four bars after the lowest bar in the look-back peri-
od for the oscillator line (the deepest valley produced by the oscillator must occur
before the deepest valley produced by the price). Another condition is that the low-
est bar produced by the oscillator line is not the first bar in the look-back period
(again, there has to be a definable bottom). Finally, the oscillator must have just
turned upward (defining the second valley as the signal about to be issued). If all
conditions are met, there is ostensibly a divergence and a buy is posted. If a buy
has not been posted, a similar set of conditions looks for peaks (instead of valleys);
the conditions are adjusted and a sell is posted if the market formed a higher high,
while the oscillator formed a lower high. This logic does a reasonable job of
detecting divergences seen on charts. Other than the entry orders, the only differ-
ence between Tests 13 through 21 is the oscillator being analyzed (in relation to
prices) for the presence of divergence.

Tests 13 through 15: Stochastic Divergence Mode&. Fast %K was used with the
standard entries. Optimization involved stepping the Stochastic length from 5 to 25
in increments of 1 and the divergence look-back from 15 to 25 by 5. The best para-
meters were length and look-back, respectively, 20 and 15 for open, 24 and 15 for
limit, 25 and 15 for stop. This model was among the worst for all orders and in both
samples. In-sample, the limit was marginally best; out-of-sample, the stop. In-Sam-
ple, across all orders, Unleaded Gasoline, Soybeans, and Soybean Meal were prof-
itable; Gold and Pork Bellies were moderately profitable with a limit. Unleaded
Gasoline held up out-of-sample across all orders. Soybeans were profitable out-of-
sample for the open and stop. More markets were profitable out-of-sample than in-
sample, with the stop yielding the most markets with profits. The pattern of more
profitable trading out-of-sample than in-sample is prima facie evidence that opti-
mization played no role in the outcome; instead, in recent years, some markets have
become more tradeable using such models. This may be due to fewer trends and
increased choppiness in many markets.

Tests 16 through 18: RSI Divergence Models. Optimization stepped the RSI period
from 5 to 25 in increments of 1, and the divergence look-back from 15 to 25 by 5.
Overall, the results were poor. h-sample, the stop was lest bad, with the limit close
behind. Out-of-sample, the stop was also best, closely followed by the open. Given that
the RSI has been one of the indicators traditionally favored by traders using diver-
gence, its poor showing in these tests is noteworthy. Heating Oil was profitable for all
orders, Unleaded Gasoline WZY significantly profitable for the open and stop, Light
Crude for the limit and stop. In-sample, Soybeans traded very profitably across orders;
Orange Juice, Corn, Soybean Oil, and Pork Bellies traded well with the stop. Out-of-
sample, the oils were not consistently profitable, while Soybeans remained profitable
across orders; Orange Juice and Soybean Oil still traded profitably with the stop.

Tests 19 through 21: MACD Divergence Mode&. The length of the shorter
moving average was stepped from 3 to 15 in increments of 2; the length of the
longer moving average from 10 to 40 by 5; and the divergence look-back from 15
to 25, also by 5. Only parameter sets where the longer moving average was acta-
ally longer than the shorter one were examined.
PART II The Study of Enwics


Finally, models that appear to work, producing positive returns in both sam-
ples! With entry at open, trades were profitable across samples. In-sample, the
average trade made $1,393; 45% of the trades were winners; and there was only
an 8.7% (uncorrected; 99.9% corrected) probability that the results were due to
chance; both longs and shorts were profitable. Despite poor statistical significance
in-sample, there was profitability out-of-sample: The model pulled $140 per trade
(after commissions and slippage), with 38% winning trades; only shorts were
profitable.
The limit performed slightly worse in-sample, but much better out-of-sam-
ple. Figure 7-2 depicts the equity curve for entry on a limit. In-sample, the aver-
age profit per trade was $1,250 with 47% winning trades (the highest so far); longs
and shorts were profitable; and the probability was 13.1% (uncorrected; 99.9%
corrected) that the results were due to chance. Out-of-sample, the model made
$985 per trade; won 44% of the time: was profitable in long and short positions;
and was only 27.7% likely due to chance.
It-sample, the stop had the greatest dollars-per-trade return, but the smallest
number of trades; only the shorts were profitable. Out-of-sample, the system lost
$589 per trade; only short positions were profitable. Regardless of the order used,
this model had relatively few trades.
The market-by-market analysis (see Tables 7-1 and 7-2) confirms the poten-
tial of these models to make money. The largest number of markets were profitable
in-sample. Across samples, all three orders yielded profits for Light Crude and
Coffee; many other markets had profitability that held up for two of the orders, but
not for the third, e.g., Heating Oil, Live Cattle, Soybeans, Soybean Meal, and
Lumber.

SUMMARY ANALYSES
Table 7-3 provides the results broken down by the model, order, and sample. The
last two colunms on the right, and the last two rows on the bottom, are averages.
The numbers at the right are averaged over order type. The numbers at the bottom
have been averaged over all models.
The best results across samples were for the MACD divergence model. The
limit produced the best combined results in both samples: a 12.5% return (annu-
alized) and $1,250 per trade in-sample, and a 19.5% return (annualized) and $985
per trade out-of-sample. This model is dramatically different from all others.
When considered across all order types and averaged, the overbought/over-
sold models using the RSI were worst (especially in terms of dollars-per-trade).
Also among the worst were the Stochastic divergence, Stochastic overboughtiover-
sold, and RSI divergence models.
When all models were averaged and broken down by order type, the limit
order was best and the entry at open worst.
FIGURE 7-2
.˜-
Equity for MACD Divergence Model with Entry on a Limit




CONCLUSION
With breakouts and moving averages, a limit usually was the best overall performer,
perhaps because it minimizes transaction costs; a stop sometimes improved perfor-
mance, depending on its interaction with the entry model. For some oscillator
entries, including the profitable MACD divergence, a limit was again best. Other
oscillator models preferred the stop, perhaps due to its trend filtering quality.
There was an interaction between specific oscillators and models. The diver-
gence model, for example, worked well with the MACD, but terribly with the RSI.
Such results demonstrate that, when studying a model with an indicator compo-
nent that may be varied without altering the model™s essence, it is important to test
all model-indicator combinations as certain ones may perform dramatically better.

WHAT HAVE WE LEARNED?

In general, for best results, use a limit order. However, test a stop as it
n

sometimes works better.
Performance of Models Broken Down by Model, Order,
Oscillator
and Sample




. When testing a model that can be used with multiple indicators, try sever-
al to see whether any yield distinct improvements.
n Attempt to algorithmically implement concepts normally employed in a

highly variable and subjective manner. Sometimes this can be exception-
ally difficult, requiring fuzzy logic or neural network technology, along
with other specialized methods.
CHAPTER 8


Seasonality




I magmc that tomorrow is June 7, 1997. You need to decide whether or not to
trade. If you do trade, you will enter at the open and exit at the close. You also need
to decide how to enter the market: Should you go long or short? As part of the
decision process, you examine the behavior of the market on all June 7s that
occurred within a look-back window of some number of years (e.g., 10). You tab-
ulate the number of June 7s on which trading occurred, the average open-to-close
change in price, and the percentage of time the market rallied or collapsed.
Perhaps, in the past 10 years, there were eight instances when the market was open
and June 7 was a trading day: of those instances. perhaps the market closed high-
er than it opened six times (75%) and the average change in price was 2.50 (a rea-
sonable figure for the S&P 500). On the basis of this information, you place a
trading order to enter long tomorrow at the open and to exit at the close. Tomorrow
evening you repeat the procedure for June 8, the evening after that for June 9, and
so on. This is one form of seasonal trading. Will you make a profit trading this
way? Will your trading at least be better than chance? These are the questions that
arise when discussing seasonal trading and that this chapter attempts to answer.

WHAT IS SEASONALITY?
The term seasondity is used in many different ways by traders. Some construe
seasonality as events that are strictly related the four seasons, e.g., the increased
demand for heating oil in the winter or gasoline in the summer. Others have a more
liberal interpretation that includes weather patterns and election cycles.
Over the years, a number of articles in academic journals have demonstrated
that stocks show larger returns around the first of each month. There has been some
discussion of the so-called January Effect, in which stocks tend to rise in January.
Hannula (1991) used seasonal cycles in his own trading, providing as an example
a chart for EXABYTE stock with strong seasonal patterns marked. He also dis-
cussed another phenomenon, sometimes observed with seasonal patterns, in which
the highs and lows occasionally invert, a pattern that we also have witnessed and
that may be worth exploring. Other factors that influence various markets have def-
inite dates of occurrence and so should induce seasonal effects; e.g., the dates for
filing taxes occur at the same time every year. The legendary trader, Gann, appar-
ently made heavy use of recurrent yearly behavior in his trading. Bernstein™s (1995)
home-study course on seasonality suggests trading off significant tops and bottoms,
and when there has been consistent movement in a tradable over a number of years;
this approach, as well as Hannula™s, may tend to involve trades lasting several
weeks to several months.
In 1990, we first published the Calendar Effects Chart, a set of tables and a
chart that show date-specific behavior in the S&P 500 cash index. The chart illus-
trates a general up-trend from January through September, and then an up and
down decline until October 24. The market then, on average, bottoms, after which
time it steeply rises until the end of the year. On a more detailed level, rapid gains
seem to occur throughout most of January, the first half of April, and the first half
of June. A peak can be seen on October 8, and a very steep decline that leads to a
bottom on October 24. When the tables and chart for this publication were gener-
ated, extreme movements were clipped at +2 percent to prevent them from having
undue influence on the results. Consequently, the steep decline in October, and the
other patterns mentioned, cannot be attributed to events in specific years, for
instance, the crash in 1987. For some dates, there were incredibly consistent pat-
terns; e.g., if an entry occurred on the close of April 14 and the trade was exited
one day later, over 90% of the time a small profit would have been made. Entry on
May 6, with exit one day later, resulted in a profit 100% of the time, as did entry
on July 13. The market declined 90% of the time from October 18 to 19, and 89%
of the time from October 16 to 17. Although the crash may have involved a much
greater than normal amount of movement, the presence of a decline at the time
when the crash occurred was not at all unexpected. In an attempt to capture high-
probability, short-term movements, the Calendar Effects Chart could have been
used to enter trades that last one or two days. For example, such a methodology
would have caused a trader to go short at the close on October 16 and exit on
October 19, thus capturing the crash. The data contained in this publication could
also have been used to help maintain positions during periods of steep ascent or
decline.
There have been other studies indicating the presence of strong seasonal effects
in the market that can be exploited for profitable trading. An investigation we con-
ducted (Katz and McCormick, April 1997) found that short-term seasonal behavior
could be used to trade the S&P 500: The system used fairly fast moving average
crossovers that were computed on seasonally anticipated prices. Because the antici-
pated prices could be computed at least one year ahead, lag in the moving average
crossover was easily compensated for with a displacement that enabled the system
to take trades at crossovers occurring several days after the fact. The trades taken by
the system typically lasted between 7 and 8 days, a fairly short-term seasonal trad-
ing model. The system was profitable: It pulled an astonishing $329,900 from the
S&P 500 between January 3.1986, and November 8, 1996. The test did not include
transaction costs, but even with $15 round-turn commissions and $75 per trade slip-
page, a profit of $298,310 (about a 10% reduction) resulted. The return on account
was 732%, not annualized; assuming fixed contract trading, this amounted to over
70% per year, annualized, on a constant one-contract, no-reinvestment basis. There
were 351 trades taken, of which 60% were winners. Both the longs and shorts were
profitable. The average trade pulled $939 from the market-not bad for a simple,
seasonality-based trading model, Findings like these suggest there are strong sea-
sonal patterns in the markets producing inefficiencies that can be exploited by
traders, and that are worthy of investigation.
For our current purposes, seasonaliry is defined as cyclic or recurrent phe-
nomena that are consistently linked to the calendar. The term is being used in a
broad sense to mean market behavior related to the time of the year or to particular
dates, including anniversaries of critical events (e.g., the October 16, 1987, crash).
In short, seasonality is being construed as calendar-related cyclic phenomena. It
should be made clear, however, that while all seasonality is cyclic, not all cycles are
seasonal.

GENERATING SEASONAL ENTRIES
There are many ways to time entries using seasonal rhythms. Two basic approaches
will be examined: momentum and crossover. To calculate momentum, a series of
price changes is computed and centered smoothing (a smoothing that induces no
delays or phase shifts, in this case, a centered triangular moving average) is applied.
Each price change (or difference) in the series of price changes is then normalized:
It is divided by the 50.day average true range. For every bar, the date is determined.
Instances of the same date are then found in the past (or perhaps future). For each
such instance, the momentum is examined. The average of the momentums becomes
the value placed in the seasonal momentum series for the current bar. The seasonal
momentum series measures the expected rate of change (or momentum) in prices at
a given time. It is based on the historical movement of prices on the specified date
in different years. The number in the seasonal momentum series for the current bar
is determined only by events about 1 year or more ago. This is why it is possible to
use the centered moving average and other techniques that look ahead in time, rela-
tive to the bar bei˜ng considered. Entries are taken as follows: When the seasonal
momentum crosses above some positive threshold, a buy is posted. When the
156




momentum crosses below some negative threshold, a sell is posted. Buying or sell-
ing can happen on any of the standard three orders: at open, on limit, or on stop.
Entries may also be generated by computing the price differences, normalizing
them, applying an integration or summing procedure to the series (to obtain a kind
of pseudo-price series, based on previous instances of each date), and then applying
a moving average crossover model to the series. Because the value at any bar in the
series is determined only by bars that are about 1 year old or older, the delay in the
crossovers can be compensated for by simply looking ahead a small number of bars.
Both of the methods described above arc somewhat adaprive in nature; i.e.,
they do not require specific information about which dates a buy or sell order
should be placed. The adaptive quality of the aforementioned methods is impor-
tant since different markets respond to seasonal influences in different ways, a fact
that logic, as well as our earlier research, supports.
In the current study, several rules for handling confirmations and inversions
are also tested to determine whether better results can be obtained over the basic
models. Confirmarion means additional data is available that supports the signals
produced by the model. For example, suppose a model generated a buy signal
for a given bar. If everything is behaving as it should, the market should be form-
ing a bottom around the time of the buy. If, however, the market is forming a top,
the buy signal might be suspect, in that the market may not be adhering to its typ-
ical seasonal timing. When such apparently contradictory circumstances exist, it
would be helpful to have additional criteria to use in deciding whether to act upon
the signal, in determining if it is correct. The crossover-with-con˜rmation model
implements the crossover model with an additional rule that must be satisfied
before the signal to buy or sell can be acted upon: If a buy signal is issued, the
Slow %K on the signal bar must be less than 25%, meaning the market is at or near
the bottom of its recent range. If a sell signal is issued, Slow %K must be greater
than 75%, indicating that the market is at or near the top of its range, as would be
expected if following its characteristic seasonal behavior. The conjinnation-und-
inversion model adds yet another element: If a buy signal is issued by the basic
model, and the market is near the top of its range (Slow %K greater than 75%),
then it is assumed that an inversion has occurred and, instead of issuing a buy sig-
nal, a sell signal is posted. If a sell signal is generated, but the market is near the
bottom of its range (Slow %K less than 25%), a buy signal is issued.

CHARACTERISTICS OF SEASONAL ENTRIES
Consider trading a simple moving average crossover system. Such a system is
usually good at capturing trends, but it lags the market and experiences frequent
whipsaws. If slower moving averages are used, the whipsaws can be avoided,
but the lag is made worse. Now add seasonality to the equation, The trend-fol-
lowing moving average system is applied, not to a series of prices, but to a
series that captures the seasonal ebb and flow of the market. Then compute the
seasonal series so it represents that ebb and flow, as it will be several days from
now-just far enough ahead to cancel out the annoying lag! The result: A sys-
tem without lag (despite the use of slow, smooth, moving averages) that follows
seasonal trends. The ability to remove lag in this way stems from one of the
characteristics of seasonality: Seasonal patterns can be estimated far in
advance. In other words, seasonality-based models are predictive, as opposed
to merely responsive.
Since seasonality-based models are predictive, and allow turning points to be
identified before their occurrence, seasonal-based trading lends itself to coun-
tertrend trading styles. Moreover, because predictions can be made far in advance,
very high quality smoothing can be applied. Therefore, the kind of whipsaw trad-
ing encountered in responsive models is reduced or eliminated. Another nice char-
acteristic of seasonality is the ability to know days, weeks, months, or even years
in advance when trades will occur--certainly a convenience.
Seasonality also has a downside. The degree to which any given market may
be predicted using a seasonal model may be poor. Although there may be few
whipsaws, the typical trade may not be very profitable or likely to win. If inver-
sions do occur, but the trading model being used was not designed to take them
into account, sharp losses could be experienced because the trader could end up
going short at an exact bottom, or long at an exact top.
The extent to which seasonal models are predictive and useful and the pos-
sibility that inversion phenomena do exist and need to be considered are questions
for empirical study.


ORDERS USED TO EFFECT SEASONAL ENTRIES
Entries based on seasonality may be effected in at least three ways: with stops,
limits, or market orders. While a particular entry option may work especially well
with a particular model, any entry may be used with any model.
Entry orders themselves have their own advantages and disadvantages. The
advantage of a market or&r is that no signaled entry will be missed. Stop orders
ensure that no significant trends (in a trend-following model) will elude the trader,
and that entry will not occur without confirmation by movement in favor of the
trade (possibly beneficial in some countertrend models). The disadvantages are
greater slippage and less favorable entry prices, A limit order gets the trader the
best price and minimizes transaction costs. However, important trends may be
missed while waiting indefinitely for a retracement to the limit price. In coun-
tertrend models, a limit order may occasionally worsen the entry price. The entry
order may be tilled at the limit price, rather than at a price determined by the neg-
ative slippage that sometimes occurs when the market is moving against the trade
at the time of entry!
158




TEST METHODOLOGY
The data sample used throughout the tests of seasonal entry methods extends from
August 1, 1985, to December 31, 1994 (the in-sample period), and from January
1, 1995, through February 1, 1999 (the out-of-sample period). For seasonality
studies, an in-sample period of only 10 years means there is a shortage of data on
which to develop the model. When generating seasonal entries was discussed,
mention was made about calculating seasonal momentum (or average price behav-
ior) based on equivalent dates in previous years. Because of the data shortage,
when considering the in-sample data, calculations will be based not only on past
years, but also on future years. This is accomplished using fhe “jackknife.”
Target dates are run throughout the series, bar after bar. If only past years are
included, for the early data points, there are very few past years or none at all.
Since it takes at least 6 years of past data to get a reasonable seasonal average,
there would be no seasonality calculations for most of the in-sample period, which
itself is only 10 years. Consequently, there is very little data on which to optimize
essential parameters or determine how seasonal models perform on the in-sample
data. The jackknife, a well-known statistical technique (also known as the “leave-
one-out method”), helps solve the data shortage problem
Suppose a seasonality estimate for June 1, 1987, is being calculated. If
only past data from the in-sample period is used, the estimate would be based on
data from 1986 and 1985. If, however, the jackknife is applied, not only would
data from the past be available, but so would data from the “future,” i.e., the
other years of the in-sample period (1988 through 1994). If the year (1987) that
serves as the target bar for the calculations is removed from the in-sample period,
the seasonality estimate for that bar would now be based on 9 years of data, a
reasonably adequate sample. The jackknife procedure is justified because the
data being examined to make the prediction is fairly independent of the data
actually being predicted by the seasonality estimate. Since the data used in gen-
erating the prediction is at least 1 year away from the target date, it is not con-
taminated with current market behavior. The process™provides an effectively
larger sample than could otherwise be obtained, and does so without seriously
compromising the available number of degrees of freedom.
For bars in the out-of-sample period, all past years are used to generate the sea-
sonal&y estimates. For example, to calculate the seasonality for January 14, 1999,
the &past-years technique is used: Data from 1998 all the way back to 1985 are
included in the analysis. In this way, no calculation for the out-of-sample period is
ever based on any future or current data.
All the tests that follow are performed using seasonal entries to trade a diversi-
fied portfolio of commodities. The exits are the standard ones, used throughout this
book to study entry models. Trades are closed out either when an entry in the oppos-
ing direction occurs or when the standard exit closes the trade, whichever comes first.
The test platform is also standard. Here is the code for the seasonal trading tests:
CHAFlER 8 Scasonality 159
160
162



/I cro88ove* avg
MovAvglma2,mal,matype,aVglen,nb) ;
// stochastic osc
if(modeltype == 3 11 modeltype == 4)
s-bar m*t %K
StochOac(stoch,hi,lo,cls,1,9,nb); //
break;
default: nrerrorl"TRAPSMOD: invalid modeltype"1;
)
/I step through bare (days) to simulate actual trading
forlcb = 1; cb L- nb; cb++) (

// take no trades before the in-sample period
// ,.. same aa Tradestation's MaxBarsBack setting
if(dt[cbl < IS-DATE) ( eqcls[cb] = 0.0; continue; )

/f execute any pending orders and save closing equity
rc 3 ts.updaee,opnIcbl, bilcbl, loIcbl. clelcbl, cb);
if(rc I= 0) nrerror("Trade buffer overflow");
eqcls[cbl = te.curr.nte˜ify(EQ_CLOSETOTAL);




// avoid placing orders on possibly limit-locked days
if(hi[cb+ll == lo[cb+ll) continue;

/! generate entry aignala, stop prices and limit prices
// for all seasonality-based entry models
signal - 0;
switchtmodeltype) (
case 1: // basic thresholded momentum entry model
k = cb + disp;
tmp = thresh * mallkl;
ifleavglk] 5 tmp &(r savglk-11 c= tmp)
signal = 1;
else if(savg[kl < -tmp &h aavglk-II >= -tmp)
signal * -1;
break;
case 2: // basic crossover entry model
k - cb + disp;
} // process next bar

I
164




After declaring local variables and arrays, the first major block of code
copies various parameters to local variables for more convenient and understand-
able reference. The parameters are described in comments in this block of code.
The next block of code performs all computations that are carried out on

<<

. 4
( 9)



>>