Backtesting Part 2: Splits, Dividends, Trading Costs and Log Plots

September 16, 2011
By

(This article was first published on Modern Toolmaking, and kindly contributed to R-bloggers)

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.

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:


To leave a comment for the author, please follow the link and comment on his blog: Modern Toolmaking.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: , , ,

Comments are closed.