计算一个变量的20步总和

Calculate the 20 steps sum of a variable

我有一个投资组合回报率的每日数据库。对于我正在复制作者每月计算的模型,前 21 个会话中每日 returns 的已实现方差 RVt。

这里有一个小例子来说明我是如何计算它的:

x <- rnorm(24795, 0, 0.2) #Generate random numbers to simulate my sample
x_2 <-x^2 #the model specify to work with the square returns
# I need the monthly sum of the square returns. For this I create a matrix
#with the length if x/20 because each month consist in 20 trading sessions

rv <- matrix(NA, nrow=(length(x_2)/20), ncol=1) 

#I create the first step
rv[1] <- sum(x_2[1:20]) 

#I create a loop to make the sum of from x_2[21:40] and continue
# with this 20 steps sums
for (i in 2:1239){
  rv[i] <- sum(x_2[i+20:i+39]) 
}
rv

问题是我的循环总结为:

 x_2[21:40]
 x_2[22:41]
 x_2[23:42]

而不是

x_2[21:40]
x_2[41:60]
x_2[61:80]

有谁知道我做错了什么吗?

这是论文中公式的图片: Formula

谢谢

米格尔

我们可以使用seq

i1 <- seq(21, length(x_2), by = 20)
i1 <- i1[-length(i1)]
i2 <-  c(i1[-1] - 1, length(x_2))
head(i1)
#[1]  21  41  61  81 101 121
head(i2)
#[1]  40  60  80 100 120 140
rv[-1] <- unlist(Map(function(i, j) sum(x_2[i:j]), i1, i2))

-输出

> head(rv)
          [,1]
[1,] 1.0533125
[2,] 1.0914327
[3,] 0.7530577
[4,] 1.0559202
[5,] 0.6579956
[6,] 0.9139404
> tail(rv)
             [,1]
[1234,] 0.7115833
[1235,] 0.6104712
[1236,] 0.6161004
[1237,] 0.7440868
[1238,] 0.7284476
[1239,] 1.8718138

我们可以使用tapply将每20个数字分成一组。

result <- tapply(x_2, ceiling(seq_along(x_2)/20), sum)

验证结果-

head(result)
#        1         2         3         4         5         6 
#1.0872762 0.4487953 1.1764887 0.8852306 0.8394201 1.0295633 

sum(x_2[1:20])
#[1] 1.087276

sum(x_2[21:40])
#[1] 0.4487953

sum(x_2[41:60])
#[1] 1.176489