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