简体   繁体   中英

Calculate Realized Volatility in R

I am attempting to calculate the realized volatility of the members of the S&P 500 over a specific interval. I am having trouble looping through the index and storing the values.

The process should be to calculate the volatility of each name and then store it within a data frame. Formatted "Ticker" and "Volatility"

I have been using the below code to calculate vol

library(tseries)
start_date <- as.Date("2019-04-23")
end_date <- as.Date("2020-01-22")
SP_500 <- data.frame(read.csv("Tickers.csv", header = TRUE))

data <- get.hist.quote('TIF',start_date, end_date, quote = c("Close"))
price <- data$Close
ret <- log(lag(price)) - log(price)
ret[is.na(ret)]<-0
vol <- sd(ret) * sqrt(252) * 100
vol

I have tried a million different attempts to looping and storing but all failed.. Thanks for the help in advance!

We can create a function that downloads the historical data for a symbol and calculate it's volatility.

library(tseries)

calculate_vol <- function(x, start_date, end_date) {

   data <- get.hist.quote(x,start_date, end_date, quote = "Close")
   price <- data$Close
   ret <- log(lag(price)) - log(price)
   ret[is.na(ret)]<-0
   vol <- sd(ret) * sqrt(252) * 100
   return(vol)
}

We can then pass symbols to this function using sapply and convert it to dataframe using stack . Assuming the column where symbols are stored in the csv is called symbol

SP_500 <- read.csv("Tickers.csv", header = TRUE)
realized_vol <- stack(sapply(SP_500$symbol, calculate_vol, start_date, end_date))

For example :

start_date <- as.Date("2020-01-01")
end_date <- as.Date("2020-01-22")
realized_vol <- stack(sapply(c('IBM', 'MSFT'), calculate_vol, start_date, end_date))
realized_vol

#     values  ind
#1  9.165962  IBM
#2 15.753567 MSFT

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM