Suppose we have three features and 252 samples per each feature. Here, features are returns of three different stocks. The goal is to maximize the total return, i,e,
My question is how to define this objective function inside a CVXpy
optimization problem?
The procedural view of the program should be look like this:
import numpy as np
import cvxpy as cvx;
return1 = np.random.normal(loc=0.05, scale=0.25, size=252)
return2 = np.random.normal(loc=0.01, scale=0.2, size=252)
return3 = np.random.normal(loc= -0.05, scale=0.15, size=252)
returns = np.array([return1, return2, return3])
# number of stocks m is number of rows of returns
m = returns.shape[0]
# x variables (to be found with optimization)
x = cvx.Variable(m)
# portfolio return
portfolio_return = cvx.multiply(returns, x)
#objective function
objective = cvx.Minimize(-portfolio_return)
#constraints
constraints = [x >= 0, sum(x) == 1]
#use cvxpy to solve the objective
cvx.Problem(objective, constraints).solve()
#retrieve the weights of the optimized portfolio
x_values = x.value
print(x_values)
However, it returns an error:
ValueError: Cannot broadcast dimensions (3, 252) (3,)
When we represent x as x = cvx.Variable(shape=(m,1))
we get another error
ValueError: The 'minimize' objective must resolve to a scalar.
Python Version: 3.8.8
CVXPY Version: 1.1.12