I haven't used xts before.

but in general you can do things more vector like

so if you have a vector of prices
vec = c(10,11,12,10,10.5,15,13,14,13)

you can get log returns like
logRet = round(diff(log(vec)),4)

The rollapply for the rolling sd looks good.

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


This is strange why are you checking if it is na and you shouldn't have to
loop through each item

imagine you had two vectors:
logRet =  round(diff(log(vec)),4)
rolling20DayStdeviations = c(.2,.3,.3,.4.,.3, NA, NA, NA) or something.

Then sharpeRatio= logRet/rolling20DayStdeviations

so all together you could have:


vec = c(10,11,12,10,10.5,15,13,14,13)
logRet = round(diff(log(vec)),4)
your rollingStdeviation function

sharpeRatio= logRet/rolling20DayStdeviations

HTH
Rob


On Wed, Mar 10, 2010 at 8:23 PM, Robert Nicholson <
robert.nicholson@gmail.com> wrote:

> 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))
>
> _______________________________________________
> R-SIG-Finance@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-sig-finance
> -- Subscriber-posting only. If you want to post, subscribe first.
> -- Also note that this is not the r-help list where general R questions
> should go.
>

	[[alternative HTML version deleted]]

