(This article was first published on

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.**Milk Trader**, and kindly contributed to R-bloggers)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...