简体   繁体   English

计算 R 中的已实现波动率

[英]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.我试图计算标准普尔 500 指数成员在特定时间间隔内的已实现波动率。 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 .然后我们可以使用sapply将符号传递给这个函数,并使用stack将其转换为数据帧。 Assuming the column where symbols are stored in the csv is called symbol假设在csv中存储符号的列称为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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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