应用函数 w.r.t。 R中的日历日

Applying functions w.r.t. calendar days in R

我有每日(金融)时间序列。由于每个月都不会在 30 日或 31 日结束,因此使用 apply 函数给我自己带来了问题。使用每月时间序列,我可以指定每个 n'th 个月。但是,我如何指定每个 n'th 月的每日系列。

假设我有这个日期数据集:

dates <- seq(as.Date("2000-01-01"), length = 1000, by = "days")

data <- cbind(rnorm(1000, mean = 0.01, sd = 0.001),
              rnorm(1000, mean = 0.01, sd = 0.001),
              rnorm(1000, mean = 0.01, sd = 0.001))

特别是,我想 运行 每个 n'th 月的协方差矩阵类似于:

cov.fixed <- lapply(as.data.frame(t(rollapply(1:nrow(data), 90, c))),
 function(i) cov(data[i,]))

但不是 90 是否可以写成每个 3rd month 以便考虑到日历天数?

非常感谢

如果你想要每个月的协方差,你可以做类似下面的事情。关键是 split 矩阵由 month.

library(zoo)

month <- as.yearmon(dates)

cov.month <- lapply(split(as.data.frame(data), month), cov)

names(cov.month) <- sub(" ", "_", names(cov.month))
cov.month$Jan_2000
#             V1           V2           V3
#V1 7.825062e-07 7.063689e-08 9.561721e-08
#V2 7.063689e-08 8.989207e-07 1.293351e-07
#V3 9.561721e-08 1.293351e-07 1.175318e-06

cov.month[[1]]    # The same

关于四分之一,代码类似,只需将as.yearqtr替换为as.yearmon即可。

quarter <- as.yearqtr(dates)
cov.quarter <- lapply(split(as.data.frame(data), quarter), cov)

然后用 sub 像上面那样取更好的名字,没有空格。

数据.

与问题不同,我设置了RNG种子。

set.seed(3658)    # Make the results reproducible
data <- cbind(rnorm(1000, mean = 0.01, sd = 0.001),
              rnorm(1000, mean = 0.01, sd = 0.001),
              rnorm(1000, mean = 0.01, sd = 0.001))