I am trying to compute a rolling window (shifting by 1 day) covariance matrix for a number of assets.
Say my df looks like this:
df <- data.frame(x = c(1.5,2.3,4.7,3,8.4), y =c(5.3,2.4,8.4,1.3,2.5),z=c(2.5,1.3,6.5,4.3,2.8),u=c(1.1,2.5,4.3,2.5,6.3))
I expect the output to look like following :
cov(df[1:3,]) :
x y z u
x 2.773333 3.666667 4.053333 2.613333
y 3.666667 9.003333 7.846667 2.776667
z 4.053333 7.846667 7.413333 3.413333
u 2.613333 2.776667 3.413333 2.573333
cov(df[2:4,]) :
x y z u
x 1.523333 4.283333 3.053333 1.23
y 4.283333 14.603333 7.253333 3.93
z 3.053333 7.253333 6.813333 2.22
u 1.230000 3.930000 2.220000 1.08
cov(df[3:5,]) :
x y z u
x 7.6233333 -0.5466667 -3.008333 5.1633333
y -0.5466667 14.4433333 5.941667 0.9233333
z -3.0083333 5.9416667 3.463333 -1.5233333
u 5.1633333 0.9233333 -1.523333 3.6133333
But everything made in a loop because I have a lot of rows in the data set…
-
How would a possible
forloop look like if I want to calculate a covariance matrix on a rolling basis by shifting the rolling window by 1 day? Or should I use someapplyfamily function? -
What time series class would be preferrable if I want to create a time series object for the loop above? Now I use
as.timeSeriesfromfPortfoliopackage.
I simply can’t get it…
Best Regards
To create your rolling windows you could use
embed.EDIT: for time series you could use package
xtsand its functionsendpoints,period.apply,apply.daily, …