python - CVXPY:如何最大化两个向量的点积
问题描述
假设我们有三个特征,每个特征有 252 个样本。在这里,特征是三种不同股票的回报。目标是最大化总回报,即
我的问题是如何在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
解决方案
感谢 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])
m = returns.shape[0]
cov = np.cov(returns)
x = cvx.Variable(m)
portfolio_return = returns.mean(axis=1)
objective = cvx.Maximize(x @ portfolio_return)
constraints = [x >= 0, sum(x) == 1]
cvx.Problem(objective, constraints).solve()
x_values = x.value
x_values.round(2)
推荐阅读
- python-3.x - 使用 LinkExtractor 的 Scrapy 不从网站中提取链接
- jquery - 根据条件格式化选项文本
- ejb - 在会话 bean 和实体 bean 上定义资源引用标签
- ruby-on-rails - Rails - Passing a specific column to query by count of an associated model
- datetime - 必要时修复格式以包含前导零
- java - 如何为 JFrame 中的对象实现 KeyListener?
- excel - excel“插入行”导致target.offset错误
- android-studio - android studio中出现错误如何显示在行的左边
- jquery - 是否可以在 datalist 中使用 select2 以及如何使用?
- oracle - 找出 SDO_ORDINATE_ARRAY 属性中包含的坐标格式