Calculate the 20 steps sum of a variable

Viewed 49

I have a daily data base of retunrs from a portfolio. For a model I am replicating the authors calculate for each month, the realized variance RVt from daily returns in the previous 21 sessions.

To do this here is a small example of how I am trying to calculate it:

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

The problem is that my loop is summing as:

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

instead of

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

Does anyone knows what I a doing wrong?

Here is a picture of the forula from the paper: Formula

Thanks

Miguel

2 Answers

We could use 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))

-output

> 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

We can use tapply dividing every 20 numbers in a group.

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

Verify the result -

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
Related