<< . .

. 14
( : 30)

. . >>

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)

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 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.

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.

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

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 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
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

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.
Equity for MACD Divergence Model with Entry on a Limit

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.


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

sometimes works better.
Performance of Models Broken Down by Model, Order,
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.


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.

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

<< . .

. 14
( : 30)

. . >>