I have the following 2-column data.frame:
Data <- data.frame(matrix(rnorm(100),ncol = 2))
I would like to calculate the variance-covariance matrix as the exponentially weighted average of the past squared/cross observations (on an expanding window):
Where delta is set to be 60/61. Thus, at t=4, the sum runs from 1 to 4, and the averages are computed over the first 4 observations. I have managed to implement a function calculating the upper triangular part of the covariance matrix, but it is quite slow. Does anyone have ideas to improve the speed?
rollEWCov <- function(Data){
res <- c()
for(i in 1:nrow(Data)){ # Expanding window of data used to calc covariances
means <- colMeans(Data[1:i,])
Cov <- matrix(0,nrow = ncol(Data),ncol=ncol(Data))
for(k in 1:ncol(Data)){ # first data-column
l <- k
while(l <= ncol(Data)){ # second data-column
Sum <- 0
for(j in 1:i){ # calc sum of exponentially weighted average of past returns
Sum <- Sum + (1-60/61)*(60/61)^(j-1)*(Data[i-(j-1),k] - means[k])*(Data[i-(j-1),l] - means[l])
}
Cov[k,l] <- Sum
l <- l + 1
}
}
res[[i]] <- Cov
}
return(res)
}