A Super-Easy, Simple-Dimple Backtester in R

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")  
}

Leave a Reply

Your email address will not be published. Required fields are marked *