1

This is just a simple question but really taking my time as I am new in R.

I'm trying to write a code for the variance of a portfolio.

enter image description here

For example, I have the following :-

weight=c(0.3,0.2,0.5)
cov  = matrix( c(0.2, 0.4, 0.3, 0.4, 0.5, 0.3,0.3,0.3,0.4),nrow=3, ncol=3, byrow = TRUE)

for (i in 1:3){
for (j in 1:3) {
port = sum((weight[i]^2) * (cov[i,i]^2)) + sum(weight[i] *weight[j]* cov[i,j]) }}

The answer if I calculate manually should be 0.336. But R gave me port=0.12 which is wrong. Where is my mistake?

3
  • Your calculation for port is only for the i = 3 and j = 3, so your loop isn't doing anything. I'm guessing you want to save the previous value for port each time you loop through. Commented Feb 5, 2016 at 14:46
  • Yes. It is a summation. So I need the previous value to sum it up. Commented Feb 5, 2016 at 14:48
  • 3
    may be you wanted to do port <- port+sum and use port<-0 before loop Commented Feb 5, 2016 at 14:50

1 Answer 1

1

First calculate the matrix product w %*% t(w):

tcrossprod(weight)
#     [,1] [,2] [,3]
#[1,] 0.09 0.06 0.15
#[2,] 0.06 0.04 0.10
#[3,] 0.15 0.10 0.25

Then multiply this with the variance-covariance matrix and take the sum of all elements:

sum(tcrossprod(weight) * cov)
#[1] 0.336

Or as a loop (inefficient):

port <- 0
for (i in 1:3){
  for (j in 1:3) {
    port  <- if (i == j) {
      port + sum((weight[i]^2) * (cov[i,i]))
    } else {
      port + sum(weight[i] *weight[j]* cov[i,j])
    } 
  }
}
port
#[1] 0.336

Note that the variance-covariance matrix typically contains the variances (sigma_i^2) on the diagonal.

Sign up to request clarification or add additional context in comments.

2 Comments

Are you sure the answer is 0.336? I think I have calculated and my answer is 0.2516. But I may be wrong. I will check again. Thanks
@nsaa See the note at the end of my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.