我正在尝试从 Yahoo! 绘制一些选项数据!财务 - 我确定这非常简单,但我只是碰壁并失去了耐心。
此代码下载股票多个到期日的期权数据,对其进行清理并为其分配一个指数,即每个期权的到期日。
b
id year val twr
1: 1 1 2010 10
2: 2 2 2011 13
3: 4 3 2013 43
4: 6 4 2015 23
现在使用 ggplot2 创建分组条形图应该没问题(条形图共享相同的指数,在这种情况下是:执行价格 1,...,K 共享相同的指数 t。y 值这里应该是未平仓合约)。
#Options data
maturity_dates <- c("2021-07-16", "2021-07-23", "2021-07-30", "2021-08-06",
"2021-08-13", "2021-08-20","2021-08-27", "2021-10-15",
"2022-01-21", "2023-01-20")
sndl_options <- getOptionChain("SNDL", Exp = maturity_dates)
#combine options data into a dataframe for puts and calls
#calls
options_df <- do.call("rbind", sndl_options[1:10])
calls_df <- rbind(options_df[1:10])
calls_df <- do.call(rbind.data.frame, calls_df)
calls_df$maturity <- substr(rownames(calls_df), start = 5, 10)
rownames(calls_df) <- 1:nrow(calls_df)
#fix maturity column and set as index
dates_vec <- 0
a <- 1
for(i in calls_df$maturity){
if(i == "210716"){
i <- "2021-07-16"
dates_vec[a] <- i
a <- a+1
} else{
if(i == "210723"){
i <- "2021-07-23"
dates_vec[a] <- i
a <- a+1
} else{
if(i == "210730"){
i <- "2021-07-30"
dates_vec[a] <- i
a <- a+1
} else{
if(i == "210806"){
i <- "2021-08-06"
dates_vec[a] <- i
a <- a+1
}else{
if(i == '210813'){
i <- "2021-07-30"
dates_vec[a] <- i
a <- a+1
}else{
if(i == "210820"){
i <- "2021-08-20"
dates_vec[a] <- i
a <- a+1
}else{
if(i == "210827"){
i <- "2021-08-27"
dates_vec[a] <- i
a <- a+1
}else{
if(i == '211015'){
i <- "2021-10-15"
dates_vec[a] <- i
a <- a+1
}else{
if(i == '220121'){
i <- "2022-01-21"
dates_vec[a] <- i
a <- a+1
}else{
if(i == '230120'){
i <- "2023-01-20"
dates_vec[a] <- i
a <- a+1
}
}
}
}
}
}
}
}
}
}
}
remove(i,a)
calls_df$maturity <- NULL; calls_df$LastTradeTime <- NULL
calls_df$ITM <- ifelse(calls_df$ITM == TRUE, 1, 0)
calls_df <- as.xts(calls_df, order.by = as.Date(dates_vec))
我只是没有得到我想要的图表。有什么建议吗?
提前致谢。
答案 0 :(得分:0)
不确定您要实现的情节。首先,您可以通过去掉一堆 if
语句并简单地使用 as as.Date
来进行适当的日期转换,从而大大简化您的代码。此外,至少对于绘图,没有必要转换为 xts
对象。
library(quantmod)
library(ggplot2)
library(dplyr)
maturity_dates <- c("2021-07-16", "2021-07-23", "2021-07-30", "2021-08-06",
"2021-08-13", "2021-08-20","2021-08-27", "2021-10-15",
"2022-01-21", "2023-01-20")
sndl_options <- getOptionChain("SNDL", Exp = maturity_dates)
calls_df <- lapply(sndl_options, `[[`, "calls")
calls_df <- bind_rows(calls_df, .id = "date")
calls_df$maturity <- substr(rownames(calls_df), start = 5, 10)
calls_df$maturity <- as.Date(calls_df$maturity, format = "%y%m%d")
calls_df$OI <- as.numeric(calls_df$OI)
ggplot(calls_df, aes(x = maturity, y = OI, fill = factor(Strike))) +
geom_col(position = "dodge")