Autofill rows in R, daily volatility calculation

184 views Asked by At

my dataset looks like this:

set.seed(1234)
mydata <- data.frame("Returns" = sample(1:20,200, replace=T), "Vol" = 0)

I calculated annualized daily volatilty for the first 21 rows in a new column:

d_vol <- sd(mydata$Returns[1:21]) 
y_vol <- d_vol*sqrt(252)

The above calculation replaces the value in the column vol, row 21 by 83.38345

What I'm trying to learn is:

How to roll or autofill the remaining (22:200) rows with the formula used in (y_vol).

Thanks,

1

There are 1 answers

0
dcarlson On

Using just base r:

mydata$Vol[21:200] <- mapply(function(x, y) sd(mydata$Returns[x:y])*sqrt(252), 1:180, 21:200)

Also, FYI,

mydata <- data.frame(Returns = sample(1:20,200, replace=T), Vol = NA)

works just fine. No need for quotes around column names. Also you should use NA instead of 0 as the initial value for Vol.