[R-SIG-Finance] Perhaps somebody would like to critique my code?

Robert Nicholson robert.nicholson at gmail.com
Thu Mar 11 03:23:00 CET 2010


This piece of code is giving me the answers I expect it to but to me it looks ugly and that's usually a sign that there are better more elegant ways to accomplish the same task.

I would welcome any criticism of the following as I'm only just getting started in R

library('quantmod')
getSymbols('RIMM')
TICKER=RIMM
#TICKER = as.xts(read.table("/Users/robert/Programming/R/close.txt"))
PriceChange = rollapply(Cl(TICKER), width=2, function(x) x[2] - x[1], by=1, align = "right", na.pad = TRUE)
colnames(PriceChange) = c("Price.Change")
TICKER = merge.xts(TICKER, PriceChange)
LogOfChange = rollapply(Cl(TICKER),width=2, function(x) round(log(x[2]/x[1]),4), by=1, align = "right", na.pad = TRUE)
colnames(LogOfChange) = c("Log.Change")
TICKER = merge.xts(TICKER, LogOfChange)
Sd = rollapply(LogOfChange, width=20, function(x) round(sd(x), 4), by=1, align = "right", na.pad = TRUE)
colnames(Sd) = c("StdDev.Log.Change")
TICKER = merge.xts(TICKER, Sd)
Sd$StdDev = rep(NA, NROW(Sd))
colnames(Sd) = c("StdDev.Log.Change", "StdDev")
for (i in 1:NROW(Sd)) {
Sd[i, "StdDev"] = round(TICKER[i, "StdDev.Log.Change"] * Cl(TICKER)[i],3);
}
TICKER = merge.xts(TICKER, Sd$StdDev)
Sd$Spike = rep(NA, NROW(Sd))
colnames(Sd) = c("StdDev.Log.Change", "StdDev", "Spike")
for (j in 1:NROW(Sd)) {
if (!is.na(Sd[j, "StdDev"])) {
	Sd[j, "Spike"] = round(as.numeric(TICKER[j, 'Price.Change']) / as.numeric(Sd[j-1,"StdDev"]),2)
}
}
TICKER = merge.xts(TICKER, Sd$Spike)
lineChart(Sd$Spike, line.type = 'h')
addTA(Cl(TICKER))



More information about the R-SIG-Finance mailing list