A Super-Easy, Simple-Dimple Backtester in R

April 9, 2011

[This article was first published on Milk Trader, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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.



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 their blog: Milk Trader.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)