如何解决CVXPY:如何最大化两个向量的点积
假设我们有三个特征,每个特征有 252 个样本。在这里,特征是三只不同股票的回报。目标是使总回报最大化,i,e,
我的问题是如何在 CVXpy
优化问题中定义这个目标函数?
程序的程序视图应该是这样的:
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)
然而,它返回一个错误:
ValueError: Cannot broadcast dimensions (3,252) (3,)
当我们将 x 表示为 x = cvx.Variable(shape=(m,1))
时,我们会得到另一个错误
ValueError: The 'minimize' objective must resolve to a scalar.
Python 版本:3.8.8
CVXPY 版本:1.1.12
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。