Question on Scipy - Minimize. Adding additional constraints I am trying to using scipy minimize function for the following optimization:

V = np.matrix(pd.read_csv('V.csv'))`

R = np.matrix(pd.read_csv('R.csv', index_col = 'Ticker'))`

w0= list()
for i in range(0, 84):
    w0.append(1/84)

def calculate_portfolio_var(w,V):
    w = np.matrix(w)
    return (w*V*w.T)[0,0]

cons = ({'type': 'eq', 'fun': lambda x:  np.sum(x)-1.0})
myBound = [(0, 1) for i in range(0, 84)]
res= minimize(calculate_portfolio_var, w0, args=V, method='SLSQP',constraints=cons, bounds = myBound)


where V is the variance-covariance matrix, R is the series of annualized return of stocks.

In addition to the 2 constraints (cons and myBound), I want an additional constraint that the result portfolio return, which is the weighted average of the result weights and stock returns, be equal to certain number and the number of stocks to be less than equal to certain number..

For example, it should look like:

cons = ({'type': 'eq', 'fun': lambda x:  np.sum(x)-1.0},
        {'type': 'eq', PortfolioReturn = 10%,
        {'type': 'ineq', number of result stocks &lt;= 40)


I am not so familiar with the Scipy minimize, and I would appreciate if someone can help me.
I assume problem is in accessing your columns, elements of the V matrix, since you say:
"it should look like:"

Well to actually write down these constraints, you just need to access your columns in the functions your defined in the cons dictionary.

Lets say you have your data V

&gt; array([[ 0.00749589,  0.01255155,  0.02396251,  0.04750988, 0.09495377]
&gt;        [ 0.01255155,  0.02510441,  0.04794055,  0.09502834,  0.18996269],
&gt;        [ 0.02396251,  0.04794055,  0.09631614,  0.19092151,  0.38165151],
&gt;        [ 0.04750988,  0.09502834,  0.19092151,  0.38341252,  0.7664427 ],
&gt;        [ 0.09495377,  0.18996269,  0.38165151,  0.7664427,   1.53713523]])


You should define your constraints dictionary in the following way (for example):

&gt; cons = ({'type': 'eq', 'fun': lambda x:  x[0] - 2 * x[1] + 2},  
&gt; {'type': 'ineq', 'fun': lambda x: -x[0] - 2 * x[1] + 6},       
&gt; {'type': 'ineq', 'fun': lambda x: -x[0] + 2 * x[1] + 2})


While indexing desired columns inside of the lambda function.