0

I am trying to write a portfolio optimization problem using cvxpy.

initial_weights = [0.045, 0.035, 0.024, 0.028...]
rets = (np.log(data/data.shift(1))
w = cvx.Variable(38)
ret = np.sum(rets.mean()*w)*252
prob = cvx.Problem(cvx.Maximize(ret), [cvx.sum_entries(w)==1, w>0.02, w<0.06])

result = prob.solve() After solving, w.value is of the form [[0.02], [0.02], [0.04]...]

I need to add more constraints like abs(list_final_weights-w)>0.005, but that will be possible if w.value is of the form of array of values instead of array of arrays. How can I fix this error?

Ray234
  • 173
  • 5
  • 15

1 Answers1

0

cvxpy does element-wise operations for subtraction, as long as they're of the same shape. You could convert your flat array into the appropriate shape that the solver needs - In this case it's (N, 1) instead of a flat array of shape (N,).

list_final_weights = np.reshape(list_final_weights, [len(list_final_weights), 1])

Then you should be able to do the subtraction for the constraint:

list_final_weights - w >= 0.005 

Also cvxpy does not allow hard > or < inequalities. Only <= and >=. https://www.cvxpy.org/tutorial/intro/index.html#constraints

Adarsh Chavakula
  • 1,509
  • 19
  • 28