0

I'm trying to implement finding the weight that minimize the variance of the sum of random variables. I followed the formula from this question Minimizing the variance of weighted sum of two random variables with respect to the weights but when I plot the result the weight is neither between 0 and 1 nor the weight that minimizes the variance:

enter image description here

Can anyone please help me see where I went wrong:

import numpy as np
import pylab

def cov(X, Y):
    M = np.vstack((X, Y))
    M = np.cov(M)
    return M[0][1]

def var(X):
    return np.var(X)

def minimize(X,Y):
    num = cov(X, Y) - var(Y)
    den = var(X) - 2*cov(X,Y) + var(Y)
    w = -num/den
    return w # Should be 0 <= W <= 1 ?

X = np.array([1,4,6,3,6,3,6,2,6])
Y = np.array([1,5,9,6,8,4,9,5,9])

minw   = minimize(X, Y)
minvar = var( minw * X + (1.0-minw) * Y)

pylab.figure()

w = np.linspace(-100, 100.0, 100)
z = [ var( wi*X + (1.0-wi)*Y ) for wi in w]
pylab.plot(w, z, 'k.')

pylab.plot(minw, minvar, 'go')
pylab.xlabel('w')
pylab.ylabel('Var(w*X + (1-w)*Y)')
pylab.show()

1 Answers1

0

There seems to be nothing wrong with your code on finding the weights that minimized the variance. Besides Calculus to get the minimum variance where you cannot enforce the constraint that $(w_1 +w_2 =1)$ and $w_1, w_2\ge0$. If you do it in EXCEL Solver and provide these additional constraints, you will find the $w_1$ to be one that gives the minimum variance of x+y to be that of x. In finance when weights are more than 1, we call it short selling ( that is you borrow money to additonally invest on asset X, assuming the the numbers are returns of assets X and Y).

enter image description here

  • That's interesting thanks, given that we enforce (w1+w2=1) and w1,w2≥0 surely we would always use the sum of variables that gave weight 1 to the variable with smaller variance and 0 to the one with larger variance? – nickponline Feb 26 '15 at 01:30
  • You are right, if you changed the data a little bit may be you will have weights less than 1. If your data were to be returns of X and Y, what it means is shortsell on asset X and sell of Y to the negative weight that you from subtracting 1-1.28= 0.28% of the existing value of the assets. Try some other data and see the calculus way works reasonably. If you find my answer useful, do accept the answer – Satish Ramanathan Feb 26 '15 at 01:44
  • I can't see to create a dataset for X and Y that give weights that aren't w1=0,w2=1 or w1=1,w2=0? Do you have a simple example? – nickponline Feb 26 '15 at 01:49
  • See the edit. I have included a data set for which I used the calculus method got a minimum variance. Good luck – Satish Ramanathan Feb 26 '15 at 02:48