Posts Tagged ‘strategy’

My BackTesting Engine Evaluation in 2007

April 9th, 2009 by JackieAnnPatterson | No Comments | Filed in Backtesting Set Up

Before starting the current round of major backtesting, I evaluated several tools to decide which to use.    This article shares the highlights of that endeavor and the main reasons for the outcome.

TradeStation was my incumbent.  By 2007 when I made my last evaluation, I’d had a couple years of experience with it as a charting tool and a backtesting engine.    I’d also used TradeStation Radarscreen to scan the market for opportunities, but found it awkward and slow.   The backtesting had proved reliable but limited to running one stock at a time.     Then TradeStation came out with two critical enhancements:  a means to read in outside data for historical prices, and hooks to automatically process more than one stock per run.

Another favorite tool is Telechartwhich has been my top-down market analysis tool since 2005.    It doesn’t have a backtesting engine.   However, in early 2007 the Worden Bros who make Telechart had just come out with the Blocks Backscanner.    I tried it out extensively and really liked the super support as well as the flexibility.   Its strength is scanning through a huge list of stocks in incredibly fast run time.    But as a very young tool, it didn’t yet have all the features I wanted like independent data sources.  Plus, it was so new  in 2007 that I often felt like a beta tester which is exciting but not what I was looking for to prove out trading strategies.    

I didn’t get past reading the specs on other backtesting tools.    Trading Blox seemed to locked into their own strategies, plus a very high price tag.  I’d previously been exposed MetaStock, struggled with it back in 2004, and was not keen on revisiting it.   I had heard good things about Wealth-Lab but didn’t want to get locked into Fidelity, and didn’t see all the features I wanted there either.

So basically my choice came down to the new Blocks or my old standby TradeStation.   I came to the conclusion that the optimal way to proceed was to rely on each tool’s strengths.    So I use TradeStation for backtesting because I can set up the large-scale, controlled software environment for it.   This gives me a way to prove out a strategy which I do only once per strategy.

Once a strategy is proven and I’m ready to trade it, I usually want to scan the market for opportunities to apply it.   I do this daily, after the market closes, using Blocks 2.0 because it is so very fast at scanning the market.

I recently attended a class on Worden Stockfinder 4.0.  It looks promising –  the Blocks program grown up and renamed.  I’ll review my impressions in another post.

(Backtestingblog is a Worden affiliate, meaning I may be compensated if you buy their product.  Blocks, Stockfinder, Telechart are trademarks of Worden Brothers Inc.   TradeStation is a trademark of TradeStation. TradingBlox is a trademark of Trading Blox. Wealth-Lab is a trademark of Fidelity. MetaStock is a trademark of Equis.)

Tags: , , , , , , ,

Stock Buy Signals

March 16th, 2009 by jackieannpatterson | No Comments | Filed in Moving Average, Objective Trading, Strategy Development, Technical Strategies

Here is part 2 about stock entry strategy or the buying process.   The previous article talked about stock screening, which is the background investigation to select a pool of candidate stocks to buy when the time is right.   The trigger or market timing signal is the topic of this article.   

 Why You Need to Time Your Entry

Once you have a universe of candidates, you need an entry signal or trigger.  Stocks can sit around looking good enough to buy for a long time, and you need a discrete event to say “Buy Now”.  Hard experience has taught me that “when I have time to complete research” and “when I feel excited about stocks” are not the best entry conditions.    In retrospect, it was usually a price extreme that got me pumped enough to research stocks and hit the buying point.   I’ve found that exercising the judgement to pick a better entry point can be more financially rewarding than just jumping in.     Personally, I suspect that even a random entry point would be better than emotion-driven buying, and backtesting can help identify strategies that do better than random.

 How To Time Your Entry

I see three broad categories that can be used as in entry signal: news events, clock or calendar events, and price events, especially as indicated by objective technical analysis.   Let’s compare them.

 News Events

If you’re new to the stock market, reacting to news events may seem the most natural thing in the world.  However, a little experience shows that the market anticipates and prices in news before it happens.  This is called discounting.  As an example, remember the recent situation with Steve Jobs and Apple.   It follows the saying, “Buy the rumor, sell the news”, only in reverse because bad news is what moves the market lately.   Here’s what happened:  Amid rumors of Jobs’ recurring illness, the price of AAPL declined, all the while Apple insisted Jobs was healthy.   Then Jobs announced that he was taking a medical leave of absence.   If the rumor of illness prompted a decline, then one might think that the news of his departure would tank the stock - he has had an unquestionable impact on the company, after all.    What actually happened, though, is that AAPL traded down to a new 52 week low in after-hours trading on January 14, the day of Jobs’ departure.  The following day, the price opened low, but regained most of it to close at near the high of the day.  Price bounced around the lows for 3 days, and then began an ascent that ended 3 weeks and 30% later.   The market had already priced in the news and the reaction went in the opposite direction, as it often does.    The upshot of this example is that it is difficult, if not impossible, to form an objective strategy around the news because the news may be priced into the market and always must be subjectively interpreted.

 Calendar Events

The second type of entry signals, clock and calendar events, are more objective than the news, but that’s not saying they’re 100% reliable.   Some of the people who use this category of signals are

  • day-traders who never hold overnight
  • pro traders who only hold overnight
  • investors following the adage to “sell in May and go away”
  • small-cap investors who show up in December
  • commodity traders following the seasonal fundamentals
  • and those folks who mine the charts looking for the dates when a stock almost always seems to go a certain way

Some of the calendar-driven moves truly are driven by the calendar. Others are due to coincidence, while still others are illusion.  Backtesting - either automatically or by manually checking the charts - can weed out the pretenders by determining which have been profitable in the past, and that is a useful first step.    I think you owe it to yourself to take it one step further and look for a plausible cause for the move rather than betting good money on a pattern that came about by chance.

Technical Indicator Signals

 The same can be said of technical indicator signals - you need to understand why they work — plus you need to make sure they are objective.   Aronson’s book makes a good case for using objective indicators rather than relying on subjective information for trading decisions.   A signal is objective if there is no “wiggle room” in describing it, if any two people always see it the same way (not like pattern recognition) and/or you could program it into a computer.  Elder’s first book gives good descriptions of technical indicators grounded in crowd behavior.  

 You can also think through the implications of the strategy.   For example, consider the trend-following strategy of buying when price hits a new high.   A new high doesn’t guarantee that the price will keep going, but all runaway stocks had to make new highs along the way.   A good thing to know is how many stocks making new highs go on to make a profit for investors holding for, say, one year.   Backtesting is one good way to estimate this info.   Sign up for email alerts to find out when new highs will be featured in BackTesting Report.             

Backtesting can also help us overcome our human tendency to become overconfident in a signal because we can easily spot on a chart the times that the signals worked and all too easily overlook the false signals.   A false signal is where the signal comes but the stock price doesn’t go in the expected direction long enough for the trader to profit.  It’s expensive to learn about false signals and our little foibles of human cognition in live trading.

The previous article used the example of price above the moving average to illustrate a potential stock screen.  A corresponding signal using moving averages is price crossing the moving average, or moving averages crossing each other.    They offer objective, discrete events to replace emotional guesswork with rational decision-making.  To find out more, check out the BackTesting Report MA Buy Signal package.

Updated on 3/17/09 to add: (BacktestingBlog is an Amazon Associate. )

Updated on 3/19/09 to add: (Author has a position in stocks mentioned in this article. )

Tags: , , , ,

BackTesting Moving Averages

March 9th, 2009 by jackieannpatterson | 3 Comments | Filed in Backtesting Set Up, Moving Average, Reports, Technical Strategies

Why Moving Averages

As a trader or investor, the only reason to investigate moving averages is to gain knowledge to increase profits. Like many other technical indicators, moving averages are meant to help us objectively tell the market status at any given time. This helps us see through the emotions of the day and make rational decisions, which we’re told will lead to greater profits and/or fewer losses over the long run. Moving averages (MAs) smooth the series of prices for a stock. MAs are most often used to identify the trend of market direction, and are classed as a trend-following indicator. This doesn’t mean that MAs are only for long-term investors - short term traders use them also. Moving averages can be used to screen stocks for good candidates, signal buying opportunities, and offer sell signals.

Why Backtest - A Story

The goal of backtesting is to find out if moving averages really do lead to better results and what are the most promising ways to apply MAs. Let me tell you a short story. While I was putting together the results for one of the moving average BackTesting Report issues, I happened to visit a friend. At her house, I came across some reading material from a well-advertised discount stock broker. In it was an article that advising its customers to use a particular moving average length applied in a certain way to get the best results. I had my comprehensive tests right in front of me and I can tell you that broker’s method did not get the best results although they did mention a MA length that is useful in other ways. I had in my hand test results that showed that the way that broker applied the moving average had a win rate worse than the baseline when tested on 7147 stocks over 14 years of stock market data. Clearly the broker wasn’t running that kind of testing. It’s up to the customers - us! - to fend for ourselves and find out what works versus what doesn’t.

How to Calculate MAs

When backtesting moving averages, the first decision is how to calculate the moving average. Do you want a simple moving average (SMA)? Or something designed to track price better such as an exponential moving average (EMA)? You might consider an experiment to compare the win rates of the two different averages. I did just that a couple years ago, and while I don’t have the results to publish, I came away with the notion that it didn’t make a big difference whether I chose SMA or EMA — just pick one and use it consistently. So for this project, I choose to use simple moving averages because I see them mentioned in commentary most often. To actually do the calculation, I relied on the built-in function which came with TradeStation. (The choice of backtesting engine is another decision which is general enough to write about in another post.)

How to Use MAs

Next you need to pin down how exactly you want to apply moving averages. How will you interpret the relationship between price and moving average? What rules will you use to decide when to buy and sell? You don’t have to read long about stocks before coming across a bullish reference to a stock trading above its 200-day moving average or its 50-day moving average, or even the 10- or 20-day MA. Or advice about buying stocks as they cross their 50-day or 200-day moving average. These are important rules to test in the backtesting engine. And then there’s the moving average crossover - a classic method of technical analysis. That makes three distinct ways of using moving averages to test.

Going more in-depth, some trading texts talk about the slope of a moving average. If you hark back to algebra and consider the MA as a line, to find its slope you would pick two points on the line and apply the usual formula ((x2-x1)/(y2-y1)). This brings up the question of how far apart to pick the two points which can make a difference to results. Really, since the MA is being used to identify the trend, we just want to know if it is sloping up or down. Then we can simplify the whole calculation by noticing that if the price is above the moving average, it must be pulling the average up, and a price below the MA pulls it down. Thus another reason to test the efficacy of price above the moving average.

Parameter settings

Once you decide on how to use the MAs, you need to pick a selection of various lengths to test. Beware of over-optimizing. Somewhere out there is a guy with backtesting results showing 3895% gain or whatever using just the right moving average. Too bad he doesn’t know what MA will produce those results in the future. That said, you need to try more than one length to make sure that your results aren’t a fluke. Stick with defaults settings or the ones you hear about most in the media. Finding the one perfect parameter setting is not going to make you rich. Finding a cluster of good, robust settings just might do you a great deal of good though.

As a practical matter when backtesting allow enough data lag before measuring. All tests must begin measuring at the same place for apples-to-apples comparison among different MA lengths. For example, if you’re testing a 200-day moving average, it will take the first 200-days of data to calculate the first point of that moving average. That means that the first day you could possibly have a signal is 200-days into the data set. To make a fair comparison with, say, the 10-day moving average, you need to make sure not to count any signals from the 10-day moving average before the 200-day is ready to go. Fortunately TradeStation has a way to set the “Maximum number of bars study will reference” in “Properties for All” strategies which forces the backtesting engine to wait that long before tabulating data.

More Profit from Buying or Selling?

Moving average rules, and in particular moving average crossover rules, are often discussed as a reversal system. This means that one signal, say the MAs crossing upwards is a buy signal and then its opposite, say MA lines crossing down, is not only a sell signal but also the trigger to go short. Theoretically, that’s just fine but many people are not interested in shorting the market. They are looking for techniques to help them buy and maybe sell. Even a person who regularly sells and sells short might use different techniques for buying and selling. For these reasons, it’s wise to test the buy signals separately from the sell signals.

This poses a dilemma because it’s hard to evaluate a buy signal in isolation. One way to do this is to use timed exits - that is, exit the trade or sell the stock after a certain amount of time elapses. I chose to run each backtest three times with three different times exits because different people have different styles and different needs. To produce backtesting results useful to swing traders, I exit after 2 days. To model position traders, 20 days. To meet the needs of active investors, backtesting holds each position for 200 days. This gives a way to isolate the buy signals and find out just how useful the moving average is to stock buyers of various temperaments.

Need to Define Goodness

One more very important thing to consider if you are backtesting moving averages to find out how well they do in the stock market: How will you know what is good? You need objective criteria for success. That means identifying the key statistics such as win rate, expectancy, hypothetical equity gains, etc. It also means setting standards for acceptable performance in each of these areas.

An example illustrates why this is important and why it’s not as easy as it first appears. Say your tests show a win rate of 55% for a particular indicator. That may might not be so good if, say, 62% of all stocks went up during the same period of time. Or if only 25% of stocks rose during that time period, your 55% win rate would be spectacular. What is good depends on how it compares to baseline market performance under the same conditions.

You can download a free copy of the BackTesting Report Baseline issue by clicking here.

Test Set

For a meaningful backtest, you need to have enough data to make a statistically valid comparison. At the minimum, that means 30 trades. Even if you are trading just one instrument - just one stock or just one currency pair - I think it’s important to test your trading strategy on many different instruments to prove its robustness. I went over the top with an extremely large test set — 7147 stocks over 14 years — to make sure my results would apply in a wide variety of market conditions.

You can get your copy of my backtesting reports on moving average buy signals by clicking here.

Tags: , , , , , , , , , , , , , , , , , , , , ,

Selecting Time Periods for Backtesting

December 17th, 2008 by jackieannpatterson | No Comments | Filed in Backtesting Set Up

When people say they want recent data for backtesting, I wonder two things:

1. How do they test longer term strategies using only recent data?   Anything involving a 200 day moving average, for example, needs nearly a year of data just to calculate the average.   Then it needs multiple years of data to get various signals and see how they play out.

2. How did they do in 2008 relying on anything resembling the recent past of 2003-2007.   It seems to me that you need to go back to 2001, at the very least, to find data that represents a crash.

When I selected time periods for backtesting, I looked for a nice long segment that included sideways, up, and down markets.   I ultimately decided on May 1994- April 2004 as the core time period for my testing.    This includes the tech bubble and the bubble bursting in a double-dip recession.  1994 showed less volatility, and the 1998 crisis broke up the monotony of the rising market.

Added to the core period is the next segment for out-of-sample testing.   I read somewhere (sorry, forgot where) that the out-of-sample period should be one-third the length of the initial period.   May 2004- April 2007 fit that bill timewise. The market action during this period was flat and upward biased.

Yes, I could detrend the data but I’ve found that approach very unintuitive.   If I am testing trend-following strategies, it doesn’t make sense to me to remove the trend.  Instead, I do a baseline test using a simple strategy and use it for comparison to supposedly smarter strategies.    This approach, and the fact that I apply it during varying market conditions, provides a way to see if a strategy really adds value.    A strategy demonstrates “alpha” by doing better than the baseline.

Another note about my time periods.   I began my efforts with this data set in May 2007.   Hence the time periods run May - April of each year.

My third time period, May 2007 - April 2008 came about because a) it was there, and b) this period is now one-third the previous period, making it the out-of-sample for the out-of-sample data.   As it turns out, the market action was again very different, allowing further stress-testing of the strategies.   Here again, I think it would be a mistake to focus solely on the carnage of the recent past.   Dawn has so far always followed the dark of night.

Tags: , , , , , , ,

How To Clean Price Data for Backtesting

December 16th, 2008 by jackieannpatterson | 2 Comments | Filed in Backtesting Set Up

Cleaning data for backtesting is not easy but its very necessary to get meaningful results.    Mis-adjusted price splits can skew the price data and mislead the unwary backtester into thinking they’re found the holy grail when the strategy merely happens to catch the good side of a bad gap.

Here’s the steps to screen out dirty data and produce a clean dataset:

1. Pick at least 3 candidate data vendors.

2. Format the data for comparison.

3. Write a program to do a smart comparison and run it on the 3 candidate data sets.

4. Analyze the mis-compares to see which set is in error.   if 2 of 3 sets agree, assume that’s the correct value and the outlier is wrong.

5. Send feedback to the data vendors so they can fix the errors.

6. Select the set of historical price data to use for backtesting and lock it down to prevent changes during the backtesting.

7. Feed the golden price data to the backtesting engine.

This process took me several weeks of work but was worth it to get accurate results.  There’s little point of going to the work of backtesting if the underlying data is riddled with errors.

Read on for details if you are going to attempt this on your own or if you just want to see what preparations go into serious backtesting. (more…)

Tags: , , , , , , , , , , ,

ATR Trailing Stop Definition

November 10th, 2008 by jackieannpatterson | No Comments | Filed in Glossary

The ATR Trailing Stop is one way to limit losses and protect profits. A stop loss order is set a multiple of the Average True Range (ATR) away from the current stock price. As the price moves in the trade’s favor, the stop rachets along with, always calculated from a better closing prices and never from worse closing prices.    This mostly keeps from giving ground once its protected by the stop, except in the case of increasing volatility as measured by the ATR.

Click here for Back Test Performance of Trailing Stops 

Chuck LeBeau popularized the method of trailing a stop loss order a few ATRs below the recent high price for a long trade. This method became known as the Chandelier Stop.    LeBeau’s Book covers other aspects of ATRs.   The best description of the Chandelier exit is in Come Into My Trading Room: A Complete Guide to Trading by Alexander Elder.

The ATR Trailing Stop is also known as a volatility stop.

Extra Insight:

In backtesting, the ATR Trailing Stop reflects each stock’s unique daily price range.  Hence it can fit each stock better than a dollar trailing stop or even a percentage trailing stop.

As with all trailing stops, the ATR trail never exits at the extreme of a movement. Hence it always gives back some of the profits.

The ATR stop amount can be subtracted from either the high, the close, or the low of the day.    Each variation gives slightly different results.    The important concept is to match the stop distance to the stock’s volatility and to move it along with improving prices.

ATR stops are not offered by brokers, to my knowledge.   They are also tedious to calculate by hand.   The only realistic way to use an ATR stop is with software support.   Programmable software packages such as TradeStation can be programmed to display (and backtest!) an ATR stop.   

Click here for BackTesting Reports on Trailing Stops

(Backtesting Blog is an Amazon Associate.)

Last updated 11/11/08.

Tags: , , , , , , , , , , ,

Curve-Fitting Definition

November 4th, 2008 by jackieannpatterson | No Comments | Filed in Glossary

 Curve-fitting in general is the process of finding the (mathematical) description which best matches a given set of data.    When its not applied to trading strategies, it can be a very useful way of drawing conclusions from experimental data.

 When applied to trading strategies, curve-fitting can produce over-optimized, over-optimistic results.   In any set of price data, there is some “magic”  combination of indicators and parameters that catches most every move and shows outstanding results.    Unfortunately, that magic formula is the result of chance and is different for every data set.   That means that future results probably won’t come close to the numbers generated with the full benefit of hindsight.

Extra Insight: 

There’s a fine line here.   On the one hand, we want to use backtesting to see how trading strategies performed in the past with an eye to picking the best one to trade.    On the other hand, we don’t want to trade a fantasy strategy that has little chance of working in the future.

I’m using the term curve-fitting as the negative connotation of over-optimization and data-mining as the positive connotation of selecting the best of many strategies via backtesting. 

Here are three things I do to help avoid the pitfalls of curve-fitting:

  • Out-of sample testing, e.g. test and compare results across multiple time periods.
  • Select parameters which fall in the middle of a range of good parameters.   Avoid the outlier settings that produce much better results than their neighbors.
  • Forward-test new trading strategies in live trading with small amounts before committing to full size trades.

See Technical Traders Guide to Computer Analysis of the Futures Marketsfor more against curve-fitting.

(Backtesting Blog is an Amazon Associate.)

Last updated 11/11/08.

Tags: , , , , , , , , ,

Entry Strategy Definition

October 29th, 2008 by jackieannpatterson | No Comments | Filed in Glossary

  An Entry Strategy is the set of rules specifying the conditions to enter a trade. 

For a long trade, entering means buying a stock.   For a short trade, entering means selling the stock.

 

Extra Insight:

Having a strategy for entry allows a trader to plan with a cool head rather than getting caught up in the heat of the moment.   Backtesting the entry strategy gives a trader insight and confidence in the plan.

The main goal of an entry strategy is getting into profitable trades.  on the flip side, it is useful to stay out of losing trades, making it a Do-Not-Enter Strategy as well.

(Backtesting Blog is an Amazon Associate.)

Updated 11/12/08.

Tags: , , , , , ,

Exit Strategy Definition

October 29th, 2008 by jackieannpatterson | No Comments | Filed in Glossary

 The Exit Strategy is a well-defined plan specifying the conditions to get out of a trade.  

 For a long trade, exiting means selling the stock. For a short trade, exiting means buying a stock.

Extra Insight:

Having a strategy for exit allows a trader to plan with a cool head rather than getting caught up in the heat of the moment.   Backtesting the exit strategy gives a trader insight and confidence in the plan.

Most traders have two purposes for exiting:  taking profits and cutting losses. 

Sometimes both ends are served by one exit order, such as a trailing stop.    Other times, they are two distinct orders, such as a fixed stop loss and a target limit order.

A third goal of an exit strategy may be the efficient use of capital.    In that case, the exit strategy may have rules to exit a trade that isn’t going anywhere in order to redeploy the resources elsewhere.

Click here for BackTesting Reports on Exit Strategies

(Backtesting Blog is an Amazon Associate.)

Updated 11/12/08.

Tags: , , , , , ,

Expectancy Definition

October 28th, 2008 by jackieannpatterson | No Comments | Filed in Glossary

Expectancy measures a trading strategy’s profit potential.   It considers both the reliability or win rate as well as the amount gained by each win.    That way, it can compare trading strategies that often win small gains with strategies that rarely win but win big when they do. 

Expectancy = (win_rate * avg_win) - (loss_rate * avg_loss)

Van Tharp defines expectancy in terms of risk here, as the average of the R-multiples returned by trading or backtesting the system.

Extra Insight:

Over a large number of trades, the expectancy is the expected gain of the trading strategy.  Higher expectancy is generally better.  Always avoid trading strategies with negative expectancy.

Scaling the expectancy by risk is indeed useful, especially when it comes time to compare different systems.  I use the R-multiples as suggested by Van Tharp for ease of calculation.

Expectancy is also known as the Kelly Criterion for the Bell Labs researcher who proved the equation as an upper bound on the amount to risk.     A common language way to say it is to risk an amount proportional to the expected gain.   So if the expectancy is 45%, Kelly advocated risking 45% of the account value.   This may be mathematically optimal over a large number of trades but it can have a very vicious drawdown!   Imagine trading a high expectancy system, say 80% and the first trade is a loss.  For a $100k account, that would leave only $20k in the account and a long road to make a 4x gain to break even.

Expectancy is not the be-all and end-all of a trading system.   The standard deviation or variance of the results is important.  The win rate is too.  Both give insight into how psychologically difficult it is to stick to the trading strategy.

Updated: 11/12/08.

Tags: , , , , , , , , ,