R tibble数据帧切片和rollapply函数

R tibble dataframe slice and rollapply function

我正在编写一个脚本来计算 S&P500 的标准偏差,并希望将滚动标准偏差与 SD 的长期平均值进行比较。

我可以让我的代码工作,但看起来有点笨拙。我想问两个问题,让我的代码更容易理解。

  1. 假设我有两个索引。我可以使用一行代码找到两个代码的年化 SD 吗?现在我必须一个接一个地进行
GSPC.new <- merge(GSPC.new,rollapply(GSPC.new$GSPC.adj.ret, 252, sd)) 
  1. 切片 xts 对象更容易。我可以在 tibble 数据框中做同样的事情吗?
gspc.avg10yr <- mean(na.omit(GSPC.new$GSPC.adj.std.annualised["2011/2022"]))

以下所有代码都可以直接在RStudio中直接执行。

library(tidyverse)
library(quantmod)
library(ggplot2)

tickers <- c("^HSI","^GSPC")
getSymbols(Symbols = tickers,
           src = "yahoo",
           index.class = "POSIXct",
           from = "1997-01-01")

GSPC.new <- na.omit(GSPC)
GSPC.new <- merge(GSPC.new, dailyReturn(GSPC.new$GSPC.Adjusted))
colnames(GSPC.new)[7] <- "GSPC.adj.ret"
GSPC.new <- merge(GSPC.new,rollapply(GSPC.new$GSPC.adj.ret, 252, sd)) # how to annualised both tickers in one line
colnames(GSPC.new)[8] <- "GSPC.adj.std"
GSPC.new <- merge(GSPC.new, GSPC.new$GSPC.adj.std*sqrt(252))
colnames(GSPC.new)[9] <- "GSPC.adj.std.annualised"
GSPC.new.tbl <- as_tibble(fortify(GSPC.new))
p.gspc <- ggplot(GSPC.new.tbl, aes(x=Index,y=GSPC.adj.std.annualised))
p.gspc + geom_line()
gspc.avg10yr <- mean(na.omit(GSPC.new$GSPC.adj.std.annualised["2011/2022"])) # is it possible to do in tibble way?
gspc.avg15yr <- mean(na.omit(GSPC.new$GSPC.adj.std.annualised["2006/2022"]))
gspc.avg20yr <- mean(na.omit(GSPC.new$GSPC.adj.std.annualised["2001/2022"]))
gspc.avg25yr <- mean(na.omit(GSPC.new$GSPC.adj.std.annualised["1997/2022"]))
p.gspc + geom_line()+
  geom_hline(yintercept = gspc.avg10yr, color = "red")+
  geom_hline(yintercept = gspc.avg15yr, color = "blue")+
  geom_hline(yintercept = gspc.avg20yr, color = "green")+
  geom_hline(yintercept = gspc.avg25yr, color = "black")

将代码数据放在环境 e 中,迭代代码名称,计算列表 returns 中的 ret.list,然后将其形成一个 xts 对象,ret。从中计算标准化 returns 年化 std_ann 作为 xts 对象。

要创建绘图,请创建一个网格数据框 g,并从它的数据框 Means 列 Series、col(颜色)和要在 geom_hline 中使用的均值。 autoplot 将使用 Series 来引用面,geom_hline 将使用 Means 中的 Series 列将每条水平线与适当的面相匹配。

仅使用下面列出的包(以及它们所依赖的包)。

library(quantmod)
library(ggplot2)

tickers <- c("^HSI","^GSPC")
yrs <- c(red = 10, green = 15, blue = 20, black = 25)

getSymbols(Symbols = tickers, env = e <- new.env(), from = "1997-01-01")

ret.list <- Map(function(nm) dailyReturn(na.omit(Ad(e[[nm]]))), ls(e))
ret <- setNames(do.call("merge", ret.list), names(ret.list))
std_ann <- rollapplyr(ret, 252, function(x) sqrt(252) * sd(x, na.rm = TRUE))

g <- expand.grid(Series = names(std_ann), col = names(yrs), 
  stringsAsFactors = FALSE)
meansfun <- function(Series, col) {
    st <- as.Date(as.yearqtr(2022-yrs[[col]]-1))
    mean(window(std_ann[, Series], start = st), na.rm = TRUE)
}
Means <- transform(g, means = mapply(meansfun, Series, col))

autoplot(std_ann) +
  geom_hline(aes(yintercept = means), Means, col = Means$col) +
  xlab("")