R tibble 数据帧切片和 rollapply 函数

发布于 2025-01-09 17:34:55 字数 1897 浏览 4 评论 0原文

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

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

  1. 假设我有两个索引。我可以使用一行代码来查找两个股票代码的年化 SD 吗?现在我必须一个接一个地执行
GSPC.new <- merge(GSPC.new,rollapply(GSPC.new$GSPC.adj.ret, 252, sd)) 
  1. 它 对 xts 对象进行切片更容易。我可以在 tibbble 数据框中做同样的事情吗?
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")

I am writing a script to calculate the standard deviation of S&P500 and want to compare the rolling standard deviation to the long term average of the SD.

I can make my codes work but seems kind of clumsy. I want to ask two questions to make my code easier to understand.

  1. Suppose I have two indices. Can I use one line of code to find the annualised SD for both tickers? Now I have to do it ticker by ticker
GSPC.new <- merge(GSPC.new,rollapply(GSPC.new$GSPC.adj.ret, 252, sd)) 
  1. It is easier to slice a xts object. Can I do the same in tibble dataframe?
gspc.avg10yr <- mean(na.omit(GSPC.new$GSPC.adj.std.annualised["2011/2022"]))

All code below can be executed directly in RStudio directly.

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")

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

_畞蕅 2025-01-16 17:34:55

将股票数据放入环境 e 中,迭代股票名称,计算列表 ret.list 中的回报,然后将其形成 xts 对象 ret。由此计算标准化年化收益 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("")

screenshot

Place the ticker data in environment, e, iterate over the ticker names calculating the returns in a list, ret.list, and then form that into an xts object, ret. From that calculate the standardized returns annualized, std_ann, as an xts object.

To create the plot create a grid data frame g and from it data frame Means with columns Series, col (colors) and means to be used in geom_hline. autoplot will use Series to refer to the facets and geom_hline will use the Series column in Means to match each horizontal line to the appropriate facet.

Only the packages listed below (and the packages they depend on) are used.

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("")

screenshot

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文