在滚动中对数据框的列应用和积 windows

Apply sum product on columns of a dataframe in rolling windows

我有一组定义的权重,我想在时间序列数据帧上滚动 windows 计算 returns 的加权和。我相信我们会在这里使用 rollapplyr,但我不确定如何在数据帧的每一行上执行滚动 window 函数。

在下面找到数据样本的 dput 输出:

tempVar <- structure(c(NA, -0.0081833512947922, 0.00508150903899551, -0.0072202479734873, 
0.00345258369231161, NA, 0, -0.00847462699097257, -0.00794638265247283, 
0.00445091892889238, NA, NA, NA, NA, NA, NA, 0, -0.0136462286616492, 
-0.00638979809877149, -0.00109950533341685), class = c("xts", 
"zoo"), .indexCLASS = "Date", .indexTZ = "UTC", tclass = "Date", tzone = "UTC", index = structure(c(946598400, 
946857600, 946944000, 947030400, 947116800), tzone = "UTC", tclass = "Date"), .Dim = 5:4, .Dimnames = list(
    NULL, c("TY00.USA", "CGB00.MOD", "G10L00.IFEU", "RLI00.IFEU"
    ))) 

为了简单起见,让我们考虑权重为:

tempWeights <- c(1.09,0.89,0)

注意:权重表明截至评估之日,该日期的 returns 没有 weighting.These 权重总和不是设计为 1

我希望输出为:

tempRRI <- structure(c(NA, NA, NA, -0.00439731, -0.0008871759, NA, NA, NA, 
-0.00754241803, -0.0163096243, NA, NA, NA, NA, NA, NA, NA, NA, 
-0.01214514381, -0.02056130983), .Dim = 5:4, .Dimnames = list(
    NULL, c("TY00.USA", "CGB00.MOD", "G10L00.IFEU", "RLI00.IFEU"
    )), index = structure(c(946598400, 946857600, 946944000, 
947030400, 947116800), tzone = "UTC", tclass = "Date"), .indexTZ = "UTC", class = c("xts", 
"zoo"), .indexCLASS = "Date", tclass = "Date", tzone = "UTC")

希望与 weighted.mean() 类似,但求和,或者如果有人可以建议我如何使用 tempWeights 对每列(滚动)求和。weighted.sum() 不做同样的事情。

tempRRI <- rollapplyr(tempVar, width = 3, function(x) {weighted.mean(x,tempWeights)}, by.column = TRUE) 

您通过将 weighted.mean() 乘以权重总和来调整公式:

tempRRI <- rollapplyr(tempVar, width = 3, function(x) {weighted.mean(x,tempWeights)*sum(tempWeights)}, by.column = TRUE)