UPDATE 9/21/2011: Costas correctly points out that I should lag my strategy vector by one day, as today's returns are determined the position we chose yesterday. I updated the code, results, and charts to reflect this. Please alert me to any similar errors in the future.
In my last post, I demonstrated how to backtest a simple momentum-based stock trading strategy in R. However, there were a few issues with my implementation: I ignored splits, dividends and transaction costs, all of which can have a large impact on a strategy. I also came up with a better plot to help show how a given strategy compares to a benchmark, and wrapped everything together into one function.
First of all, we need to reload our functions from the last post. These functions define our strategy and analyze its performance.
Next, we can test our strategy. I've added a couple new indexes:
This function does a lot of lifting:
1. It loads the data and adjusts the closing price for splits and dividends. It uses the splits/dividends data from yahoo, but performs its own, more accurate calculations.
2. It determines a position series, based on the "daysSinceHigh" function. This part is the same as in my last post.
3. It determines trades, which are defined as days when today's position is different from the previous day's positions. I assumed that transactions costs are 0.5% of equity, so on trading days I subtracted 0.005 from my Returns.
4. It makes a plot. This plot is different from the charts.PerformanceSummary we used last time. The first plot shows cumulative returns of my strategy and the index, while the second plot shows the relative performance of my strategy over the benchmark (also known as alpha). The third plot shows drawdowns.
5. It returns a data table of statistics, comparing the strategy to the benchmark.
I tested this strategy on GSPC, FTSE, DJI, N225, EEM, EFA, and GLD. (The last 3 are ETFs). The strategy performs well on some indexes, and poorly on others. Here's the results of my backtest:
As you can see, this strategy tends to reduce drawdowns, but it also sometimes reduces overall returns. In some cases, you could leverage up the strategy, which would increase both returns and drawdowns, but that's the subject of another post.
Here's a buncha charts: