Search code examples
pythonoptimizationportfoliocvxpyconvex-optimization

Python - portfolio opimisation using CVXPY - DCP rules not followed


I have a problem related to portfolio opimisation, I am trying to maximise an objective which is: say I have column A, and solution weights, my objective is to minimise the sum of [(weights - column A)^ 2 / column A], in other words, it's a problem of squared difference divided by column A, and I would like to minimise the sum of those.

import cvxpy as cp

# size 50, as there are 50 values in column A, and I would like to have 50 individual weights
wts = cp.Variable(50)

# Some constraints, i.e. total weights = 100%, and the sum of weights of index positions 1, 2, 3,  4 to be less than 0.50.
constraints = [cp.sum(wts) == 1.0]
constraints = constraints.append([cp.sum(wts[[1,2,3,4]]) <0.50])

# Objective
sum_square = cp.sum(cp.square(wts-index_data['A'].values) / index_data['A'].values)
prob = cp.Problem(cp.Minimize(sum_square), constraints)

prob.solve()

which unfortunately did not work for me, is there some function that I'm unaware of? or is there any problem with the set up of my problem? as I get

cvxpy.error.DCPError: Problem does not follow DCP rules. Specifically:
The objective is not DCP. 

Solution

    1. See https://stackoverflow.com/help/minimal-reproducible-example how to create a minimum reproducible example

    2. A < constraint is not allowed. It should be <=. You should have seen some error messages that are difficult to ignore.

    3. You can't use np.square inside a CVXPY model. (Also the relevant import is missing: this should have given obvious error messages). Try cp.square.