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:

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()

(w1+w2=1)andw1,w2≥0surely we would always use the sum of variables that gave weight1to the variable with smaller variance and0to the one with larger variance? – nickponline Feb 26 '15 at 01:30w1=0,w2=1orw1=1,w2=0? Do you have a simple example? – nickponline Feb 26 '15 at 01:49