A Super-Easy, Simple-Dimple Backtester in R

April 9, 2011
By

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

I cut my finger on a paring knife this morning. Don't use a sharp knife to spread butter on your toast. It's better to limit yourself to using dull kitchen utensils until the caffeine kicks in. No matter, I still have most of my digits to type in a simple backtesting program in R. Good thing it's only about 15 lines of code.

require(quantmod)

getSymbols("GLD")

for(i in seq(5, 15, 5))
  for(j in seq(50, 80, 15))

{
    GLD$fast     <- SMA(Cl(GLD), n=i)    
    GLD$slow     <- SMA(Cl(GLD), n=j)        

    golden_cross <- Lag(ifelse(GLD$fast > GLD$slow, 1, -1))
    golden_cross <- na.locf(golden_cross, na.rm=TRUE)
       
    coin         <- ROC(Cl(GLD))*golden_cross
    best_coin    <- max(coin)
    worst_coin   <- min(coin)
    last_coin    <- cumprod(1+coin)[NROW(coin),] 
   
    annual_coin   <- round((last_coin-1)*100, digits=2)/(NROW(coin)/252)

    cat(i,j,annual_coin, best_coin, worst_coin, "\n", file="~/goldcat", append=TRUE) 
    cat(i,j,annual_coin, best_coin, worst_coin, "\n")  

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

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.