hi,
Please help me in calculating variance and covariance as i am getting the
following error
Error in lambda * S + (1 - lambda) * a : non-conformable arrays
---------- Forwarded message ----------
From: G Girija <girijagun@gmail.com>
Date: Thu, Jul 18, 2013 at 10:20 PM
Subject: extracting variance and covariance
To: r-help@r-project.org
Hi,
I am not able to ‘extract variance and covariance’
As mentioned, there are 5 stocks and changed the code [
http://www.forecastingfinancialrisk.com/3.html] as follows:
> S<-cov(returns)
> S
V1 V2 V3 V4 V5
V1 0.0004951526 0.0001256519 0.0001651016 0.0003024310 0.0003516796
V2 0.0001256519 0.0008076471 0.0001251208 0.0002005305 0.0002347568
V3 0.0001651016 0.0001251208 0.0010000707 0.0003158028 0.0003682633
V4 0.0003024310 0.0002005305 0.0003158028 0.0011405561 0.0008442661
V5 0.0003516796 0.0002347568 0.0003682633 0.0008442661 0.0018536153
> EWMA[1,]<-c(S)[c(1,10,5)]
> a=t(as.numeric(returns$i)) %*% as.numeric(returns$i) ---*Here we need
to change dataframe to numeric, that too only columns.*
> str(a)
num [1, 1] 0
> dim(a)
[1] 1 1
> dim(lambda*S)
[1] 5 5 ---------*As the dimensions are not same we can not do
‘%*%’*
> dim((1-lambda)*a)
[1] 1 1
for(i in 2:T)
{
S<- lambda*S+ (1-lambda)*t(returns$i) %*% returns$i
EWMA[i,]=c(S)[c(1,4,2)]
}
*Original code as per* http://www.forecastingfinancialrisk.com/3.html is
EWMA = *matrix*(*nrow*=T,*ncol*=3) *# create a matrix to hold the
covariance matrix for each t*
lambda = 0.94
S = *cov*(y) *# initial (t=1) covariance matrix*
EWMA[1,] = *c*(S)[*c*(1,4,2)] *# extract the variances and covariance*
*for* (i *in* 2:T){ *# loop though the sample*
S = lambda * S + (1-lambda) * *t*(y[i]) %*% y[i]
[[alternative HTML version deleted]]