Moving SD in R - Syntax needed

 data<-read.csv("http://ichart.finance.yahoo.com/table.csv?s=^NSEI&a=08&b=16&c=2006&d=08&e=26&f=2012&g=d&ignore=.csv")  
 tmp <- data[order(data$Date), ]  
 data<-tmp  
 data'$'MovAvg60=filter(data[,5],rep(1/60,60),sides=1)

I could manage to get the 60 day Moving Average of the Index data that was taken from finance.yahoo.com... but "standard deviation" function gives 1 singe value of standard deviation.. But I need the moving SD

Upvotes: 0

Views: 314

Answers (4)

Joshua Ulrich
Joshua Ulrich

Reputation: 176688

As Frank noted in his comment, and as I mentioned in the post he linked to, TTR::runSD will do this (it's likely faster than rollapply). I'd also recommend you spend some time learning one of the finance workflows, rather than re-inventing the wheel.

> getSymbols("^NSEI", from="2006-08-16", to="2012-08-26")
[1] "NSEI"
> NSEI$StDev60 <- runSD(Cl(NSEI), 60)
> tail(NSEI)
           NSEI.Open NSEI.High NSEI.Low NSEI.Close NSEI.Volume NSEI.Adjusted  StDev60
2012-08-17   5368.60   5399.95  5341.70    5366.30           0       5366.30 138.1689
2012-08-20   5366.30   5366.30  5366.30    5366.30           0       5366.30 138.1317
2012-08-21   5368.70   5425.15  5368.70    5421.00           0       5421.00 139.2909
2012-08-22   5395.75   5433.35  5394.80    5412.85           0       5412.85 138.7741
2012-08-23   5426.15   5448.60  5393.85    5415.35           0       5415.35 137.0164
2012-08-24   5392.60   5399.65  5371.00    5386.70           0       5386.70 130.5664

Upvotes: 1

Wojciech Sobala
Wojciech Sobala

Reputation: 7561

You can use following formula (http://en.wikipedia.org/wiki/Variance):

# SD = sqrt(EX^2-(EX)^2)

data$MovSD60=sqrt(filter(data[,5]^2,rep(1/60,60),sides=1)-data$MovAvg60^2)

Upvotes: 3

Sven Hohenstein
Sven Hohenstein

Reputation: 81713

You can use rollapply from the zoo package to apply a function to a moving window.

library(zoo)
rollapply(data[5], 60, sd, fill = NA, align = "right")

Upvotes: 3

sgibb
sgibb

Reputation: 25736

You could use ?embed and ?apply, e.g.

## create grid (each row contains 60 entries)
e <- embed(data[,5], 60)

## calculate sd for each row
apply(e, MARGIN=1, FUN=sd)

# [1] 126.5202 125.5809 127.6456 128.2805 129.2382 129.8014 ...

Upvotes: 3

Related Questions