0

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,

  • you can use `zoo::rollapply(mydata$Returns, 21, sd, fill=NA, align="right") * sqrt(252)` or `data.table::frollapply(mydata$Returns, 21, sd) * sqrt(252)` – chinsoon12 Nov 15 '19 at 05:29

1 Answers1

0

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.

dcarlson
  • 10,936
  • 2
  • 15
  • 18