Computing Quadratic Variation in R
-
23-06-2021 - |
Domanda
In order to compute the quadratic variation of a timeseries in R, I would like to to sum for every point the square of log returns of the current point and the last x points.
I know that you can build the square of log returns of py by typing
diff(log(py))^2
However how can I build a timeseries which is summing at every point the last 5 points in order to build the quadratic variation ?
Soluzione
The function embed
combined with rowSums
gives what you need:
cbind(
AirPassengers,
sum5=c(rep(NA, 4), rowSums(embed(AirPassengers, 5)))
)
AirPassengers sum5
Jan 1949 112 NA
Feb 1949 118 NA
Mar 1949 132 NA
Apr 1949 129 NA
May 1949 121 612
Jun 1949 135 635
Jul 1949 148 665
...
What embed
does is to create a matrix with lagged values of your initial vector:
embed(AirPassengers, 5)
[,1] [,2] [,3] [,4] [,5]
[1,] 121 129 132 118 112
[2,] 135 121 129 132 118
[3,] 148 135 121 129 132
[4,] 148 148 135 121 129
[5,] 136 148 148 135 121
[6,] 119 136 148 148 135
[7,] 104 119 136 148 148
[8,] 118 104 119 136 148
...
You can them use rowSums
or any other manipulation on the rows of this matrix.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow