pyesetz: (stock)
Pyesetz/Песец ([personal profile] pyesetz) wrote2011-04-13 03:34 pm

I wrote a computer program!

It slices!  It dices!  It juliennes prices!  And don’t you want to know how it works?  No, of course not.  (See obsessive details.)

I had a drawdown a few weeks back, for which the standard response is “stop trading and start analyzing”.  So I wrote an analyzer program, because — unlike stock-trading — that’s something I actually know how to do.  My program looks at weekly historical data for a stock and uses rules to calculate what the buy and sell prices would have been; from those it computes, for each week, how long the stock would have been held if bought then and what the profit would have been.  That was the easy part.

Then I added calculations for various technical indicators such as MACD.  Doing this required that I learn how those indicators really work.  MACD is especially difficult because it is the difference between two exponential moving averages, and EMAs are very sensitive to round-off error.  I don’t know how people managed to calculate these things back in the olden days of pencil and paper: if you make an arithmetic mistake in your EMA, it will continue to screw up your results for more than a year afterward.

To avoid having to write a graphing module for my program, I tried to make my indicators produce the same values as the indicators at StockCharts.com so I can use their free charts to display my results.  This was mostly successul except that I think their values for Parabolic SAR are bogus and I refuse to match them; whenever a stock has a wide-ranging week following by several narrow-range weeks, from then until the next stop-out the pSAR values shown on their charts are just way too low in my opinion.  But I got everything else to match, down to at least one decimal place and usually two.

Now the creative part: I assigned limit values for each indicator.  If the indicator was on the wrong side of its limit, that meant the stock should not be bought.  For each week, if none of the indicators said “do not buy”, then my program would pretend to buy the stock and see how it would have done.  Then I used a technique much like simulated annealing to adjust the limit values for maximum gain.  Result: only 1% of weeks were selected for purchase and those weeks yielded a 6% gain on average.  Then I doubled the number of stocks being analyzed (from 50 to 100).  Result: average purchase yielded a loss!  So I tweaked the limit values some more and got the average gain up to 4% per purchase.

Now clearly this system has major shortcomings.  There are about 5,000 stocks available for purchase via Schwab, but I am testing only 100 of them so my results might not be general enough (and clearly the results from 50 stocks were not generalizable).  Also, my system shows very different results for different time periods.  Results for the last three years are better than results for just the last year, so my limit values may have a bearish bias or in general they have a bias that depends on the overall market mood.  I probably need fancier formulas, perhaps tighter limits but allow the purchase if one or two limits are violated, or maybe I should bias the limits based on the overall market mood that week, or something.  But what I’ve got seems profitable already.

On Friday, April 2nd, I bought a “basic” membership at StockCharts.com, which includes access to their stock-screener.  I converted my indicator limits into their query language and ran the screen.  It said I should buy Eastman Kodak (EK).  My program agreed that EK was a candidate—but there had been no previous week in the last three years when that stock would have been chosen, so there was no history of gains to reassure me.  One of the nice features of StockCharts.com is historical screens: what would this query have found if run the previous week?  Answer: nothing.  The week before that?  Nothing.  In fact, nothing for the preceding seven weeks—and for the weeks before that the recommendations all turned out to have been losers.  How disappointing!

I tried tweaking my limits this way and that.  Sometimes CYD would show up, sometimes not, but EK was always there.  It was like a Twilight Zone episode where you always end up back at the same mineshaft no matter which road you take.  I was in the middle of writing an email to StockCharts.com, complaining that their screener was failing to find stocks that I *knew* should have matched, when I realized what the problem was: in their query language I had written “weekly close < SMA × limit” but in my program I had written “weekly low < SMA × limit” which is a much easier criterion to meet.  After fixing that typo, I started seeing a dozen hits every week—and the hits from a few weeks earlier would have produced gains by now.  Excellent!

About 30% of the time, my system selects terrible stocks that fall off the bottom of the chart almost immediately.  So I picked five of the initial recommendations, to increase the likelihood that this first use of my new system would produce gains overall, even if one or two of the picks were turkeys.  Three of the five ended their first week with higher prices than I had paid.  None of them have stopped out yet.

A major problem with this “trend-trading” system, from my point of view, is how little attention it needs.  There is literally nothing to do all week except for an hour on Sunday nights, adjusting stop prices and selecting (from a short list) the new stock for next week.  The average stock is held for six weeks, so there will be no profit to take for a long time.  I want a “swing-trading” system so I can have some buttons to press on my computer each day.  So I altered my program to support daily trading as well as weekly.  The daily approach yields average gains that are ½ the size but are obtained in only ⅓ the time of the weekly, so it looks like the daily system would be more profitable than the weekly if I kept it up for a year.

Last weekend I ran my daily scan at StockCharts.com for the first time.  It said I should buy AER, but that stock also showed up on the scan for Thursday and usually results are inferior if you don't buy on the first day when the stock is a candidate. It turned out the purchase attempt would have failed anyway because AER jumped on Monday and my buy-limit price would have been too low, but I didn’t even try.  On Monday night, the candidates were HI and LXK.  Once again I turned up my nose and didn’t buy either of them.  Last night it seemed to be happening yet again with DUG, ERY, and ZNH.  But at 9pm EDT, when Yahoo finally updated their historical prices so my program could download them, I discovered that DUG was a buy-candidate six times in the last 750 days and half of those would have been winners!  So I bought it, although I am not at all sure that the price of petroleum will continue to fall for at least a week (which is what will be needed for this purchase to end up as a winner).  As of right now, so far so good: DUG is worth more than I paid.

Also last weekend, I ran the weekly scan again and selected QTM as the purchase for this week.  It had a bad day yesterday but today it is reaching for the sky.  And EK isn’t doing too badly, either.

I slapped a GPL on my program, but I don’t plan to publish it yet until there are some realized gains to show.  It is written in Emacs Lisp, which is the best language I know for writing programs where you don’t know where you’re going until you get there.  It is a little slow: 0.03 seconds for a weekly scan of three years for a stock.  But the speed is fine if I am just testing individual stocks that StockCharts.com has already selected for me.