Note: This post is NOT financial advice! This is just a fun way to explore some of the capabilities R has for importing and manipulating data.
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.
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: