我想根据每日价格计算每周收益

  • 本文关键字:计算 每周 收益 每日 r
  • 更新时间 :
  • 英文 :


我是R的新手,我想使用周三到周三的收盘价来计算周回报率,因为我正在处理来自不同国家的股市指数。

为此,我从quantmod下载每日收盘价:

getSymbols("^GDAXI",from="2001-12-19", to = "2022-03-18")
GDAXI2<-GDAXI[,4]

我得到了一个";xts"动物园":

GDAXI.Close
2001-12-19     4984.69
2001-12-20     4934.14
2001-12-21     5019.01
2001-12-24     NA
2001-12-25     NA
2001-12-26     NA
2001-12-27     5117.13
2001-12-28     5160.10 
2001-12-31     NA
2002-01-01     NA
2002-01-02     5167.88
2002-01-03     5270.29

然后我使用以下代码只获取周三收盘价:

wednesday = as.POSIXlt(time(GDAXI2))$wday == 3
indx <- c(0, which(wednesday))
GDAXI3<-period.apply(GDAXI2, INDEX=indx, FUN=last)

我获得以下数据("xts"zoo"(:

GDAXI.Close
2001-12-19     4984.69 
2001-12-26     NA 
2002-01-02     5167.88
2002-01-09     5288.21
2002-01-16     4984.20
2002-01-23     5163.03

问题是可能有一个星期三是假日。,所以我得到了一个缺失的值。

"在周三不是活跃交易日的情况下,将使用下一个日期的收盘值以及最近日期序列中的有效价格:周二、周四、周一和周五。多日通常是不必要的;

我需要帮助,如果一周不包括星期三,我想排除下一个工作日。我想用第二天(2001-12-27(的数据来代替那个星期三的遗漏值

我还发现了这个有趣的话题:

根据R 中的每日价格计算每周回报

但是我无法运行Joshua Ulrich制作的脚本,我的数据出现了以下错误:

Error in try.xts(NA) : 
Error in as.xts.logical(x, ..., .RECLASS = TRUE) :   order.by must be either 'names()' or otherwise specified

约书亚·乌尔里希的剧本:

WedOrNext <- function(w) {
# find all the weekdays after Tuesday and before Saturday
iwd <- .indexwday(w)
i <- iwd > 2 & iwd < 6
# determine which row to return
if (any(i)) {
# return the first weekday after Tuesday
w[i][1L]
} else {
# return NA if there are no weekdays after Tuesday
NA
}
}

尝试使用我的原始数据(每日收盘价(:

do.call(rbind, lapply(split(GDAXI2, "weeks"), WedOrNext))

输出:

Error in try.xts(NA) : Error in as.xts.logical(x, ..., .RECLASS = TRUE) :   order.by must be either 'names()' or otherwise specified

有人知道我如何才能得到这些每周的价格吗?或者你能告诉我为什么我不能运行约书亚的剧本吗?

提前非常感谢!

如果我们转换为ts并再次转换回xts,那么这将用NA填充所有缺失的日期,然后我们可以使用na.locf0(x)na.locf0(x, fromLast = TRUE)从前向和后向填充它们。(请注意,Cl会选择收盘列——您也可以考虑使用Ad进行调整后的收盘。(

x <- as.xts(as.ts(Cl(GDAXI)))

最新更新