Monday, October 10, 2016

Minimum Variance Portfolio with R and MATLAB

Minimum variance portfolio of risky assets that bears the lowest risk level of expected rate of return. This article shows how to program using R and MATLAB

First you create a matrix of random returns. Using real data is encouraged but not required. In R you need quadprog package to solve the QP optimization problem, so you will have
require(quadprog)
or
library(quadprog)

at the top of the program. Then generate returns with mean and standard deviation parameters. The array has ns rows/observations and na columns/variables

na <- 20
ns <- 100

returns  <- array(rnorm(ns*na, mean = 0.001, sd = 0.005), dim = c(ns,na))
Note that R solves

$$min\, c^{'}w+1/2w^{'}Qw$$

subject to the constraints, while you need just the quadratic term. So you need to make c a zero vector, which is done by dvec = rep(0,20) in the function call. And Q is twice the covariance matrix. A and a contain the equality constraints, here meaning sum of all the weights = a = 1

Q <- 2 * cov(returns)

A <- rbind(rep(1,20))

a <- 1

B <- rbind(diag(na))

b <- rbind(array(0, dim = c(na,1)))

Note that B and b contain the inequality constraints that say individual weights are greater than or equal to 0.

Then comes the call to solve.QP. The parameter meq = 1 to tell it that there is 1 equality constraint on the top of the constraint matrix Amat and bvec (and there is just one in this case, no inequality constraint).

result <- solve.QP(Dmat = Q, dvec = rep(0,20), Amat = t(rbind(A,B)), bvec = rbind(a,b), meq  = 1)
Then get the result

w <- result$solution

Then the weights are:

 
w
[1] 0.042753543 0.043274802 0.032720692 0.052568580 0.002538901 0.084979023 0.041237919 0.071080501 0.020027778
[10] 0.019911924 0.062425080 0.037147835 0.115155891 0.038342951 0.028615360 0.054265149 0.040568791 0.052440092
[19] 0.086009247 0.073935940
Coding in MATLAB is similar. Again here c is a vector of all zeros. B and b represent the constraints that individual weights are positive (no short sales). You need the negative sign as the constraints in MATAB use $&\leq$ but you need $&\geq$, so multiplying both sides with -1 changes the sign.

returns = 0.001 + randn(ns, na) * 0.005;
Q = 2 * cov(returns);
c = zeros(1,na);
A = ones(1,na);
a = 1; 
B = -eye(na);
b = zeros(na,1);
w = quadprog(Q,c,B,b,A,a);