Matrix-based calculation of portfolio mean and variance
When \(w\) is the column-matrix of portfolio weights, \(\mu\) the column-matrix of expected returns, and \(\Sigma\) the return covariance matrix. Then the portfolio expected return is \(w'\mu\), and the portfolio variance is \(w'\Sigma w\). Remember that the portfolio's volatility is the square root of its variance.
You will practice matrix multiplication in R using the %*%
function, instead of the standard *
. In addition, you will transpose the matrices by using the standard function t()
. Remember that transposing a matrix is simply changing the rows of the matrix to the columns.
The weights, vector of means, and the covariance matrix are pre-loaded in your workspace as weights
, vmeans
, and sigma
, respectively.
This exercise is part of the course
Introduction to Portfolio Analysis in R
Exercise instructions
- Convert weights to a matrix called
w
usingas.matrix()
. - Convert the vector of means (
vmeans
) to a matrix calledmu
usingas.matrix()
. - Calculate portfolio mean monthly return. Remember the function
t()
transposes a vector. - Calculate the portfolio volatility.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Create a weight matrix w
# Create a matrix of returns
# Calculate portfolio mean monthly returns
# Calculate portfolio volatility
sqrt(t(___) %*% ___ %*% ___)