i am a beginner on R and i am currently trying to compute the historical volatility per year. My dataset looks like this :
date prices
01/01/2000 100
03/01/2000 98
05/10/2000 103
08/03/2001 102
08/04/2001 110
i would like to create a for loop in order to compute quickly the historical volatility i have been computing "manually" as follows :
data_hv <- read.csv("file")
data_hv_2000 <- data_hv[(1:259),]
data_hv_2001 <- data_hv[(260:518),]
data_hv_2002 <- data_hv[(519:778),]
data_hv_2003 <- data_hv[(779:1038),]
and then, computing the historical volatility once i have grouped per year the data in subsets of data :
price = data_hv_2000$price
ret <- log(lag(price)) - log(price)
print(ret)
vol <- sd(ret, na.rm = TRUE) * sqrt(259) * 100
vol
price_2001 = data_hv_2001$price
ret <- log(lag(price_2001)) - log(price_2001)
vol_2001 <- sd(ret, na.rm = TRUE) * sqrt(260) * 100
vol_2001
260 and 259 being the number of rows of each subset.
i have tried to start doing a for loop :
data_hv %>%
for (i in 2000:2022) {
filter(contains(i)) %>%
price_i = data_hv_i$Wheat
ret <- log(lag(price_i)) - log(price_i)
vol_i <- sd(ret, na.rm = TRUE) * sqrt(nrows(data_hv_i)) * 100
vol_i
}
There are a couple things you want to remember when running for loops and one of them is to create a empty object of desired type before running the loop. Also, you are piping into a for-loop and into an object, which is probably causing an error.
Try this:
Final Solution
Created on 2022-06-20 by the reprex package (v2.0.1)