You need to be careful how you index. In the example code, y is a 'zoo
series' and y[i] is gives the ith row, as in y[i, ]. This means t(y[i])
%*% y[i] is actually a 2X2 matrix. Also, the code c(S)[c(1,4,2)] picks
off the diagonal and lower triangular elements. The example involves two
stocks, so there are 3 elements. When you expand the example to 5 stocks,
there will be 15 elements (5 variances and 10 covariances). Rather than
manually selecting the elements you can use something like this:
EWMA[i,]
<- S
[lower.tri(S,diag=TRUE)]
Note, however, that you'll have to change the indexing in the final step if
you use this code.
Lastly, if you are expanding the code for five stocks, the returns matrix
should have 5 columns --- one for each stock. Then,
t(returns[i, ]) %*% returns[i, ]
will be 5X5 just as lambda * S is.
On Tue, Jul 23, 2013 at 5:29 AM, G Girija <girijagun@gmail.com> wrote:
> Hi,
> I have 5 stock values and i am calculating EWMA
> followed the logic as given ind following link.[
> http://www.orecastingfinancialrisk.com/3.html<
> http://www.forecastingfinancialrisk.com/3.html>
> ]
>
> [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 covariancefor (i
> in 2:T){ # loop though the sample
> S = lambda * S + (1-lambda) * t(y[i]) %*% y[i]
> EWMA[i,] = c(S)[c(1,4,2)] # convert matrix to vector }
> EWMArho = EWMA[,3]/sqrt(EWMA[,1]*EWMA[,2]) # calculate correlations
> ]
>
>
>
> EWMA[1,]<-c(S)[c(1,7,13,19,25,5)] --I am taking all diagonal values and
one
> more value. ---Is it correct????
>
> my returns matrix dim is 1x2496 and its transpose is 2496x1.
> so the resultant matrix will be 1x1.
> but we are adding it to lambda*S which is 5x5 matrix.----may be I am
> getting error because of this. How to overcome this error? Pl help
>
> Error in lambda * S + (1 - lambda) * t(as.matrix(returns[i])) %*%
> (as.matrix(returns[i])) :
> non-conformable arrays
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
[[alternative HTML version deleted]]