January 19, 2016

The objective is to design an end-of-day (EOD) stock trading strategy almost from scratch with, for background, an old trading script that did no trading at all. It was published in 2000, over 15 years ago, author's handle: Glitch. As given by the author:

"The indicator oscillates around zero and registers extreme ratings when prices are trending. Values above 100 indicate a bullish trend, and less than -100 indicate bearish trending. This ChartScript colors the bullish bars blue and the bearish bars red. Congestion bars are black."

This way, I am free to design a trading script based on a given concept. In this case, using Glitch's designed trend index which is achieved by multiplying the rate of change of 3 EMAs of different lookback periods. It is close to a MACD indicator as it also looks for inflection points.

First, the original code:

#1 Original Code

(click chart to enlarge)

The script outputs a trend index composed of the rate of change of the 3 EMAs displayed. It should give anyone some ideas as to how they could make it profitable. The script paints the bars blue or red when they exceed +/- 100, respectively. This also can be used to break the price movements into 3 sections, with a middle one and a moving channel delimited by the above boundaries.

#2 Chart from Original Code

Chart from Original Code

(click chart to enlarge)

The mission is to add trading rules and procedures so as to make it a long-term winner. The transformation will be done on one stock to debug the code and then applied to a 10-stock dataset, the same as I've used in previous tests. A kind of proof of concept. Simulation duration: 5,184 trading days (≈20 years). Note from the above that the trend index does roughly isolate interesting trading areas.

I opted to use the MACD as the technical indicator to set initial trading rules. TradeMACD v01. I did not expect impressive results using MACD over a 20-year testing period. Here is the code snippet used directly from the user manual:

#3 MACD Code Snippet

MACD code snippet

(click chart to enlarge)

It translates to, if the MACD crossover from under its signal line and the MACD is below zero, then buy at market tomorrow at the open. The performance report gave:

#4 MACD Performance Report

MACD performance report

(click chart to enlarge)

There were 102 trades, of which 79 were profitable (77.45% hit rate). Overall profit is not impressive, to say the least. But, I still need some comparative basis, so I added some analyzing code snippets to view behind the scenes and print on the chart the numbers I want to see. Added some cosmetics. The resulting chart spoke for itself:

#5 MACD Chart

MACD Chart

(click chart to enlarge)

I painted bars green if the Trend Index was greater than 100 and rising and, while still above 100, red when falling. As if trying to isolate tops.

The overall performance is dismal. The ending profit is still money, but it took 20 years to get so little. The concept appears good. It still has a 77.45% hit rate! But that is about all I could say positive about it.

What I do not like when examining the above chart? All the trading sections. A CAGR of 0.64% is certainly nothing to brag about! At this rate, it would take 108 years just to double one's money and another 108 years to double again. Definitely a good reason not to touch such a thing.

The above example also illustrates the problem inherent in many trading strategies. Their developers do not seem to want to look at the future and how it will unfold. In the sense that they won't do simulations over the long term, or if they do, won't show them for some evident reason. They don't want people to realize that their trading strategies were doomed from the start, and whatever you paid for such a strategy, it was a total waste. Most importantly, it was a waste of your future, your time, and your money. And that is really terrible. Ok, my rant is done.

Let's go do some serious thinking and modify this strategy to give it not only a purpose but transform it into a hyper-achiever.

The thing I like about the original script is the implied trading zone division. The selling zone could be above Trend_Index > 100 and the buying zone below Trend_Index < -100. The zone in between can be used as a no-trading zone for holding positions or waiting to get in.

This complies with what I published recently: Stock Trading Strategy Mechanics available on Amazon. The book elaborates on trading methods using this kind of 3-zone definition.

Always the same question. Where is the money?

The math of the stock trading game is simple. You choose a stock, make a bet: bet = quantity*price, wait some time (Δt), then choose to close or maintain the bet with either a profit or loss giving: win(lose) = q*Δp where Δp = price(out) - price(in). That's it.

That is all there is, and that is all you can do. You can have the trading interval Δt go from nanoseconds to days to years to decades. You can buy 1 share to millions at a time, you can do 1 to millions of trades with for the only restriction that any of those bets be executable, meaning that you have the money or collateral needed to initiate any trade and that the market can accommodate you.

As a trader, you know from the start that you will not win on every trade. You readily accept averaging things out. To know the total profit (loss) generated, you simply add the result of all the trades: Σ(n)q*Δp where n is a sequenced trade number: i = 1, ..., n. To get the average profit per trade, you divide by the number of trades: (Σ(n)q*Δp)/n, which is the cumulative sum of all the generated profits and losses divided by n the number of trades.

If, on average, (Σ(n)q*Δp)/n is positive, and n is large enough, you might have a repeatable and sustainable edge. Just being able to say this with some corroborating evidence, and technically, you won the game. You could delegate the job to a machine and let it do its thing: let your program gradually pile the averaged-out winnings in your trading account.

Chart #4 above shows the averaged profit/loss: (Σ(n)q*Δp)/n = $267.40 with n = 102 trades.

If I want to improve the picture, I only have 4 areas in which to do this, namely q, Δp, n, and Δt. I do have control over q, even if it is limited by my available trading capital. I could maybe try to control Δt by fixing timed constraints for exits or entries. I have less leeway in controlling n or Δp, as if the trading methodology dictates what those numbers could be.

Still, if I want to improve the scenario, I need to trade more (increase n), make bigger bets (increase q), and go for wider spreads (increase Δp). The mission sounds simple enough.

However, the MACD used has a fixed set of crossings over the 20-year period. Its number of trades is equivalent to its number of crossing the signal line. The more I would increase Δt, the more it would have an impact on reducing the number of trades, which would be counterproductive. However, I am not forced to exit a trade. I could transform the underlying trading philosophy and have the program accumulate shares over the long haul. I could also allow leveraging and use some margin up to a certain limit. I would need more program controls, and that is just code.

The above would improve performance and add to end results.

So the MACD code snippet is changed, one to accept holding on to some positions, and two, to sell nonperforming positions. It is a very crude method but productive nonetheless. Sales will be executed if:

if PositionOpenProfit( Bar, p ) > - 400 then
  if Bar - PositionEntryBar( p ) > 20 then
   SellAtMarket( Bar + 1, p , 'MACD' );

which is saying: if the position lasted over 20 days, and it lost $400, get rid of it, meaning sell at market tomorrow at the open, whatever the price.

The outcome of such procedures could be seen in two ways, one from the performance report and another from the trades report, which can give an idea as to how the strategy behaved over time.

#6 MACD Initial Modifications: Trades

MACD initial modifications: trades

(click chart to enlarge) 

#7 MACD Summary Performance Report

MACD summary performance report

(click chart to enlarge) 

#8 Trading MACD Chart

Trading MACD Chart

(click chart to enlarge)

The above chart (#8) shows a 53-fold improvement over chart #4.

Now, the picture starts to be interesting. We have not done much, but it counted a lot. We can again notice in chart #8 that the MACD is limiting the number of trades, thereby limiting the strategy's potential. Furthermore, to achieve this higher result, it was required to use margin, which ended at 21.20%. The risk was minimal since the lowest equity was down by $1,402 in 1996. At all other times, one could have closed the account and be positive. The ending profit figure is after having repaid the amount under margin: the negative cash reserves. The ending profit ($1,452,366) is the net result of all the trading activity, to which should be added the initial capital. Still, the CAGR is only 11.17%.

How can I push further?

After having accepted the use of some margin, as in the previous example, my next mission was to improve on the number of trades n. The previous chart saw its Δp increase considerably, but its number of trades remained constant due to the MACD's limited number of signal crossings. Based on chart #8, which displays an average win of $24,898 per trade with an average loss of -$386, it would certainly be in my interest to increase the number of trades.

So, I opted to add more entry points. As long as there was cash in the account, I could buy more shares, take additional positions, and, with the use of margin, could leverage performance further if and when needed within the limiting constraints. I also opted to require more profits per position, again increasing Δp. This would also have for a result to reduce the average Δt, simply by making more trades over the same long-term trading interval. The time series is being sliced in more ways than before and in smaller pieces.

What is the outcome of those modifications?

#9 MACD v.02 Multiple Entries & Exits

MACD Multiple Entries & Exits

(click chart to enlarge) 

#10 MACD v.02 Performance Report

MACD v.02 performance report

(click chart to enlarge) 

#11 MACD v.02 Equity Curve

MACD v.02 Equity Curve

(click chart to enlarge) 

#12 MACD v.02 MAE / MFE


(click chart to enlarge) 

#13 MACD v.02 Trade Report

MACD v.02 Trade Report

(click chart to enlarge)

The above 5 charts resume the trading activity over the 20-year time interval. With these last modifications to the original program, I'm well set to do a portfolio-level test, meaning use the other 9 stocks in the usual dataset to confirm what has been extracted from ABT – using the same price data series for all the graphs and charts shown - can also be extracted from other stocks. I will do the 10-stock test, it could as well be for hundreds, it would mostly depend on the size of the initial capital that one could put to work.

The final outcome is quite remarkable, but still, it is not the strategy's limit. It can go further and produce even more. It is a question of regulating what you want to see and what you want to have, starting with what you've got.

I am putting on your shoulders the choice to do what you can versus what's really available. In a sense, going from chart #2 to #5, to #8, to #9 is intrinsically a matter of choice. And my question is: which one do you prefer? They are all accessible. It all depends on the method of play, the understanding that the game, especially this type of game, is not about a trade here and there but about building a long-term portfolio of stocks and building your retirement fund so that you can enjoy life to the fullest.

Look again at chart #9, and read the story it is telling. Starting with an initial capital of $200k, using $10k trading units, the strategy was able to execute 841 trades. 624 of which show an average profit of $16,752 while 217 show an average loss of -$377, with a profit factor of 127.88. The lowest equity was $106,607, which was seen in July 2002. Over its 19.94 years of trading activity, the stock achieved a 22.02% CAGR compared to the stock's 10.85% CAGR, an 11.17% alpha. Not only that, but during this time, 242,735 shares were accumulated in the process, now valued at $9,840,477, to which should be added the ending cash reserves of $731,023 to reach the ending profit of $10,371,499.

All this trading the same data series as in charts #2, #5, and #8. The difference comes from the trading strategy itself. The how the volume is handled. I transformed the original trading strategy to a Buy & Hold variation ready to release held shares if the price was interesting enough.

This is the same kind of thing you will find in my book, where I try to explain how to structure such a methodology. From my point of view, your future wealth is in your hands.

What Next?

The next step will be to show the output of what remains to be done: the 10-stock test over the last 20 years. This will enable answering the question: if it was good for one stock, is it for many? I can give you the answer right now; it will definitely be yes.

I will also make other improvements to this trading strategy before doing the 10-stock test since I expect that the other stocks will also benefit from them.

Created... January 19, 2016,   © Guy R. Fleury. All rights reserved.