4
$\begingroup$

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 <= 40)

I am not so familiar with the Scipy minimize, and I would appreciate if someone can help me.

$\endgroup$
1
  • $\begingroup$ whats the problem exactly, given that we cant replicate it because we dont have the dataset? from here looks solid. Give us the error $\endgroup$
    – Noah Weber
    Commented Dec 20, 2019 at 8:20

1 Answer 1

1
$\begingroup$

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

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

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

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

While indexing desired columns inside of the lambda function.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.