Professional Documents
Culture Documents
2023APR
2023APR
REPATRIATION
Using the flow of foreign
investment money 14
MINING PATENT
DOCUMENTS
Looking for trading ideas 18
INTERVIEW
John F. Ehlers 28
APRIL 2023
Subscribe Or Renew Today!
A subscription to Technical Analysis of Stocks & Commodities magazine
gets you so much more than just a magazine:
8999
1 year.........................
$
2 years.................... 149
$ 99
3 years.................... 199
$ 99
Best Standalone
Analytical Software
in it’s price category
1993-2023
We can.
This is neither a solicitation to buy or sell any type of financial instruments, nor intended as investment recommendations. All investment trading involves multiple substantial risks of monetary loss. Don’t
trade with money you can’t afford to lose. Trading is not suitable for everyone. Past performance, whether indicated by actual or hypothetical results or testimonials are no guarantee of future performance
or success. NO REPRESENTATION IS BEING MADE THAT ANY ACCOUNT WILL OR IS LIKELY TO ACHIEVE PROFITS OR LOSSES SIMILAR TO THOSE SHOWN. IN FACT, THERE ARE FREQUENTLY SHARP DIFFERENCES
BETWEEN HYPOTHETICAL PERFORMANCE RESULTS OR TESTIMONIALS AND THE ACTUAL RESULTS SUBSEQUENTLY ACHIEVED BY ANY PARTICULAR TRADING PROGRAM. Furthermore, all internal and external
computer and software systems are not fail-safe. Have contingency plans in place for such occasions. MetaStock assumes no responsibility for errors, inaccuracies, or omissions in these materials, nor shall
it be liable for any special, indirect, incidental, or consequential damages, including without limitation losses, lost revenue, or lost profits, that may result from reliance upon the information presented.
CONTENTS APRIL 2023, VOLUME 41 NUMBER 5
Copyright © 2023 Technical Analysis, Inc. All rights reserved. Information in this publication must not be stored or reproduced in any form without written permission from the publisher. Technical Analysis of Stocks & Commodities™
(ISSN 0738–3355) is published monthly with a Bonus Issue in March for $89.99 per year by Technical Analysis, Inc., 4757 California Ave. S.W., Seattle, WA 98116–4499. Periodicals postage paid at Seattle, WA and at additional mailing
offices. Postmaster: Send address changes to Technical Analysis of Stocks & Commodities™ 4757 California Ave. S.W., Seattle, WA 98116–4499 U.S.A. Printed in the U.S.A.
ibkr.com/sc-trader
IRON CONDORS If you trade options close to the price it will expire in the money. While
What exactly is an iron condor? of the underlying, you can take in a this is not mathematically correct, it
An iron condor involves selling an lot of option premium, however, the does provide a reasonable estimate.
out-of-the-money call and put and odds are generally very high that the So a call option with a delta of 15 is
simultaneously buying another call underlying will move outside your thought to have a 15% probability
at a higher strike price and buying profit range. On the other hand, if you of expiring in-the-money (which is
another put at a lower strike price. trade options that are extremely far- bad for the option seller) and an 85%
The idea is to create a “profit range.” out-of-the-money, you have a higher probability of expiring out-of-the-
As long the underlying security price probability of the options expiring money (i.e., worthless).
remains within the profit range, the worthless, but your returns can be
trade will make money. In a perfect microscopic. Which expiration to use?
world, the underlying security stays Here too, we must consider the
within the profit range, all options An iron condor involves tradeoff. Selling longer-term options
expire worthless, and the trader keeps “selling premium,” and offer the potential to take in more
all the premium received when the option premium, however, they also
trade was entered.
the maximum profit is give the underlying security more
In choosing and trading an iron equal to the premium time to move out of the profit range.
condor, there are a variety of im- received when the In addition, the bulk of option time
portant factors to consider. Gener- trade is entered. decay occurs in the 30 days leading
ally speaking, they can be boiled up to expiration. If we go too far out
down to: While I’ve already stated that in time, we will have to wait a long
there are no correct answers, for the time before time decay really begins
• Which strike prices to trade? purposes of this piece, I am going to work in our favor.
• Which expiration to use? to lay out some example guidelines So, we will look for options with 15
• What to do if the underlying as follows: to 45 days left until expiration.
moves too far?
• Sell a call option with a delta of 15 Other factors to
The reality is that there are no or less and sell a put option with consider
“correct” answers to these questions. a delta of −15 or higher An iron condor involves “selling
The key is that your answers to • Buy a call option with a delta premium,” and the maximum profit
these questions comport with your between 5 and 10 and buy a put is equal to the premium received
own objectives regarding risk and option with a delta between −10 when the trade is entered. The higher
reward. and −5 implied option volatility is for the
underlying security, the more time
Which strike price to There is nothing magic about these premium there is built into the op-
trade? values. They are chosen to try to put tions, thus the higher the profit poten-
Ideally, you want the best tradeoff the odds of success in our favor. In tial. One word of caution, though. If
between potential return and the this case, we are looking at an options we limit our search only to securities
probability of achieving that return. delta as roughly the probability that presently trading at extremely high
6 • April 2023 • Technical Analysis of Stocks & Commodities
Explore Your Options
OPTIONSANALYSIS.COM
FIGURE 1: TRADE PARTICULARS, IRON CONDOR EXAMPLE. Iron condors involve selling an out-of-the-money call and put while simultaneously buying
another call at a higher strike price and buying another put at a lower strike price.
IV levels, we will
typically focus on
stocks making large
price swings (which
is causing the high
IV in the first place).
This is not what we
want when selling
an iron condor. So,
regarding IV, sim-
ply make sure that
IV is not at rock bot-
tom levels and that
there is some worth-
while premium to
be earned.
In a perfect world, FIGURE 2: RISK CURVES, IRON CONDOR. Here you see the risk curves for the example trade in Figure 1. The trade has 35 calendar
the stock in question days until option expiration. The maximum profit on the trade would be $60 or 13.6% of capital risked.
will remain in a
quiet trading range during the life of announcement prior to the expiration 2,000
an iron condor trade. Some traders date of the options you plan to trade. • No earnings announcement in the
argue that one way to accomplish Few things can cause a stock to make upcoming 45 days
this is to purposely look for stocks a surprisingly large move like an • IV rank > 15% (0% = IV at a
or indexes that are already mired in a earnings announcement. So they are two-year low, 100% = IV at a
trading range. This makes sense, but best avoided. two-year high)
again, a word of caution. No trading • Call and put sold are $10 to $14
range lasts forever, so if you trade a Scanning for iron condors away from underlying price
security that has been in an extended Using www.optionsanalysis.com, I • Difference between call and put
trading range, one could argue that scanned for iron condors using the strikes sold is $20 to $25
it is that much closer to the next following criteria on 12/16/2022:
breakout and big move. Example trade
It is also ideally preferable not to • Stocks with an average options The top trade using the scan described
trade an iron condor on a security bid/ask spread <= 2%
that has an upcoming earnings • Average daily option volume > Continued on page 21
April 2023 • Technical Analysis of Stocks & Commodities • 7
DIGITAL SIGNAL PROCESSING
H
profit per trade because the data swings are less, all
igh-frequency components in the data other things being equal. When carried far enough,
spectra—that is, “noise” in the data or all transaction costs of slippage and commission can
the extra wiggles on the chart that distract exceed your average gross profit per trade.
from price direction—are the bane of trad- The bottom line is there is a “sweet spot” for sam-
ers because they often lead to whipsaw trades. The pling rate that depends on the trader’s technique.
usual approach is to reduce their effect on trading
rules through the use of smoothing filters, such as A new approach to smoothing
moving averages. In the past I have introduced more No matter the sampling rate, we still have to get rid of
effective smoothing filters, like the SuperSmoother those pesky high-frequency components. My radical
infinite impulse response (IIR) filter and the Hann proposal is this: Simply ignore them. But ignoring the
windowed finite impulse response (FIR) filter. high-frequency components doesn’t come for free.
I now propose to eliminate those high-frequency Sampled data is different from continuous data
components with a new approach. because its shortest possible wavelength has exactly
two samples per cycle. This is called the Nyquist
Data sampling rate frequency. Sampled data simply does not contain
Market data are sampled data. For example, using information whose wavelengths are shorter than that
daily data, we get only one sample per day. Regard- of the Nyquist frequency. Of course, those spectrum
less of whether that sample is the close representing components are still there in continuous data. The
the data for that day, the average of the high, low, sampling process handles those shorter wavelength
and close, or any other combination of available components by aliasing. That is, the shorter wave-
statistics. We still only get one sample per day. The length components are simply folded back into the
sample rate can be increased. For example, trad- observable spectrum.
ing intraday on 15-minute bars is not uncommon. Figure 1 illustrates the principle of aliasing, where the
There is a temptation to increase the sample rate cyan line is sampled every 1.25 cycles. The wavelength
VICTORIA NOVAK/MOXUMBIC/E-ART/SHUTTERSTOCK
further, using five-minute bars, one-minute bars, or of the cyan line is shorter than the Nyquist frequency,
even tick bars. The temptation is caused by confus- and so it appears that the signal is the blue line. The
ing resolution with accuracy. More intricate market samples exactly fit both the cyan and blue sine waves,
activity is revealed by the higher sampling rate, but but the blue line has a longer wavelength than the
the increased resolution doesn’t necessarily lead to Nyquist frequency. Thus, in this case, the observable
greater trading profits. The reason for this is that the spectrum component is the blue line because it is the
market data is fractal and has the spectral density of aliased version of the cyan line.
pink noise. That is, the amplitude of the cycle com-
by John F. Ehlers
April 2023 • Technical Analysis of Stocks & Commodities • 9
It is a workable approximation that the cycle amplitude is
halved every time the cycle spectrum component wave-
length is doubled. So, if we sample once every five days,
a five-day cycle period component is aliased back into our
observable spectrum at half amplitude, a 2.5-day period
component is aliased back into the observable spectrum
at one quarter amplitude, and so on. So, the aliased energy
falls off rapidly compared to the desired signal energy.
Further, market data is nonstationary and so the aliased
FIGURE 1: ALIASING. The principle of aliasing is demonstrated here. That is, signals energy does not fold back coherently. Rather, it is simply
become indistinguishable—or aliases of one another—when sampled. Here, the a little more noise added to the already noisy signal. The
cyan line is sampled every 1.25 cycles of the market data. The samples exactly fit end result is that aliasing is hardly noticed, as a practical
both the cyan and blue sine waves, but the blue line has a longer wavelength matter.
than the Nyquist frequency. In sampled data, as opposed to continuous data, the
shortest possible wavelength has exactly two samples per cycle.
Less lag
The undersampled data also undergoes a quantization
Market data is fractal lag that is half the quantization step size. (“Quantization”
The reason that we can ignore the high-frequency com- means to subdivide into small but measurable increments.)
ponents in market data is because market data is fractal. If daily data is sampled every five days, the induced lag is
2.5 days. This lag is much shorter than that of smoothing
filters that reject cyclic components longer than the Nyquist
rate (10 days) if we were using daily samples.
A practical application of smoothing by undersampling
Undersampling removes the high- is shown in Figure 2. The undersampled data is further
frequency components in price data. smoothed by a six-period Hann filter and a 12-period Hann
filter to be the equivalent of a double moving average. It is
Elimination of these components apparent that the high-frequency components in the data
is done with less lag than that of have been removed by the combination of undersampling
conventional smoothing filters. and Hann-windowed FIR filters.
{ coef(0),
Function: Hann Windowed Lowpass FIR Filter Filt(0);
(c) 2021-2022 John F. Ehlers
} Filt = 0;
coef = 0;
Inputs: For count = 1 to Length Begin
Price(numericseries), Filt = Filt + (1 - Cosine(360*count / (Length +
Length(numericsimple); 1)))*Price[count - 1];
coef = coef + (1 - Cosine(360*count / (Length + 1)));
Vars: End;
count(0), If coef <> 0 Then $Hann = Filt / coef;
Continued on page 43
a dynamic suite of
trading platforms
designed for every
kind of trader.
From the advanced tools of thinkorswim® desktop to the streamlined interface of thinkorswim
web to the convenience of thinkorswim mobile, thinkorswim offers a range of trading
experiences for a range of trading needs. So no matter where you are on your trading journey
or how you like to trade, the thinkorswim suite of trading platforms is designed for you.
All investing involves risks, including loss of principal. TD Ameritrade, Inc., member FINRA/SIPC, a subsidiary of The Charles Schwab Corporation.
© 2022 Charles Schwab & Co., Inc. All rights reserved.
Using The Flow Of Foreign Investment Money
Repatriation
Traders are always looking for tradable patterns in the 4. Seasonal trades in stocks recognize that some com-
data. Here is a pattern used by currency traders that you panies, such as travel and leisure, profit from more
may not have heard of and that could provide an edge. activity during the summer and winter holidays.
5. Volume is highest near the open and close, and
By
by Perry J. Kaufman lowest in the middle of the day.
now, we know that the stock market is Traders also mine data looking for new patterns, or
a complex vehicle for investing. Each patterns that persist for only a short time based on the
person or institution has their own reason current economic conditions. Investors react differently
for buying and selling and their own in bull markets than in bear markets.
timing. Yet viewed as a bigger picture,
there are patterns that emerge that traders have been Repatriation
able to exploit. The patterns can be either technical or There is a pattern that is rarely recognized except by
fundamental, or both. For example: currency traders, and it is called repatriation. It is the
flow of foreign investment money back to the country
1. “Taylor’s 3-Day Trade” looks for reversals after of origin.
three days of price moves in one direction. re·pa·tri·a·tion | rēιpātrēιāSH(ə)n, rēιpatrēιāSH(ə)n |
PANUWATCCN/SHUTTERSTOCK
FIGURE 1: SAMPLE PROGRAM OUTPUT. Here you see monthly returns of the euro currency futures (CU) when the S&P closed higher three days before the end
of the month. Cells with zero correspond to months in which the S&P closed lower.
It doesn’t seem as though there should be a pattern to tion on the close two days before the end of the month
that flow because investors enter and exit the markets and exit on the close of the month. We hold the trade
every day for any number of reasons. But there is a pat- for only two days.
tern driven by large non-U.S. investment firms. It goes
this way: Selecting higher S&P returns
The program allows you to test the day on which you
When foreign money is invested in the U.S. stock market, measure the index returns, then enter on the close of that
and that market is profitable for the current month, they day. We use the close of the third day back to allow the
repatriate those profits at the end of the month. trade to be held for two full days.
It also allows you to set a filter for the index returns.
We can recognize when this occurs by measuring That is, you may want to capture the currency returns
the returns of the S&P, the NASDAQ, or the small-cap if the S&P is positive by any amount on the third day
index. If they are profitable above a certain return, then before the month-end. But we also want to see what hap-
the currencies of the foreign investors will be stronger pens if we are more selective. Do the returns improve if
on the last day of the month because they need to buy we require the S&P to close higher by 1% or 2%? The
those currencies to repatriate the funds. To move money higher our threshold, the fewer the cases.
from the U.S. back to, for example, Europe, they need Figure 1 shows the table produced by the program
to sell the dollar and buy the euro. That goes for other using three days back and any S&P positive return. The
currencies as well. cells with zero correspond to months in which the S&P
We don’t know which parts of the U.S. market have closed lower.
been targets of foreign investments, so we will look at Figure 2 shows the monthly returns of the S&P–euro
all three stock indexes mentioned above. combination using S&P return filters of 0%, 1%, and 2%.
It shows that either a 1% or 2% filter is an improvement
A program to test the theory over no filter.
I wrote a program on my own platform so that I could
test multiple index and currency markets at one time. In
sidebar “Repatriation Pattern Trade, In EasyLanguage When foreign money is invested
Code,” you will find a program that allows you to test in the US stock market, and the
one combination at a time. US stock market is profitable
You enter the equity index market as data2 and the for the current month, they
currency as data1. We are interested in the profits from
the currency if the index market has returned greater
repatriate those profits at the
than some percent as of two days before the end of the end of the month.
month. We then take a long currency/short dollar posi-
April 2023 • Technical Analysis of Stocks & Commodities • 15
REPATRIATION PATTERN TRADE, IN EASYLANGUAGE CODE
This code allows you measure the returns of an equity totalmonth[ix] = totalmonth[ix] + months[ix];
index and test for a potential currency trade to enter two totalPL = totalPL + months[ix];
days before the end of the month. The code allows you // monthly PL
to set a threshold for the index returns to filter trades. print(File("c:\TradeStation\Repatriation_
Currency data is entered as data1 and equity index data Monthly_$PL.csv"),
is entered data2. year(date[1])+1900:4:0,",", ix:2:0, ",",
totalPL:8:4);
months[ix] = 0;
// PJK Repatriation end;
// Copyright 2022-2023, P J Kaufman. All rights reserved. nyears = nyears + 1;
// This program uses futures only end;
// data1 = currency // new year begins
// data2 = equity index k = 0;
end;
inputs: daysbeforemonthend(2), minreturn(0.02);
vars: endofmonth(0), pendofmonth(0), indexreturn(0), // calculate last month returns from end of prior to
cmonth(0), pmonth(0), // n days before this end
ix(0), k(0), size(0), ATR(0), investment(25000), nyears(0), if pendofmonth = 0 then
totalPL(0), indexreturn = 0
priordate(0), newdate(0), savecmonth(0); else
array: months[12](0), totalmonth[12](0); indexreturn = close[daysbeforemonthend] of
data2/pendofmonth - 1;
once begin
// Writes an ASCII file with a name created from the data months[pmonth] = 0;
// series if indexreturn >= minreturn then begin
print(File("c:\TradeStation\Repatriation_Table.csv"),
"Year,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,No // currency returns only last day of month
v,Dec"); ATR = AvgTrueRange(20);
for ix = 1 to 12 begin if ATR <> 0 then
months[ix] = 0; size = investment/(ATR*bigpointvalue)
end; else
k = 0; size = 0;
print(File("c:\TradeStation\Repatriation_Monthly_$PL. months[pmonth] = 100.*(close[1]/
csv"),"Year,Month,$PL"); close[daysbeforemonthend] - 1);
end; end;
cmonth = month(date); k = k + 1;
pmonth = month(date[1]);
// if end of data output final records
// if month changes, process if lastbaronchart and cmonth = pmonth then begin
if cmonth <> pmonth and cmonth <> savecmonth and print(File("c:\TradeStation\Repatriation_Table.csv"
currentbar > 1 then begin ),year(date[1])+1900:4:0,",",
savecmonth = cmonth; months[1]:8:4,",",months[2]:8:4,",", months[3]:8:4,",",months
pendofmonth = endofmonth; {index} [4]:8:4,",",
priordate = newdate; months[5]:8:4,",",months[6]:8:4,",",months[7]:8:
endofmonth = close[1] of data2; {index} 4,",",months[8]:8:4,",",
newdate = date[1]; months[9]:8:4,",",months[10]:8:4,",",months[11]:
8:4,",",months[12]:8:4);
// if end of year then print and clear arrays
if pmonth = 12 then begin print(File("c:\TradeStation\Repatriation_Table.
print(File("c:\TradeStation\Repatriation_Table.csv") csv"),"Total,", totalmonth[1]:8:4,",",
,year(date[1])+1900:4:0,",", totalmonth[2]:8:4,",", totalmonth[3]:8:4,",",totalmonth[4]:8:
months[1]:8:4,",",months[2]:8:4,",",months[3]:8: 4,","
4,",",months[4]:8:4,",", ,totalmonth[5]:8:4,",",totalmonth[6]:8:4, ",",to-
months[5]:8:4,",",months[6]:8:4,",",months[7]:8: talmonth[7]:8:4,",",
4,",",months[8]:8:4,",", totalmonth[8]:8:4,",",totalmonth[9]:8:4,",",total
months[9]:8:4,",",months[10]:8:4,",",months[11]: month[10]:8:4,",",
8:4,",",months[12]:8:4); totalmonth[11]:8:4,",",totalmonth[12]:8:4);
end;
for ix = 1 to 12 begin
G
by Gregory Aharonian law, to protect your invention. Patents prohibit other
people or other companies from using your invention,
ood traders are always looking for an edge where your invention is either something new or is an
in their trading and are always looking for improvement on existing techniques. (Note that patents
new trading techniques to harness. Profitable are not a right for you to use your invention, since actual
strategies must be able to exploit something implementation of your invention may be subject to
that probabilistically puts you at a slight ad- various laws and regulations.) If you hold a patent on a
vantage over the other side of the trade. An “edge” might particular invention, and if someone uses that invention
come from your own market observations, or something without licensing your invention or without outright
you read, or ideas you may pick up in an online trading- buying your patent from you, then legally you can sue
TIERNEYMJ/SHUTTERSTOCK
related forum. Of course, if an idea becomes too popular them for patent infringement. In some cases (such as has
and is used by too many trading strategies, the edge it occurred with some cellphone patents and drug patents),
provided could fade. So we must always be in the hunt the penalties for patent infringement have been in the
for new ideas. billions of dollars.
18 • April 2023 • Technical Analysis of Stocks & Commodities
TRADING TECHNIQUES
A good introduction to the US patent system can be found new inventions. So the point of this article is that you
in the book Patent It Yourself by David Pressman. can get some ideas and inspiration from what others are
In the United States, the patent system is overseen by thinking and developing, and you may be able to take
the US Patent and Trademark Office (USPTO, www. a germ of an idea and make it your own, for your own
uspto.gov). This site also gives a thorough overview of personal use, which could give you a unique edge. After
what patents are and the basic process for obtaining one. all, it is commonplace for companies today to stay abreast
Other countries may have their own patent offices. of what their competitors are doing and to keep moving
forward with their own progress by studying others’
Finding trading ideas products, developments, successes, and failures, and also
For many decades, business methods have been patent- researching their patents (both to avoid infringement
able. One type of business method that is patentable is and to work toward distinguishing their own product
trading techniques for use in the financial markets. Inter- offerings).
estingly and somewhat controversially, one requirement Second, understand that patent offices are not experts
for obtaining a patent is to give a detailed description of in the technology for which they are examining patent
your invention, which serves to identify and distinguish applications. So patent offices such as the USPTO won’t
your patent or invention from other patents or inventions. really know if a particular invention actually works or
These descriptions can be a rich source of ideas for trad- not. They are only trying to gauge whether the invention
ing strategies and trading techniques. By browsing the described is adequately unique to be patentable.
documents, you may be able to glean a few good trading Third, patents do not provide a highly detailed descrip-
ideas from work that others are doing in the field. tion of the invention. A patent filing serves to briefly
To be clear, I am not proposing the replication, imple- describe and identify an invention; it is intentionally
mentation, and distribution of another’s patented inven- not a how-to manual on how to use or implement an
tion. Patents are a form of intellectual property and as invention. However, it still may contain enough food
such they are someone else’s property. Technically, it for thought for you to think about how you might use
is the implementation of the idea (such as in a process, some of the ingredients yourself, and you may be able
a machine, a manufactured item, a composition, or a to add some of the ingredients you come across into
design) that is patented. your own recipe.
I will also say that points two and three, which on the
Browsing the databases face of it seem like drawbacks, actually have a benefit
Patent offices maintain public databases of the patents for traders: The fact that patent documents lack complete
issued in their country. The USPTO’s database is at details of an invention or may represent something never
www.uspto.gov/patft. Since such databases are mostly actually undertaken means that it won’t be a widely
designed for insiders, they are not the easiest to use, and known idea or product. Again, a widely used idea could
they only include patents for their own country. I find dilute an edge, whereas a vague idea about something or
that an easier-to-use and more comprehensive patent da- an obscure ingredient could help you yourself to create
tabase is offered by Google, available at: https://patents. something unique that no one else is using and that will
google.com. This site allows you to search on keywords give you an edge.
of interest to start exploring. A fourth note is about timelines. Patents generally
last 20 years from when they were filed, with some ex-
Caveats and notes tensions. A check of the USPTO database can help tell
There are several caveats and characteristics about patents you whether a patent is still in force, or whether it has
to note for some more background. lapsed. Some inventions for which the patent on it has
First, given that the whole point of having a formal expired and was not renewed or extended can fall into
system of patenting is to protect inventions and the the public domain. Ideas that are in the public domain
implementation of ideas, it is illegal and improper to use can usually be more freely used (but could also be more
a patented invention without going through the proper widely used).
steps to license or buy the rights to it, as I already stated. A fifth note: Sometimes, you will see multiple patents
An important purpose of patents is to make it worthwhile filed for one invention. Given that it is likely a company
for people and companies to invest in the research and spent a significant amount of money (in the tens of thou-
development necessary to bring their ideas to market. sands of dollars or more) to prepare and file so many
This is what makes it possible for us all to benefit from patent applications for one invention, this can indicate
April 2023 • Technical Analysis of Stocks & Commodities • 19
the inventor believes their invention is something “hot”
and they want rock-solid legal protection for it. While
it’s interesting to see what “hot” or important ideas are Patent documents can be
being developed in the field, again, ideas garnering a lot
of attention or being put into service in many ways may
an interesting source of
in the end suffer from dilution and lead to less unique ideas and inspiration.
trading ideas for you.
A final caveat has to do with if you are considering
patenting your own idea. If this article inspires you to https://patents.google.com/patent/US20140289096A1/en
consider patenting your own trading idea or invention, I
would suggest avoiding that route, especially if you are “Asset analysis according to the required yield method”
a retail trader. One reason is that generally, the protec- (Note: this one has some good math in it)
tion of patents stops at national borders. And financial U.S. Patent Application 2010/042553 (abandoned in 2012)
markets today are global in nature. So while a patent- https://patents.google.com/patent/US20100042553A1/en
holder could potentially sue to stop someone else from
using their idea within their own borders, or possibly “Method and device for evaluating stock exchange
within other countries that have mutual agreements in rates”:
place, you would not be able to do much about use of Austrian Patent AT501028 (abandoned in 2011)
your idea outside your border. And again, gaining an https://patents.google.com/patent/AT501028B1/en
edge can mean having a unique approach.
“System and methods for detecting advance earning
Examples insider information”:
One public benefit of the patent system is that patent U.S. Patent Application 2017/236201 (abandoned in 2019)
applications that have been abandoned for more than https://patents.google.com/patent/US20170236201A1/en
two years are in the public domain. Furthermore, issued
patents that have been abandoned/expired for more than “Market microstructure data method and appliance”
six years are completely in the public domain and are (includes mathematical formulas):
not generally subject to litigation concerning infringe- U.S. Patent Application 2014/149273 (abandoned in 2015)
ment, meaning if you first start using techniques in an https://patents.google.com/patent/US20140149273A1/en
abandoned/expired patent six years or more after it was
abandoned/expired, you theoretically can’t be sued for Those are some examples I found that I think contain
damages for using it. some very good ideas. You may wish to explore the
Following are some examples of links to abandoned/ database for yourself according to your own interests.
expired technical analysis–related patents whose tech- To begin, go to the Google Patents site and you’ll see a
niques would now be considered in the public domain. simple search box. Enter a term having to do with the
And here is an interesting side note about the patents markets. Entering “technical analysis” plus “stocks” and
in these links: While many academic writings in the “options” returns over 1,800 search results. Peruse the
finance realm are written in support of the efficient mar- results and see if any seem to match your interests. You
ket hypothesis (that is, with the premise that there can may find, for example, a description of a trend trading
be no successful trading systems), all of the following system, or example equations being incorporated into
patents are for inventions in support of the inefficient an algorithm, or even some example output that could
market hypothesis. be examined. It can be educational.
Or you could try searching on the term “interest
“Method for creating and valuing financial instruments rates.” Interest rate predictions are hugely important in
linked to average credit spreads”: the financial world, and you’ll see some of the research
U.S. Patent Application 2006/143099 (abandoned in 2008) being done in this area.
https://patents.google.com/patent/US20060143099A1/en Or try “Black-Scholes,” the well-known model used
in options trading. The search results suggest there are
“System/method for providing [graphical] share assess- over 2,000 patents around the world describing improve-
ment data with compound quality analysis”:
U.S. Patent Application 2014/289096 (abandoned in 2016) Continued on page 41
20 • April 2023 • Technical Analysis of Stocks & Commodities
Explore Your Options
KAEPPEL/OPTIONS cay will begin in earnest soon)
Continued from page 7 • The amount a trader must put The idea that a trader
up to trade a 1-lot is $440—this can “set it and forget
involved using options on Elec- also represents the maximum
tronic Arts (EA). With EA trading dollar risk
it” with an iron condor
at $121.74, the legs are: • The maximum profit on the is misguided.
trade is $60, or 13.6% of capital
• Buy 1 Jan20 2023 140 call @ risked the simplest terms possible, the trader
$0.19 • The maximum profit will be real- must formulate a contingency plan
• Sell 1 Jan20 2023 135 call @ ized if the trade is held until expi- regarding what they will do if the
$0.45 ration and EA is between $109.40 underlying security approaches one
• Sell 1 Jan 20 2023 110 put @ and $135.60 at that time of the short strikes. Unfortunately, the
$0.72 range of possible actions is beyond the
• Buy 1 Jan 20 2023 105 put @ Managing the trade scope of this article. But in general, if
$0.38 If the underlying stock doesn’t wan- one of the short strikes is threatened,
der too far, there isn’t really anything most traders will attempt to adjust the
The trade particulars and the risk that needs to be done. The main original position to reset the reward-
curves for this trade appear in Figures problem with an iron condor is that to-risk ratio more favorably.
1 and 2. the risk on both the upside and the
downside is generally much larger
Things to note: than the profit potential. So the idea
• This trade has 35 calendar days that a trader can “set it and forget it”
until option expiration (so time de- with an iron condor is misguided. In
KAUFMAN/REPATRIATION
Continued from page 17
We then take a long currency/
short dollar position on the
Figure 5 shows that this approach also works for the
British pound when Nasdaq returns more than 2%.
close two days before the end
of the month and exit on the
are These reTUrns good enoUgh? close of the month.
We are looking at about 15% return over 12 years. That’s
not a lot. However, it is earned by being in the market only
24 days each year. In addition, futures can be leveraged. and Learn To Trade (2022). For questions or comments,
Currency futures can be leveraged a lot. please go to www.kaufmansignals.com.
The benefit of this approach is that it is very different
from other trading methods, and it has less exposure to The code given in this article is available in the Article
price shocks. If you are only in the market 24 of 252 Code section of our website, Traders.com.
days, you have reduced your exposure by 90%.
You have also gained another view of why prices FUrTher reading
move. Kaufman, Perry J. [2022]. Learn To Trade, Amazon.
[2020]. Trading Systems and Methods, 6th Edi-
Perry J. Kaufman is a trader and financial engineer. tion, Wiley.
He is the author of many books on trading and market [2020]. Kaufman Constructs Trading Systems
analysis, including the sixth edition (2020) of Trading (print and ebook editions), Amazon.
Systems and Methods (with the first edition published in ‡TradeStation
1978 as a seminal book in the field of technical analysis), ‡See Editorial Resource Index
as well as Kaufman Constructs Trading Systems (2020),
April 2023 • Technical Analysis of Stocks & Commodities • 21
Long-Term And Short-Term Trading Of An ETF
Come follow along on a quest to discover profitable provide some trading strategy rules for ETFs related to
trading rules you can use, based on a few technical gold and silver, based on the same technique. In response
indicators. In this two-article series focusing on two dif- to those requests, we set out to devise some possible
ferent markets, we’ll conceptualize some strategies and trading strategy rules that could beat a buy-and-hold
technical trading rules, test them, and then compare the strategy for SLV and GLD, the popular ETFs related to
results. Here in part 1, the focus is on trading a popular the silver and gold markets.
gold market ETF. Here in this article, we will analyze some possible
technical trading rules for GLD. Then, in part 2, to appear
by Massoud Metghalchi, PhD, in an upcoming issue of this magazine, we will analyze
and Linda A. Hayes, PhD some possible technical trading rules for SLV.
In
the September 2022 issue of Technical SPDR Gold Shares ETF (GLD)
Analysis of Stocks & Commodities, I and GLD is symbol for the SPDR Gold Shares ETF that
coauthor Peggy Cloninger presented an owns gold bullion and began trading on November 18,
OLIVIER LE MOAL/SHUTTERSTOCK
article on trading the natural gas ETF UNG 2004. This ETF allows investors to participate in the
(“Trading Natural Gas Using UNG”). In the gold market without having to take actual delivery of
article, we used a Coppock indicator that gold. GLD is designed to closely mimic the price of gold
we had revised and updated. After that article came out, minus the fund’s fees and expenses. This ETF can easily
some readers wrote to us and asked us if we could also be bought and sold via stock brokerage firms.
22 • April 2023 • Technical Analysis of Stocks & Commodities
TRADING STRATEGIES
STOCKCHARTS.COM
revised Coppock indi-
cator plus a dozen other
technical indicators such FIGURE 1: SPDR GOLD SHARES ETF (GLD). The popular SPDR Gold Shares ETF GLD began trading on November 18, 2004
as the relative strength and is designed to closely mimic the price of gold minus the fund’s fees and expenses.
index (RSI), moving
average convergence/ Chance of Losing in the Stock Market
divergence (MACD),%D of stochastic (%D), moving 100%
averages (MAs), and a few others. Then, we will provide
the best results from the technical trading rules tested. 75%
Chance of Loss
MINDFULLYINVESTING.COM
25%
Long-term analysis
In the long term, we use the rate function in Microsoft 0%
Excel to estimate the geometric return of the B&H 0 5 10
Years Invested
15 20
strategy as follows:
FIGURE 2: WEALTH RISK OVER VARIOUS TIME HORIZONS. Many assets
tend to appreciate in the long run, as does the stock market in general. The risk
B&H return = Rate (N, PMT, −PV, FV) associated with wealth (not periodic returns) for the S&P 500 after 15 years of
= 5.95% Eq.1 buying and holding the S&P 500 is almost zero.
where N = number of periods, or 15.33 years, PMT is zero, A trader following strategy 1, long/money, will buy
PV is the closing price of GLD on 6/1/2007 or $64.27 the GLD ETF when the trading rule emits a buy signal.
when technical trading estimation starts, and FV is the When the rule emits a sell signal, the trader will sell
closing price of GLD on 10/1/2022 or $155.99. GLD and invest the funds in TLT.
Note that although the GLD ETF started trading in A trader following strategy 2, long/short, will buy GLD
November 2004, because of the estimation of a moving when the trading rule emits a buy signal and short GLD
average of 30 months, our start of technical trading when the rule emits a sell signal.
analysis is 6/1/2007, since the use of MA30 requires 30 For strategy 3, leverage/money, a trader will buy GLD
months of averaging the GLD price. on leverage and invest in TLT when the rule emits a sell
We will design the technical trading rules in com-
bination with a few strategies to beat the return of the
B&H strategy, which was 5.95%. The four strategies are
similar to the strategies we discussed in the September
To investigate trading rules that
2022 article on natural gas, namely: could outperform a buy-and-hold
strategy for GLD, we will explore
Strategies applying the revised Coppock
1. Long/money indicator plus a dozen other
2. Long/short
3. Leverage/money, and
technical indicators.
4. Leverage/short
April 2023 • Technical Analysis of Stocks & Commodities • 23
signal. The return for buy days for this strategy will be Coppock Trading Rule
two times the GLD return minus the TLT return. Rule
Strategy 1 Strategy 2 Strategy 3 Strategy 4
Finally, for strategy 4, leverage/short, a trader will buy Monthly
0.63% 0.48% 1.15% 0.99%
GLD on leverage when the rule emits a buy signal and average
short GLD when the rule emits a sell signal. Annual
7.91% 5.87% 14.74% 12.57%
return
We use TLT, iShares Treasury bond ETF, as a proxy Rule 10-Month MA > 30-Month MA
for returns on invested funds for strategies 1 and 3 and a Monthly
borrowing rate for strategies 3 and 4 when a trader buys average
0.64% 0.33% 1.15% 0.84%
GLD on leverage. Annual
7.94% 3.98% 14.81% 10.60%
return
Assessing risk Rule 30-Month MA Is Increasing
Monthly
Our approach to risk is very different from most literature average
0.62% 0.77% 1.12% 1.26%
on risk/return trade-offs. In the long run, the risk for a Annual
7.72% 9.66% 14.33% 16.39%
trader’s wealth is almost zero. For example, the risk as- return
sociated with wealth (not periodic returns) for the S&P FIGURE 3: LONG-TERM TECHNICAL TRADING RULES FOR GLD, 6/1/2007–
500 after 15 years of buying and holding the S&P 500 is 10/1/2022. Here are the three long-term technical trading rules that showed
almost zero as can be seen by the chart in Figure 2. the best results in the tests, in combination with the four long/short strategies.
Given that in the long run most assets such as precious These long-term trading rules are based on monthly data for GLD. You can see
that the results from these three best trading rules are very similar. Compare
metals do not lose their value and the risk of a negative
to the annual return of 5.95% for the buy & hold approach.
return after 15 years is close to zero, we only look at the
returns of various trading rules that can beat the B&H
return. In the short run, when we use daily data, we Next we’ll explain each of these three rules and how
compare both the risks and returns of various trading they were combined with each of the four strategies
rules with the risk and return of the B&H strategy. For discussed earlier.
the long term, we look at returns only, since after 15
years, the value of an asset such as gold would be above Trading rule 1: Coppock trading rule
its price 15 years ago. Let’s start with the trading rule based on the Coppock in-
dicator. We estimate the Coppock indicator as follows:
Calculating annual returns
For our tests on our long-term trading rules, we will es- Coppock = EMA10 of [ROC (14 months GLD price)
timate annual returns based on the following formula: + ROC (11 months of GLD price)] Eq. 3
Annual return = EXP (average monthly where EMA10 is the exponential moving average of 10
return * 12) −1 Eq. 2 months, and ROC [14] and ROC [11] are the 14 months
and 11 months rates of change of the closing price of
The “annual return” in equation 2 is based on the geo- GLD.
metric compounding of the monthly average returns. A trader following this Coppock trading rule with
“EXP” is the Excel function for “exponential.” strategy 1 will buy GLD if Coppock is greater than
zero and will stay invested in GLD till the Coppock
The trading rules indicator becomes zero or less than zero; at this time,
In the table in Figure 3, we present the three long-term the trader will sell all GLD and invest the funds in TLT.
trading rules that had the best results in our test. Our This will be repeated for the entire period of 6/1/2007 to
long-term trading rules are based on monthly data (a 10/21/2022, implying a total of seven in and out trades of
total of 185 months or observations) for GLD. You can GLD for the entire period, or 0.45 trades per year. Since
see that the results from these three best trading rules the transaction costs of trading GLD are zero, we have
are very similar. The three trading rules are: not considered transaction costs.
A trader following this Coppock trading rule with
1. Coppock indicator trading rule strategy 2 will buy GLD when the rule emits a buy
2. 10-month moving average > 30-month moving signal (Coppock >0), and will short GLD when the rule
average emits a sell signal.
3. 30-month moving average is increasing For strategy 3, when the Coppock trading rule emits a
24 • April 2023 • Technical Analysis of Stocks & Commodities
buy signal, the trader borrows at the money market rate All trades for the above three trading rules are made
and doubles (50% margin) investment in GLD. When the on the last day of each month. We assume that on the
rule emits a sell signal (Coppock <0), the trader parks last day of each month, a few minutes before the market
the funds in TLT. closes, a trader can estimate the GLD price that will
This rule with strategy 4 implies buying GLD on trigger a buy or sell signal and will initiate a conditional
margin when the rule emits a buy signal and shorting limit order just before the market closes at the end of
GLD when the rule emits a sell signal. each month. If a trader cannot estimate the GLD price
For the Coppock trading rule, strategies 2 and 4 are that triggers a buy/sell signal at the close of the month,
inferior to strategies 1 and 3, implying shorting GLD is the trader can initiate the buy/sell order the next day at
not a good idea for the Coppock trading rule. The returns the open. Placing the order on the open the next day
of strategies 1 and 3 are 7.91% and 14.74%, respectively, would not change our results. Also, it would eliminate
and these returns should be compared with the B&H the non-synchronicity bias.
return of equation 1, or 5.95%. In conclusion, for long-term trading, the trader may
perform better by using one of our three trading rules
Trading rule 2: MA10>MA30 with strategy 1 (low risk) or strategy 3 (high risk) rather
The second-best long-term trading rule from Figure 3 than buying and holding GLD for the long term.
is MA10>MA30. For this trading rule combined with
strategy 1, a trader will buy GLD if the 10-month mov- Short-term analysis
ing average is above the 30-month moving average, and From Yahoo Finance, we’ll use the daily closing price of
otherwise, will park the funds in TLT. GLD and TLT from 11/19/2004 to 10/10/2022. Since the
Strategy 2 is similar to strategy 1 except when the rule estimation of MA200 days requires data from previous
emits a sell signal, the trader will short GLD. Strategies days, all estimations and technical trading are done from
3 and 4 are similar to strategies 1 and 2 except when 9/16/2005 to 10/10/2022, which is 4,296 days of daily
the rule emits a buy signal, the trader will buy GLD on prices. We estimate various statistics as follows:
margin.
Once again, as with the previous trading rule, strategies Daily return = Log (Pt / Pt-1) Eq. 4
2 and 4 are inferior to strategies 1 and 3, implying that
it is better to park the funds in TLT rather than shorting Annual return = EXP (average daily returns
GLD when this rule emits a sell signal. * 260) −1
The average annual returns for this trading rule used
with strategies 1 and 3 are 7.94% and 14.81%, better than σA = σd * √365 Eq. 5
the B&H of 5.95%. This trading rule implies six trades
in and out of GLD for the entire period.
where σA and σd are the annual and daily standard devia-
Trading rule 3: 30-month MA is increasing tion (SD) of daily returns of GLD according to equation 4.
The third best long-term trading rule from Figure 3 is “EXP” is the Excel function for “exponential.”
when the 30-month MA is increasing, a trader will buy
GLD if MA30 of GLD is going up, and otherwise (that The trading rules
is, when MA30 is going down), the trader will be out of For exploring short-term trading rules, we analyzed
GLD, either buying TLT (strategies 1 and 3) or shorting
GLD (strategies 2 and 4).
The annual average returns for this trading rule com- Given that in the long run most
bined with the four strategies are 7.72%, 9.66%, 14.33%,
and 16.39%, respectively. These long-term annual returns
assets like precious metals do not
should be compared with the B&H return of 5.95%. lose their value and the risk of a
negative return after 15 years is
Conclusions close to zero, we only look at the
Given that leverage usually increases risk, a trader with returns of various trading rules
a low tolerance for risk should apply these trading rules
with strategy 1. Traders with a higher tolerance toward that can beat the B&H return.
risk could use one of these three rules with strategy 3.
April 2023 • Technical Analysis of Stocks & Commodities • 25
a dozen technical indicators generated by % D of Stochastic Indicator Is Increasing
TraderCode software. Here, we’ll discuss the Rule
Strategy 1 Strategy 2 Strategy 3 Strategy 4 B&H
best technical trading rules with combinations Annual
12.79% 1.35% 26.69% 13.84% 7.49%
of the above four strategies found from our return
test. We will also compare the risk-return of Annual SD 19.34% 21.85% 32.80% 34.37% 21.85%
the best trading rules and strategies with the Reward/
0.66 0.06 0.81 0.40 0.34
Risk
risk-return of buying and holding GLD.
Rule RSI > 30 B&H
In the table in Figure 4, we present the three Annual
best models from our tests. They are: return
9.37% 9.04% 19.11% 18.75% 7.49%
Annual SD 21.47 21.84 43.40% 43.59% 21.85%
1. %D of stochastic indicator is increas- Reward/
0.44 0.41 0.44 0.43 0.34
ing Risk
2. RSI >30 Rule 150-Day MA Increasing B&H
3. 150-day MA is increasing Annual
return
9.04% 6.49% 18.39% 15.62% 7.49%
Annual SD 20.09% 21.85% 36.66% 37.65% 21.85%
Trading rule 1: %D of stochastic indicator Reward/
is increasing Risk
0.45 0.30 0.50 0.41 0.34
The best trading rule from Figure 4, combined FIGURE 4: SHORT-TERM TECHNICAL TRADING RULES FOR GLD, 9/16/2005 TO
with strategy 1, means that the trader buys 10/10/2022. To come up with some possible technical trading rules for shorter-term trading,
GLD if the %D of the 14-day slow stochastic a dozen technical indicators were explored. The three best trading rules from the test are
(MA3 of %K) is increasing. The trader stays shown here, in combination with the four long/short strategies. Also shown is the risk-return
of the trading rules and strategies compared with the risk-return of buy & hold for GLD.
invested in GLD until %D starts to decrease.
Notes: SD stands for standard deviation, and annual return is based on the formula [EXP (Daily
At that point, the trader sells GLD and parks average*260) −1]. EXP is the Excel function for “exponential.” %D is the slow stochastic.
the funds in TLT. This will be repeated for
the entire period of 9/16/2005 to 10/10/2022,
implying a total of 138 in and outs in GLD over the 17.07 Trading rule 2: RSI >30
years, or an annual average of 8.09 trades per year. Since The second-best short-term trading rule for GLD from
the transaction costs of trading GLD are zero, we have Figure 4 implies buying GLD if the 14-period relative
not considered the transaction costs. strength index (RSI) is above 30.
The annual returns of this trading rule combined with A trader following this rule with strategy 1 will buy
strategies 1 and 3 are 12.79% and 26.69%, respectively, GLD if RSI is above 30 and will stay invested until RSI
compared to the B&H annual return of 7.49%. The risks goes below 30; at that time, the trader will sell GLD and
of this trading rule with strategies 1 and 3 are 19.34% park the funds in TLT for strategy 1, or, for strategy 2,
and 32.80%, respectively. will short GLD. This rule with strategies 3 and 4 is
These risks should be compared with the risk of the similar to strategies 1 and 2 except that when the rule
B&H strategy of 21.85%. Thus, trading rule 1 with strat- emits a buy signal, the trader buys GLD on margin.
egy 1 has a higher return and a bit lower risk than the For this RSI trading rule combined with each of the
B&H strategy. Trading rule 1 with strategy 3 provides four strategies, the reward-to-risk ratios are higher than
very high returns and also higher risk, so it’s a good the reward-to-risk ratio of B&H. This RSI trading rule
choice for risk-tolerant traders. The reward/risk ratio combined with strategy 1 is appropriate for traders with
(annual return divided by annual SD) of this rule with a low risk tolerance, with strategy 2 for traders with a
both strategies 1 and 3 are much higher than the reward/ medium risk tolerance, and with strategies 3 and 4 for
risk ratio of the B&H. traders with a high risk tolerance.
This trading rule with strategies 1 and 3 are superior This rule combined with strategy 1 has an annual return
to strategies 2 and 4, implying that when the rule emits of 9.37%. Note that if we change RSI>30 to RSI>31 or
a sell signal, it is better to park the funds in TLT rather RSI>29, the annual return for this rule with strategy 1
than short GLD. remains unchanged at 9.37% for RSI>31, and becomes
This rule combined with strategy 1 is appropriate 8.49% for RSI>29.
for traders with a low tolerance for risk, while the rule
combined with strategy 3 is appropriate for traders with Trading rule 3: 150-day MA is increasing
a high tolerance to risk. In the third-best trading model, when the 150-day MA
26 • April 2023 • Technical Analysis of Stocks & Commodities
is increasing, a trader will buy GLD and Sub-Period 1: 2/27/2007 to 3/28/2014
stay invested in GLD as long as MA150 is Strategy 1 Strategy 2 Strategy 3 Strategy 4 GLD (B&H)
increasing, and otherwise will be out of GLD. Annual
22.62% 2.59% 47.29% 23.24% 12.99%
For this trading rule, strategies 2 and 4 are return
inferior to strategies 1 and 3, implying that Annual SD 21.55% 25.83% 38.81% 41.39% 25.82%
when the rule emits a sell signal, it is better Reward/
1.05 0.10 1.22 0.56 0.50
Risk
for traders to park funds in TLT rather than
Sub-Period 2: 3/29/2014 to 10/10/2022 GLD (B&H)
shorting GLD. Annual
This trading rule with strategy 1 has return
3.76% 0.15% 8.90% 5.11% 2.72%
an annual return of 9.04%, annual SD of Annual SD 16.83% 16.98% 25.39% 25.49% 16.97%
20.09%, and reward to risk of 0.45, all better Reward/
0.22 0.01 0.35 0.20 0.16
than the B&H strategy for GLD. A similar Risk
conclusion can be made about this rule with FIGURE 5: ARE THE TRADING RULES ROBUST? To help ensure the trading rules are robust
strategy 3. and aren’t just the result of “data snooping,” which can introduce bias into an evaluation, the
This MA trading rule combined with strat- sample test period was divided into two equal sub-periods and the test was rerun Shown
here are test results for just one of the technical trading rules (that is, the “increasing %D”
egy 1 is appropriate for traders with a low
rule), combined with each of the four strategies. As can be seen, the trading rule and strategy
risk tolerance and combined with strategy 3 combinations that beat the reward/risk ratio of the B&H strategy in the entire sample also beat
for traders with a high risk tolerance. the B&H strategy in each sub-period, suggesting the trading rule is robust.
Notes: SD stands for standard deviation; annual return is based on the formula [EXP (Daily
Order placement average*260) −1] where EXP is the Excel function for “exponential.”
All trades for the above three rules are made
at the end of each day. A few minutes before the market In addition, we did the same robustness check for the
closes, a trader can estimate the GLD price that will trigger other two trading rules from Figure 3 and found similar
a buy or sell signal and initiate a conditional limit order results: The trading rules and strategies that beat the
just before the market closes at the end of each day. If a B&H reward/risk ratio in the entire sample also did so
trader cannot estimate the GLD price that triggers a buy/ in each sub-period. (We can provide the returns of the
sell signal at the close of the day, the trader can initiate other two trading rules upon reader request.)
the buy/sell order the next day at the open.
Conclusions
Robustness and “data snooping” GLD is an exchange-traded fund that holds gold bullion
One method to check that the results are robust and not for investors. Traders can buy and sell the fund at leading
a result of data snooping is to divide the entire sample brokerage firms just like for any other ETF, and it has a
period into sub-periods. very good trading volume.
(“Data snooping” is making inferences about the results In this study, we suggest technical trading rules that
when in reality the results could be due to chance. The could beat the B&H strategy both in the short run and
more combinations of variables you test, the likelihood in the long run.
grows.) For long-term traders, we suggest three technical trad-
If the results in each sub-period are similar to the re- ing rules, shown in Figure 3, based on monthly data, that
sults over the entire period, we can conclude with high can be combined with the four long/short approaches
confidence that our methodology is robust, and our results discussed earlier and that indicate better performance
are not the result of data snooping.
In the table in Figure 5, we provide the results for the Continued on page 55
technical trading rule of “%D increasing” for each sub-
period. The two equal sub-periods are from 9/16/2005 to
3/28/2014 and 3/29/2014 to 10/10/2022, implying 2,147
days for sub-period 1 and 2,149 days for sub-period 2. In this study, we’ve suggested
As can be seen in the table, the trading rules and strate- technical trading rules that could
gies that beat the reward/risk ratio of the B&H strategy beat the B&H strategy both in the
in the entire sample also beat the B&H strategy in each
sub-period. Therefore, we can reasonably conclude our
short run and in the long run.
trading rules are robust.
April 2023 • Technical Analysis of Stocks & Commodities • 27
INTERVIEW
A Conversation
With John Ehlers
After four decades of providing products, services, and education to trad-
ers through his company, MESA Software, John F. Ehlers has announced
his retirement. We congratulate him on his long and successful career.
He has been a Contributing Editor to Technical Analysis of Stocks &
Commodities since 1983, a year following the magazine’s launch. He
has written more than 100 articles for the magazine, more than any other
contributor. Ehlers is a pioneer in the use of cycles and digital signal
processing (DSP) technical analysis. He launched MESA Software in the
early 1980s after developing the technique of maximum entropy spectral
analysis as applied to trading and market analysis. MESA Software has
focused on offering algorithmic trading strategies that adapt to different
markets and market conditions.
Traders and technical analysts have benefitted from the research,
tutorials, tools, software, and insights he has provided via his writings,
his products, his speaking engagements, and through the annual semi-
nars he offered through 2022, in which he would share some of his life’s
work on analyzing market data. He continues to contribute articles to
this magazine based on his ongoing, latest research. In this issue, you At its core, trading is an
will find an article in which he presents a practical and effective way to art. But success is simply
smooth market data.
Prior to launching MESA Software, he was a Senior Engineering Fel-
a matter of statistics. By
low with Raytheon and worked on special projects including SkyLab. It using technology, one has
was during his time there that he started to become interested in studying a much higher probability
market data and cycle analysis. of success.
Ehlers can be reached through his website at MESAsoftware.com.
Stocks & Commodities Contributing Writer and “Algo Trading”
columnist Kevin J. Davey interviewed John Ehlers via email in January 2023 to discuss his trading and analysis
approach, his thoughts on where quantitative financial analysis is heading, and his long and meaningful contri-
bution to the fields of technical analysis and quantitative financial analysis.
John, your contributions stand out to you, and why? themselves an immense amount of
over the years to the To me, the importance of an article time simply by avoiding volatility
trading community are is directly related to my contribution when trying to improve market tim-
immense and far reach- to technical analysis. So, I think ers. Instead, they can use volatility
ing. That makes it tough my best article was “A Technical to establish amplitude thresholds to
for someone new to algorithmic Description Of Market Data For improve the probability of a trade
trading, or new to your material, Traders,” which appeared in the May being successful.
to actually benefit from your great 2021 issue of S&C. I also established that the signal
work. So let’s start with the archives In that article, I proved that vola- information in the data is analogous
of this magazine. Out of the 100+ tility is orthogonal (that is, uncor- to frequency modulation or phase
articles you have written for Stocks related) to market timing signals. modulation of a radio wave. The
& Commodities, which one or two Astute strategy developers can save implication of this relationship is
28 • April 2023 • Technical Analysis of Stocks & Commodities
that band-limiting filters can recover short position at the top
trading information with greater ac- of that swing. It is easy
curacy than conventional technical to add a volatility rule to Astute strategy developers
indicators. apparently improve the can save themselves an
It is common knowledge that percent winners or profit immense amount of time
market data are fractal and the factor in historical test-
statistical shape of the market spec- ing. What I have proven is simply by avoiding volatility
trum is pink noise. That means the that such a rule is illusory, when trying to improve
amplitude swings of the frequency and a resulting strategy market timers.
components are in direct proportion will be less robust in out-
to their wavelength, which makes of-sample applications.
the measurement of cycles very dif- Swing trade timing rules
ficult. In fact, cycles are ephemeral should be solely dependent upon the varies with time. Therefore, a walk-
and measurement shows them to be position of the phasor. forward-type procedure is advised
all over the place. Therefore, it is I don’t think Bollinger Bands to get the best strategy performance
just not practical to use measured should be used for swing trading for from the filters.
frequency as a parameter to tune several reasons, mostly because of
filters or indicators. computational lag. Bollinger Bands Let’s say I am a brand-new algo/
I also like “Predictive And Suc- first require a moving average from systematic trader. What would be
cessful Indicators” in the January which to compute the standard devia- the best path for a newbie to start
2014 issue because I introduced the tion. The lag of a moving average utilizing your research and material
SuperSmoother and highpass filters is approximately half the average into their own trading?
there. length, and that alone is enough to Nothing can replace preparation.
I introduced the bandpass filter make the swing trade timing signals First of all, my approach embraces
in “The Bandpass Indicator” in the ineffective. swing, or reversion to the mean, trad-
September 1994 issue. ing. I do this because the algorithmic
I introduced the Hann-windowed In the other articles you mentioned, approach offers a better chance of
FIR (finite impulse response) smooth- filters are introduced. As a best having a higher probability of win-
ing filter in “Windowing” in the practice, do you recommend the ning trades. Trend trading typically
September 2021 issue. trader first analyze the market offers a higher probability of a larger
data with these indicators and profit factor. If you want to be a trend
There is definitely a lot to absorb filters to see if they can be tuned trader, about all my techniques will
in those articles. In the first article to the particular market, or would provide are smoothing filters.
you reference, you mention how you rather people just incorporate If you embrace swing trading, read
volatility is uncorrelated to market the filters in strategies they are all that has been written and apply
timing signals. Can you expand developing? the concepts to your own particular
upon that a bit? For example, I think of the market as a “blackbox market and style of trading. Don’t
are you saying that Bollinger system” when using digital signal avoid studying DSP because it ap-
Bands—which give signals and use processing (DSP). Such a system has pears to be too difficult. Thoroughly
standard deviation as a volatility an input, and output, and a transfer test your strategy for robustness. Now
measure for the upper and lower response linking the two. A system your work is done. When it comes to
bands—can be improved upon or transfer response is often charac- trading, just turn on the computer and
modified by encompassing the ideas terized by its response to an input let it process the trades for you. Don’t
in that article of yours? If so, can impulse function. My research shows override your algorithm. In fact, don’t
you briefly explain? that the system response of the market even look at the trades until they are
I want to underscore that I am is broadly described as the combina- closed. That way you can maintain
referring to swing, or reversion to tion of a highpass filter and a low- your sanity and quality of life.
the mean, style of trading. With that pass filter, forming a relatively wide
style, a trader is attempting to enter passband of spectral components. Excellent points, both on the proper
a long position at the bottom of the Since the market is nonstationary, use of your work and on how to test
cyclic swing and exit or reverse to a the particular tuning of these filters and ultimately execute a strategy.
April 2023 • Technical Analysis of Stocks & Commodities • 29
Sorry for the sidetrack axis). Suppose the data consistently
question. Please continue had a frequency less than 0.05 and
I think this is a profound with new algo trader your trading rules provided strate-
tips. gies that couldn’t miss for weeks
overview of DSP applied to Another tip is to ma- at a time. Then, the data shifts and
trading: Market data are nipulate the data to create now you can’t get a winning trade
fractal and has a pink noise tradable events. Since to save your life. What happened?
spectrum. the data are fractal, the The answer is in the phase response.
spectrum component Successful trades occurred when the
amplitudes are in direct filter phase response was near +90
proportion to their wave- degrees. But when the data shifted
That said, what are the two or three length. Taking a simple difference to a frequency larger than 0.05, the
best tips you’d offer to brand-new of successive data samples creates filter phase response was near -90
algo/systematic traders? a filter whose amplitude outputs are degrees. Thus, the data shift caused
The most important aspect of inversely proportional to wavelength. a 180-degree phase reversal for the
algo trading is “keep it simple.” A Thus, the difference flattens the data information provided to the trad-
trading strategy absolutely has to be spectrum amplitudes. Then, the infor- ing rules and the trading rules are
dirt-simple to be robust in all market mation can be recovered by applying a therefore dead wrong in the second
conditions. One can see an immense smoothing filter to flattened spectrum case. This illustrates how important
interaction between tunable inputs data. Differencing sampled data is phase response is to a successful
when optimizing a strategy. Those analogous to taking the derivative in algorithmic strategy.
same interactions are present when calculus and smoothing is analogous
the fixed parameters are presented to integration in calculus. Therefore, Your material is math and science
with the variable market data. So my by simply applying the two inverse intensive (no surprise, considering
rule is to use only one, or at most two, mathematical operations, one can your rocket science background!).
tunable parameters when developing create a nearly matched filter for Your answer to the above question
a strategy. trading. There are different combi- is a great example of that. Here is
nations of filters and indicators that a two-part question: First, can you
With limiting yourself to two approximate the frequency response recommend a good book for people
tunable parameters, are you also of a matched filter. starting out with digital signal
including any stop-losses or profit The third tip is to expand analysis processing, maybe that focuses
targets in your strategy, as most into the frequency and phase domain. more on concepts as opposed to
traders do? If those values are also Most traders are familiar with the the detailed math? Next, how
optimized or tuned, then you could squiggly lines of indicators in the can non-math-inclined traders
have four parameters total. Or, do time domain. Those squiggly lines best utilize your work in digital
you mean a limit of two total for the have a direct representation in the fre- signal processing to help them be
whole strategy? quency domain as well. The chart in a successful trader?
I would prefer to not use stop-loss Figure 1 of the
rules in my strategies because the amplitude and
stop-loss interferes with the perfor- phase response
mance of the trading rules. Having of a relatively
said this, I am not completely oblivi- narrow band
ous to real-world considerations. So bandpass fil-
my strategies include stop-losses that ter illustrates
are merely disaster stops. They are my point. The
set on the basis that they are rarely green line is
hit, and therefore have minimum the amplitude
interaction with my trading rules. response (left
Therefore, I don’t count a disaster axis). The blue
stop as a tunable parameter. line is the phase FIGURE 1: AMPLITUDE AND PHASE RESPONSE OF A RELATIVELY NARROW
response (right BAND BANDPASS FILTER
30 • April 2023 • Technical Analysis of Stocks & Commodities
DSP is a relatively complicated opposite mathematical
subject, requiring advanced math- function—taking the in-
ematics. But the necessity to mini- tegral of the band-limited My approach embraces swing,
mize computational lag in trading signal. Integration is the or reversion to the mean,
applications means that only a tiny equivalent of summa- trading. I do this because the
fraction of the entire DSP subject is tion and summation is
used. I would advise traders not to the basically the same
algorithmic approach offers
try to learn all about DSP, but to just as lowpass filtering. The a better chance of having a
get a general understanding of the result of using the two op- higher probability of winning
concepts. So, rather than recommend- posite calculus operations trades. Trend trading typically
ing a book, traders can read my DSP is an approximation to a offers a higher probability of a
tutorial at https://www.mesasoftware. statistically matched filter
com/DSPTutorial.htm or review the in the frequency domain. larger profit factor.
tutorial found at www.micromodeler. This matched filter can be
com/dsp. tuned using combinations
Just don’t be intimidated by tech- of highpass and lowpass filters. on risk, and that means that losses are
nology. Learning a little bit about DSP I know the concept is difficult for inevitable. But taking a loss in real
is a whole lot easier than memoriz- traders to get their mind around, but money is a lot different than looking at
ing a bunch of patterns or trying to once you master the concept, the rest drawdown on a hypothetical histori-
understand the relationship between of the application of DSP is just tun- cal study. Taking a loss is tough, and
price and volume. One key feature of ing simple filters. a trader must be prepared for it.
DSP is that it exploits the duality of All of this also means that an im-
the time domain and the frequency Over the years, you have seen portant key to successful trading is to
domain. That is, the characteristics of many successful and unsuccessful do thorough research before trading
the squiggly lines in the time domain traders. What do you think is the is begun. The research involves not
can be explained in terms of filters most important key to successful only the probability of success of the
in the frequency domain. trading? selected strategy, but also the impact
I think this is a profound overview Without question, the single most of the losses.
of DSP applied to trading: Market important key to successful trading
data are fractal and has a pink is money management. It is simple. For those wanting to learn more
noise spectrum. That means that the You have to have enough capital to about your money management
amplitude of the cyclic component stay in the game. That means a suc- thoughts and practices, can you
swings are in direct proportion to cessful trader needs to understand expand upon how you perform
their wavelength. A reasonable ap- his capability to absorb losses. This money management, or point
proximation is that the cyclic swing capability includes both financial and readers to an article or book chapter
amplitudes increase at the rate of 6 psychological aspects. you wrote on the topic?
dB per octave. Since the spectrum On the financial side, a trader’s ac- Money management is not my
components do not have equal ampli- count must be sufficiently capitalized forte. I think the primary objective
tude, cyclic analysis is possible only to fully implement the strategy being of money management is to stay
if the spectrum is equalized. The followed. In trading futures, that alive so you can trade another day.
spectrum can be equalized by taking capability means having a respect So I simply approach the subject with
a simple difference of successive data for the effect margin can have on the the question of how many consecu-
samples, which is approximately the downside. If you get a margin call, it tive losers can I afford to take. That
same as taking a derivative in calcu- is impossible to continue following number, times the average loss per
lus. The derivative has a frequency your strategy without the influx of trade and initial margin, is the amount
response of −6 dB per octave, which more capital. of capital I must have to trade. I use
provides the equalization. The result On the emotional side, traders must ten consecutive losers as my rule
of taking the difference is a band- realize that their role in the market is because the probability of this event
limited signal (that is, an oscillator). to provide capital so that producers is vanishingly small.
The information in the band-limited and consumers can mitigate their
signal can be recovered by using the risks. That means the trader is taking I find it very interesting that a
April 2023 • Technical Analysis of Stocks & Commodities • 31
ing is synonymous with a cycles tutorial and a DSP tutorial,
curve fitting. So, if you as well as many of the more recent
Without question, the like curve fitting you will technical articles I have written.
single most important key love AI. No matter how
you slice it, AI is pattern Thank you John, not just for this
to successful trading is matching on steroids. interview, but for all the work
money management. Technology will bring you’ve contributed to trading over
more sophistication to the the years. Your legacy in trading (or
art of trading. Successful should I say “lagacy”) will last for
“numbers” guy like yourself, with traders will be forced to decades to come.
so much research into DSP for acquire skills in signal processing and
trading, highlights the importance probabilities of outcomes. Traders of Kevin J. Davey may be reached at
of emotions and psychology for tomorrow probably will become the kdavey@kjtradingsystems.com.
good trading. Do you have anything ones we call quants today.
(books, articles) that you have Further reading
written or read that have really Do you think retail traders who Ehlers, John F. [2013]. Cycle Ana-
helped you emotionally? do not embrace these advanced lytics For Traders, John Wiley
Nope. The numbers protect you concepts will be able to succeed? & Sons.
against emotions. You just have to Of course retail traders can succeed [2001]. Rocket Science For
understand that losses are part of without quant skills because, at its Traders, John Wiley & Sons.
trading. You must also respect lever- core, trading is an art. But success [1994]. “The Bandpass In-
age when trading futures. One way of is simply a matter of statistics. By dicator,” Technical Analysis of
sidestepping many emotions is to put using technology, one has a much Stocks & Commodities, Volume
your computer on autotrade and don’t higher probability of success. It takes 12: September.
even look at the results until the end a mountain of experience to be a [2014]. “Predictive And Suc-
of the day or end of the week. successful seat-of-the-pants trader cessful Indicators,” Technical
using skills that are nearly impos- Analysis of Stocks & Commodi-
For many years you have been sible to quantify, and many traders ties, Volume 32: January.
at the forefront of incorporating burn out before they acquire those [2021]. “A Technical Descrip-
advanced concepts like digital skills. Then there is the emotional tion Of Market Data For Traders,”
signal processing into trading. What and psychological aspect of trading. Technical Analysis of Stocks &
advanced concepts do you think will Without technology, trading losses Commodities, Volume 39: May.
dominate trading the next 10–20 are closely linked to personal fail- [2021]. “Windowing,” Tech-
years? Machine learning, artificial ure because the trader blames the nical Analysis of Stocks &
intelligence, etc. losses on bad decisions. Then, the Commodities, Volume 39: Sep-
I am fond of saying that artifi- sense of failure ultimately leads to tember.
cial intelligence is better than real abandonment of trading altogether. Montevirgen Karl [2019]. “Market
ignorance—but not by much. Com- On the other hand, knowing that the Data Insights With John Ehlers,”
puters are really, really dumb. They probability of losses is just part of the interview, Technical Analysis of
have no capacity to draw inferences. game, traders using technology avoid Stocks & Commodities, Volume
Anyone who has done even a little the personal involvement. So, using 37: September.
programming knows that computers technology improves the probability Gopalakrishnan, Jayanthi [2004].
are perversely literal. Computers can of success. “John F. Ehlers of MESA,” in-
make blazingly fast calculations and terview, Technical Analysis of
have a semi-infinite memory, which Now that you are wrapping up a long Stocks & Commodities, Volume
makes them ideal for tasks like pat- and successful career, will traders 22: January.
tern matching. Pattern matching is still be able to access your website, • https://www.mesasoftware.com/
useful for applications like facial rec- software, and work? DSPTutorial.htm
ognition, voice recognition, or even I am keeping my website https://me- • www.micromodeler.com/dsp
making estimates of the best chess sasoftware.com active as a resource
moves. In trading, pattern match- for algorithmic traders. It contains
32 • April 2023 • Technical Analysis of Stocks & Commodities
MARKET RAP
THE WORLD OF RETAIL TRADING
Emilio Tomasini is an adjunct professor of corporate finance at the
University of Bologna in Italy and is a professional trader. He has au-
dited over 5,000 accounts of traders during 13 years of a real-money
trading competition, giving him unique insights into what helps a retail
trader to succeed. He has expertise in technical analysis and trading
Emilio Tomasini
system design. In this column, he shares his sometimes “unserious”
thoughts on serious topics in finance. In his writings, he hopes to help the retail trader better understand the leap
from unprofitable to profitable trader, firmly believing that the right answers can come only if the right questions
are asked. At his website at www.emiliotomasini.com, he offers some of his expertise in a free video course.
LOOK TO EXPLOIT PRICING AND As with most collectors, I often trading—price inefficiencies.
MARKET INEFFICIENCIES find myself surfing maniacally in Looking for price inefficiencies in
(Or, How I Apply Trading Method- the online public auctions all around stock and futures trading is a difficult
ologies To Antiques On Ebay) the world, mostly on eBay, in the concept, so I’ll use helmet-collecting
Being a trader is a kind of obsession. continual hunt for the lucky punch. as an example, a simpler topic.
But oftentimes, the skills involved in In trading, however, we know that On eBay, a pricing inefficiency
trading give you a way to understand “lucky punches” do not exist—it’s only can occur when a seller does not
realities in life that go beyond most price patterns that exist, and we know know the true value of the item. But
people’s comprehension of them. that patterns tend to repeat. A good nowadays, with so much information
I want to make an admission, even trader is somebody who consciously online everywhere and the transpar-
though it could very well have great (systematic trader) or unconsciously ency it brings, it seldom happens that
consequences for my professional (discretionary trader) is able to identify somebody would list an item for sale
career in the financial industry: I am such patterns in the market’s action without first researching comparable
an eBay buyer. and is able to profit from them. items for sale. It only takes a few clicks
That is to say, beyond being a trader to look at similar items already listed
in the financial markets, I am also a The skills involved to see what the seller is asking.
collector. My object of affection is with trading give you In theory, the law of the unique price
military helmets. I really appreciated applies so that all the same helmets
a recent online lecture by Aswath
a way to understand will have the same price in the mar-
Damodaran, a real guru in corporate realities in life that go ketplace. But in reality, discrepancies
evaluation and a professor at New beyond most people’s occur, and not all information is
York University. In the lecture, he in- comprehension of them. known, so mispricing may occur.
cluded “arts and antiques” among the Here’s an example from my eBay
assets that he considers to be in good When I am surfing on eBay and experience. One time I saw a col-
company with real estate, bonds, stock the other public online auctions, I am lection of helmets for sale that were
shares, and so on. Antique military always wondering what the statistical described as all replicas. There were
helmets are in the “militaria” category pattern is that I am looking for. In almost 100 helmets in the collection,
of the antiques sector, and military other words, what pattern will allow in the German WWII style, presum-
helmets represent a large part of this me to build a valuable helmet collec- ably all copies and fakes, or there were
category. I won’t go on too much about tion while paying less than the price some doubts about their originality; in
it. However, Professor Damodaran’s that other collectors would pay? To any case, not real antiques. A serious
lecture inspired me to think about accomplish that, I know it can’t just antiques collector would pass right
and write about some of the pricing be a matter of me being interested in over this listing dismissively, not be-
mechanisms and tendencies that I see this item or that item. So what is this ing interested in putting out money
at play in both the online antiques pattern that drives me in this marvel- for reproductions or inauthentic or
auction marketplaces like eBay and ous hunt for helmets and makes my fake items. However, in examin-
the financial markets. There are les- collection valuable? ing the collection more closely, I
sons from the eBay marketplace that It turns out to be the same thing that
traders can benefit from. traders look for in stock and futures Continued on page 35
April 2023 • Technical Analysis of Stocks & Commodities • 33
Futures For You
INSIDE THE FUTURES WORLD
Want to find out how the futures markets really work? Carley Garner is
the senior strategist for DeCarley Trading, a division of Zaner, where she
also works as a broker. She has written five books on futures and options
trading, with the latest being Trading Commodity Options...With Creativ-
ity (July 2020), as well as A Trader’s First Book On Commodities (third
edition, October 2017) and Higher Probability Commodity Trading (July
2016). Garner also authors widely distributed e-newsletters; for a free
subscription, visit www.DeCarleyTrading.com. To submit a question, email
her at info@carleygarnertrading.com or via www.DeCarleyTrading.com.
Selected questions will appear in a future issue of S&C.
Carley Garner
MARKET RAP
and peaked near $1,700 in May of can distort prices at times, but a lack
U
In other words, the DDr tells us that the strength of
se price patterns in a trading system? Yes, but the sellers pushed the market down to close the session
never as a starting point. near the lows reached.
At Unger Academy, we teach when and how To check if yesterday’s close was near the session’s
to apply price patterns to different trading ap- low, we’ll use the following code:
proaches. In this article, we’ll discuss the “day
drop”—a downtrend filter that we’ll apply to (closeS(1)-lowS(1)) < DayDropValue*(highS(1)-lowS(1))
a well-diversified basket of instruments, and
VJOM/SHUTTERSTOCK
then test with a real strategy on the most liquid market where the parameter DayDropValue can take on a value
in the world, the S&P 500. between 0 and 1 and tells us the degree of strength of
our DDr: the smaller the DayDropValue, the stronger the
36 • April 2023 • Technical Analysis of Stocks & Commodities
PRICE PATTERNS
FIGURE 2: DAY DROP VALUE SET TO 35% OF THE DAY’S RANGE. In this
example, the DayDropValue is set to 0.35, which provides a reference value
FIGURE 1: THE DAY DROP PRICE PATTERN. A daily bar is called a “day drop” of 35% of the range. There will be a DDr only if yesterday’s closing price was
(DDr) when its closing is at the lower end of the trading range. Here, the daily below this value.
close is very close to the daily low, and yesterday’s session closed with a very
low value compared to the whole day’s range.
input: DayDropValue(0);
var: countDDr(0), countsession(0),
A daily bar is called a “day
dateInDateTimeFormat(0), datereadable(""); drop” (DDr) when its closing
is at the lower end of the
dateInDateTimeFormat = ELDateToDateTime(date); trading range.
datereadable = FormatDate("dd-MM-yyyy", dateInDate-
TimeFormat);
April 2023 • Technical Analysis of Stocks & Commodities • 37
produced and relate them to
the total number of sessions, countsession countDDr countDDr countDDr
all of which while evaluating
different DayDropValues.
As we all know, as the Day-
DropValue decreases, we’ll
have fewer DDrs; if we use FIGURE 4: FILTERING BY DAY DROP PATTERN. From this table, we see that using a DayDropValue between 15%
this pattern to filter our market and 25% leads to significant filtering.
entries, the number of trades
will be set proportional to the
DayDropValue.
slb=sessionlastbar;
MP=marketposition;
if daydrop and Time<1500 and (mydow = myday1 or mydow MaxDays>0 then begin
= myday2) and oktrade then buy next bar market; if Time>=1530 and Time<1600 then sell next bar market;
end;
We’ve inserted an additional condition (Time<1500),
which will allow us to trade on Tuesday and Thursday By optimizing MaxDays with the data available dur-
starting at 0:00 (exchange time); in other words, we’ll ing the initial development, I found leaving the trades
enter the first bar shortly after the stroke of midnight. open up to a maximum of 4 sessions beneficial. So let’s
With the introduction of this new time window, we’ll get set MaxDays=4 and observe the new results, seen in
the metrics shown in Figure 7. Figure 8.
The number of trades hasn’t changed, as we’ve only The change of strategy from intraday to multiday has
moved our entries forward by a few hours. The NetProfit had a substantial impact on the system: we’ve indeed seen
has remained almost the same (and so has the average an increase in Max DD, but NetProfit has increased by
trade), but we have significantly reduced the Max DD more than 60%, and the average trade has risen by about
of the strategy. 80%, reaching an excellent level for the instrument on
which we’re trading.
Can we improve the system further? Can we go even further? The strategy is very simple
We trade intraday, so we close every trade at the end of
the session. What would happen if we gave the trades
more time to develop? To answer this question, let’s enter
a new MaxDays input and a new DaysInTrade variable Let’s now look at the extent to
and replace the exit command setexitonclose with the which DDr can filter, using some
last 4 lines in the following code:
simple code that calculates on
input: MaxDays(0); daily bars the percentage of
var: DaysInTrade(0), occurrences on different markets
since 2008.
if MP<>MP[1] and MP<>0 then DaysInTrade=1;
if marketposition<>0 and DaysInTrade>=MaxDays and
April 2023 • Technical Analysis of Stocks & Commodities • 39
and already gives us excellent metrics; adding special
conditions could improve it, but it would also increase
the risk of overfitting. FIGURE 9: ADDING A TAKE-PROFIT. Would adding a take-profit improve
We, therefore, decided not to introduce any additional drawdown? The results of the test are shown here. The Max DD is indeed
entry rules but only see if using a take-profit could help lowered. Meanwhile, the net profit and average trade are improved, making
us contain the Max DD of the system. the take-profit a good addition to the strategy.
The results shown in Figure 9 are the results after in-
troducing a take-profit of $4,000. As you can see, we’ve
lowered the Max DD while increasing the NetProfit and
average trade, so we’re satisfied with this choice.
MULTICHARTS
smoothly.
Andrea Unger is a full-time professional trader, president FIGURE10:EQUITY CURVE FOR RESULTING EXAMPLE TRADING SYSTEM.
of The Unger Academy, and author of The Unger Method. The hypothetical equity curve is shown here for the trading strategy result-
He is a four-time World Trading Champion (2008, 2009, ing from using the rules and conditions discussed in this article for trading
2010, and 2012), an honorary member of SIAT (Italian long-only positions on the emini S&P 500 contract (ES). The equity curve is
Society of Technical Analysis, a branch of IFTA), and based on data from 2008 to the present, covering more than five years of
speaks throughout Europe, America, Australia, and out-of-sample data.
Asia. He may be reached at Andrea@UngerAcademy.
com. The Unger Academy provides services to traders,
including individuals, to help them improve their ap-
proach to trading (more information can be found at We’ve used DDr as a trading
https://autc.pro/tasc3). filter to trade only long
The code given in this article is available in the Article positions on the @ES, and this
Code section of our website, Traders.com. pattern has proven to be very
effective.
Further reading
Unger, Andrea [2021]. The Successful Trader’s Guide To
Money Management: Proven Strategies, Applications,
And Management Techniques, Wiley Trading. Filter,” Technical Analysis of Stocks & Commodities,
[2021]. The Unger Method: The Winning Strategy Volume 41: February.
Of The 4-Time World Trading Champion, The Boss
Books. ‡MultiCharts
[2022]. “Filters On The Test Bench,” Technical ‡See Editorial Resource Index
Analysis of Stocks & Commodities, Volume 40:
November.
[2023]. “The Outside Bar: A Rare And Powerful
40 • April 2023 • Technical Analysis of Stocks & Commodities
CMT SYMPOSIUM APRIL 26–29, 2023, explore first principles of the markets have occurred in the markets and in
50-YEAR ANNIVERSARY OF and the utility of technical analysis the world over the past 50 years.
CMT ASSOCIATION in any investment-selection model. Today, the CMT serves more than
The 2023 CMT Association Sympo- Attendees can expand their profes- 10,000 members and candidates, with
sium will be held in New York City sional network and gain new skills monthly educational meetings and
on April 26–28, 2023. This year’s that they can take back to their firms, guest speakers, an annual award to
symposium will celebrate the 50-year their clients, and their portfolios. recognize outstanding contributions
history of the CMT Association and The cost to attend ranges from to the field, and national and inter-
the history of the industry during this $1,499 to $1,899 for CMT Associa- national chapters. The association
period, with a focus on the evolution tion members or $1,649 to $2,049 offers rigorous credentialing, profes-
of technical analysis. for nonmembers. sional ethics standards, and continu-
The symposium will bring together CMTAssociation.org/events/symposium ing education requirements.
a diverse array of speakers across This year’s symposium will honor
different asset classes and arenas of 50-year history of the CMT the heritage and innovation of those
the financial industry. Sessions will Association who contributed to the field over
address the ETF ecosystem, market The CMT Association was formed to the years, all while the association
volatility variation, cross-asset cor- advance the discipline of technical strives to cultivate the community
relations, data visualization methods, analysis and advocate for association for the future.
decision theory, and machine learning members industry-wide. The asso- CMTAssociation.org
algorithms. The sessions are designed ciation, formerly called the Market
to give attendees an understanding of Technicians Association, formed
the forces at play when asset prices in the late 1960s when a group of
and valuations diverge. equity research analysts recognized
This year’s symposium will include the unwarranted gap between funda-
a celebration of several legends in the mental and technical analysts. They
field of technical analysis on the floor wanted to stand up for professional
of the New York Stock Exchange on recognition of technical analysts. The
Thursday evening. organization has sought to elevate
This annual event is an opportunity investors’ skills for mitigating market
for portfolio managers, registered risk and maximizing return in capital
investment advisers, asset allocators, markets. This mission continues to
strategists, traders, and analysts to this day despite all the changes that
T
price action in COIN soon followed. or ETF chart you’re trading.
he problem with many This is a rare, valuable lead indicator
indicators is that they are setup. Once you see the red ATR line Step 3: Use an initial stop-loss of
lagging, which is too late trend up for three or more days, you no further than $2 under your entry.
for active traders. The could enter for a strong uptrending Once you do enter, you can scale in
strategy I will discuss breakout. every several days, as long as the
here produces trading signals ahead trend remains intact to the upside.
of time. The strategy is based on a Step-by-step action plan
simple 14-step average true range Here’s how you can start using this Step 4: Keep an eye on the slope of
(ATR) indicator. strategy: the line of the ATR; once it starts
eSIGNAL
FIGURE 1: TRADING THE ATR REVERSAL, COIN. This shows an example of buying the pivot as price action goes up. The reversal in the red ATR line can be seen
at the bottom of the chart; price soon followed.
42 • April 2023 • Technical Analysis of Stocks & Commodities
to pivot back downwards, then con-
sider exiting your position. Using ATR to spot upside breakouts in this strategy
is different, because it combines trend direction
Why this technique works along with an increase in average true ranges.
The ATR was originally designed
to indicate when daily ranges are
increasing or decreasing. Using it to Trade management tips Ken Calhoun moderates a popular
spot upside breakouts in this strategy As usual, we can use this momentum live trading room for active traders.
is different, because it combines trend strategy to add to winning positions He is the founder of TradeMastery.
direction along with an increase in by scaling in every few days, as long com, an interactive webinar site
average true ranges. This built-in as price keeps trending up. Exit using for active traders, and is a UCLA
combination can be even more effec- typical signals, such as the shooting alumnus.
tive than classic ATR signals. star seen on February 5 in the chart
in Figure 1.
EHLERS/JUST IGNORE THEM However, care should be taken not to get carried away
Continued from page 12 and start folding desired signals back onto the observable
spectrum.
Then, that gap value is mathematically removed from
every sample during the day. This technique removes the John Ehlers, a Contributing Editor to STOCKS & COM-
opening price gap from the overnight period and provides MODITIES, is a pioneer in the use of cycles and DSP (digital
a more continuous function for analysis. The sampling signal processing) technical analysis. After four decades
is conducted only on the hour and at the session closing of dedication to advancing the field of digital signal pro-
time. Otherwise, the previous value of degap is held. So cessing and offering products and services to traders, he
the data is effectively sampled every four bars. The little is retiring from the company he founded, MESA Software.
jitter in the sampling clock due to the time offset of the An interview with him highlighting some of his important
first and last bar of the day doesn’t matter much because research and developments in quantitative and technical
the data are not coherent. analysis appears elsewhere in this issue. Ehlers can be
The beginning date for the indicator is provided as an reached through his website at MESAsoftware.com.
input. This is required because the impact of the opening
gap is cumulative, and the degapped undersampled data The code given in this article is available in the Article
can drift from the absolute values of the prices. Code section of our website, Traders.com.
Just to demonstrate the smoothing process of undersam-
pling, a double moving average type indicator is shown in See our Traders’ Tips section beginning on page 44
Figure 3, using Hann windowed FIR filters. for implementation of John Ehlers technique in various
technical analysis programs and trading platforms. Ac-
conclusion companying program code can be found in the Traders’
I have shown that undersampling removes the high- Tips area at Traders.com.
frequency components in price data. Elimination of these
components is done with less lag than that of conventional fuRtheR Reading
smoothing filters. Quantization lag is only half the under- Ehlers, John F. [2014]. “Predictive And Successful Indica-
sampling step size. This magic is possible because the tors,” Technical Analysis of StockS & commoditieS,
market data is fractal, so the aliased components have a Volume 32: January.
small amplitude relative to the desired signal components. Ehlers, John F. [2021]. “Windowing,” Technical Analysis
Further, the folding of the aliased component into the of StockS & commoditieS, Volume 39: September.
observable spectrum is performed noncoherently.
Undersampling can also be applied to intraday data,
removing the overnight gap openings as well.
The degree of undersampling is designer’s choice.
April 2023 • Technical Analysis of Stocks & Commodities • 43
The focus of Trad- •
Traders.com S&C Magazine
ers’ Tips this month is Traders’ Tips
John F. Ehlers’ article in
this issue, “Just Ignore At Traders.com you can also right-click on any chart
Them: Undersampling to open it in a new tab or window and view the chart
The Data As A Smooth- at a much larger size.
ing Technique.” Here,
we present the April The Traders’ Tips section is provided to help readers
2023 Traders’ Tips code implement a selected technique from an article in this
with possible implementations in various software. issue or another recent issue. The entries here are con-
The code for the following Traders’ Tips selections is tributed by software developers or programmers for
posted here: software that is capable of customization.
inputs:
Price( numericseries ),
Length( numericsimple );
F TRADESTATION: APRIL 2023 TRADERS’ TIPS CODE
In his article in this issue, “Just Ignore Them: Undersampling variables:
The Data As A Smoothing Technique,” John Ehlers explains Count( 0 ),
that data smoothing is often used as a means to help avoid Coef( 0 ),
trading whipsaws. While this can result in fewer trading Filt( 0 );
signals, it can also result in a lag in those trading signals. Filt = 0;
In the article, Ehlers describes how undersampling coupled Coef = 0;
with Hann-windowed finite impulse response (FIR) filters
can be used to remove high-frequency components in price for Count = 1 to Length
data, resulting in less lag than that of traditional smoothing begin
Filt = Filt + (1 - Cosine(360 * Count / (Length +
filters. 1))) * Price[Count - 1];
Coef = Coef +
Function: $Hann (1 - Cosine(360 * Count / (Length + 1)));
end;
{
TASC APR 2023 if Coef <> 0 Then
Function: Hann Windowed Lowpass FIR Filter $Hann = Filt / Coef;
(c) 2021-2022 John F. Ehlers
} Indicator: Undersampled Double MA
{
TASC APR 2023
Undersampled Double MA Indicator
(c) 2022 John F. Ehlers
}
inputs:
FastLength( 6 ),
SlowLength( 12 );
variables:
Sample( 0 ),
FastAvg( 0 ),
SlowAvg( 0 );
Sample = Sample[1];
{
TASC APR 2023
Undersampled Intraday Double MA Indicator
(c) 2022 John F. Ehlers
}
inputs:
BegDate( 1221117 ),
FastLength( 20 ),
SlowLength( 40 );
variables: FIGURE 2: WEALTH-LAB. This sample chart demonstrates a 6- and 12-period Hann filter
Gap(0 ), (5-period undersampled) on the daily chart of the emini S&P 500 futures (ES=F). Data provided
Degap( 0 ),
by Yahoo! Finance.
FastAvg( 0 ),
SlowAvg( 0 );
Degap = Degap[1]; various tools in Wealth-Lab such as Building Blocks (to cre-
ate no-code trading strategies), the Indicator Profiler (which
if Time = 645 then tells how much of an edge an indicator provides), or our
begin Strategy Optimizer.
Gap = Close - Degap[1];
Degap = Close - Gap; With Wealth-Lab’s ability to combine different indicators
end; in a GUI wizard, Hann filters can even be used as a “smooth-
er” to your favorite indicator like MFI, RSI, or momentum.
if Time = 800 or Time = 900 The techniques, common to moving average interpretation,
or Time = 1000 or Time = 1100 apply here as well.
or Time = 1200 or Time = 1315 then
Degap = Close - Gap; Prototyping a trading system, including complex ideas,
doesn’t take much effort with the Building Blocks feature. If
if Date < BegDate then you’re not familiar with Wealth-Lab, our web-based back-
Degap = Close; testing engine is free to use. Create a system (for example,
//Find Fast Average using Hann FIR filter applying the Hann filter to a price or indicator of choice) in
FastAvg = $Hann(Degap, FastLength);
//Find Slow Average using Hann FIR filter its user-friendly interface and run backtests of your strategy
SlowAvg = $Hann(Degap, SlowLength); right in the browser. As a natural next step, your strategy
becomes instantly available in the Wealth-Lab desktop ap-
Plot1(FastAvg, "Fast Avg"); plication for in-depth use. And if the strategy turns out to be
Plot2(SlowAvg, "Slow Avg"); good enough, you could choose to publish it for the benefit
of the Wealth-Lab community of members. Strategies pub-
A sample chart is shown in Figure 1.
lished by community members can be found at https://www.
This article is for informational purposes. No type of
wealth-lab.com/Strategy/PublishedStrategies.
trading or investment recommendation, advice, or strategy —Gene Geren (Eugene)
is being made, given, or in any manner provided by TradeS- Wealth-Lab team
tation Securities or its affiliates. www.wealth-lab.com
—John Robinson
TradeStation Securities, Inc.
www.TradeStation.com
F NEUROSHELL TRADER: APRIL 2023 modities section of the NeuroShell Trader free technical
TRADERS’ TIPS CODE support website to download a copy of this or any previous
Using undersampling of the data as a smoothing Traders’ Tips.
technique, as described by John Ehlers in his article in —Ward Systems Group, Inc.
this issue, “Just Ignore Them,” can be easily implemented sales@wardsystems.com
www.neuroshell.com
in NeuroShell Trader by combining some of NeuroShell
Trader’s 800+ indicators. To implement the undersampled
intraday double MA indicator, select “new indicator” from
the insert menu, and use the indicator wizard to set up the F THE ZORRO PROJECT: APRIL 2023 TRADERS’
following indicators: TIPS CODE
All smoothing indicators, such as the simple
Gap Sub(DayOpen(Date,Open,0),DayClose(Date,Close,1)) moving average (SMA) or lowpass filter, trade more lag for
CumGap CumSum( IfThenElse(A not equal B(Momentum( more smoothing. In this issue’s article “Just Ignore Them,”
Gap, 1), 0), Gap, 0) ,0) John Ehlers suggests undersampling the price curves for
PriceSub(Close, CumGap)
SampleFreq 4 achieving a better compromise between smoothness and
Degap SelectiveAvg(Price,A=B(Remainder(CumSum(Ad lag. We can check that out by applying a Hann filter to the
d2(1,0),0), SampleFreq),0),1) original price curve and a five-fold undersampled curve.
FastAvg Hann(Degap, 20) The C code for the Hann filter, from Ehlers’ article, is:
SlowAvg Hann(Degap, 40)
var Hann(vars Data,int Length)
Note that Ehlers’ Hann filter indicator is created using {
NeuroShell Trader’s ability to call external dynamic linked var Filt = 0, Coeff = 0;
libraries (DLLs). After moving the Hann filter code given in int i;
for(i=1; i<=Length; i++) {
the article to your preferred compiler and creating a DLL, Filt += (1-cos(2*PI*i/(Length+1)))*Data[i-1];
you can insert the resulting indicator as follows: Coeff += 1-cos(2*PI*i/(Length+1));
}
1. Select “new indicator” from the insert menu. return Filt/fix0(Coeff );
2. Choose the External Program & Library Calls }
category.
The fix0 function in the denominator has the purpose of
3. Select the appropriate External DLL Call indicator.
working around division-by-zero issues. We will now apply
4. Set up the parameters to match your DLL.
the Hann filter to the undersampled SPY price curve:
5. Select the finished button.
void run()
Figure 5 demonstrates the undersampled intraday double {
moving average indicator.. StartDate = 20220101;
Users of NeuroShell Trader can go to the Stocks & Com- EndDate = 20221231;
BarPeriod = 1440;
plot("Hann6",Hann(Samples,6),LINE,MAGENTA);
plot("Hann12",Hann(Samples,12),LINE,BLUE);
plot("Hann",Hann(seriesC(),12),0,DARKGREEN);
}
T
rading liquidity is often over- very high volumes. The greatest number three-year period. Thus, all numbers in
looked as a key technical of dots indicates the greatest activity; this column have an equal dollar value.
measurement in the analysis futures with one or no dots show little Columns indicating percent margin
and selection of commodity activity and are therefore less desirable and effective percent margin provide
futures. The following explains how to for speculators. a helpful comparison for traders who
read the futures liquidity chart pub- Courtesy of CBOT wish to place their margin money ef-
lished by Technical Analysis of Stocks ficiently. The effective percent margin
& Commodities every month. is determined by dividing the margin
value ($) by the three-year price range of
Commodity futures contract dollar value, and then multiply-
The futures liquidity chart shown be- ing by one hundred.
low is intended to rank publicly traded
futures contracts in order of liquidity. Stocks
Relative contract liquidity is indicated Trading liquidity has a significant ef-
by the number of dots on the right-hand fect on the change in price of a secu-
side of the chart. rity. Theoretically, trading activity can
This liquidity ranking is produced by serve as a proxy for trading liquidity
multiplying contract point value times All futures listed are weighted equally and equals the total volume for a given
the maximum conceivable price motion under “contracts to trade for equal dol- period expressed as a percentage of the
(based on the past three years’ historical lar profit.” This is done by multiplying total number of shares outstanding. This
data) times the contract’s open interest contract value times the maximum pos- value can be thought of as the turnover
times a factor (usually 1 to 4) for low or sible change in price observed in the last rate of a firm’s shares outstanding.
TRADERS'
RESOURCE
The information in Traders’ Resource is the most accurate at the time of posting and is subject to change. Because the vendors posting to Traders’ Resource are responsible for their own listing, Technical Analysis, Inc. declines any and all
liability for any representations made by the businesses and individuals listed. Nor can Technical Analysis, Inc. endorse any business or individual listed on Traders’ Resource. Technical Analysis, Inc. makes no warranties, express or implied,
as to the accuracy and reliability of claims herein. You agree to release Technical Analysis, Inc., together with its respective employees, agents, officers, directors and shareholders, from any and all liability and obligations whatsoever in
connection with or arising from your use of Traders’ Resource. If at any time you are not happy with the information posted to Traders’ Resource or object to any material within Traders’ Resource, your sole remedy is to cease using it. This
list is updated frequently. If you are aware of a business that should be listed, please email us at Editor@Traders.com.
CHATGPT trading algorithm, and it is written in strategy. Maybe one day it will. And
Everyone is talking about ChatGPT my requested language, TradeStation it certainly could create a profitable
for algo trading. Can you explain EasyLanguage. The code actually strategy by chance.
how that might go? verifies in TradeStation, So this is a So, at least right now, ChatGPT
ChatGPT seems to be today’s working strategy. Nice! is not the answer to developing
hot topic in many fields, including That said, just because I asked it profitable algo strategies. But it
algorithmic trading. For those of you for a “good” (meaning profitable) could be a useful tool for the trader’s
who do not know, ChatGPT is an strategy, that doesn’t mean it actually toolbox. Here’s how:
artificial intelligence (AI) tool that is good. In fact, I tested this strategy
was recently released to the public with various markets, and as is, 1. ChatGPT can write code for
(https://openai.com/blog/chatgpt). without any code changes, it generally many trading platform languag-
You ask it a question and ChatGPT loses money. es. For a new programmer, this
will provide an answer. As we will In other words, ChatGPT is smart, can make it very useful. Simply
see, it will not always be the right but not that smart. It does not know give it general instructions such
answer, but it will be an answer. how to create a profitable trading as “provide me breakout strategy
The possibilities for ChatGPT are
endless. High school and college
students have found it to be a great
tool for writing papers and essays,
although that is not really ethical.
Website content creators now have a
quicker way to write in-depth articles.
Many fields are being affected by Chat
GPT—but what about trading?
I decided to give ChatGPT a try
recently. I asked it to give me a good
algo for trading. Figure 1 shows what
it provided.
At first glance, this is pretty
impressive. ChatGPT gave me a
In other words, it
can be a great source
of inspiration, and
most algo traders are
continually looking for
CHATGPT
new strategies. FIGURE 1: CHATGPT-PRODUCED STRATEGY. Here is the response I received from ChatGPT when I
requested it to come up with a good algo strategy for trading.
54 • April 2023 • Technical Analysis of Stocks & Commodities
Algo Q&A
code for NinjaTrader 8” and it 1. It frequently has coding mis-
could provide a good start. takes, which will take time for Given the current status
2. The tool can provide new trading an inexperienced programmer of ChatGPT, I don’t see it
ideas. Prompts like “provide a to debug. eliminating the need for
simple mean reversion strategy” 2. It does not test or validate any
might give the user a whole new code it provides; the trader still algo traders to properly
strategy or group of strategies to has to test the strategy with actual test and validate their
try. In other words, it can be a market data. models.
great source of inspiration, and 3. As more traders utilize it, any
most algo traders are continually good trading ideas the tool comes
looking for new strategies. up with will quickly be shared this tool to experiment and try new ap-
3. ChatGPT can translate from one amongst users—possibly render- proaches out. I suspect as I get better
trading programming language ing the idea ineffective. at asking ChatGPT questions, it will
to another. If you have, for ex- provide better trading strategies. For
ample, NinjaTrader code, you Given the current status of Chat- anyone interested, I’ll be document-
might be able to have ChatGPT GPT, I don’t see it eliminating the ing my ongoing ChatGPT tests on
turn it into, say, EasyLanguage need for algo traders to properly test my YouTube Channel: https://www.
code for use in TradeStation. and validate their models. But at the youtube.com/@AlgoTradingWith-
same time, I do see it making pro- KevinDavey (Playlist “ChatGPT”).
All those good aspects notwith- gramming easier, and also providing
standing, ChatGPT, in its current fresh ideas for a trader to test.
form, is limited for algo traders: For my own trading, I plan on using
ninjatrader.com