首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >CVXPY:如何最大化两个向量的点积

CVXPY:如何最大化两个向量的点积
EN

Stack Overflow用户
提问于 2021-05-15 19:05:16
回答 1查看 579关注 0票数 0

假设我们有三个特征,每个特征有252个样本。这里,特征是三种不同股票的回报。目标是最大化总回报,即,

我的问题是如何在CVXpy优化问题中定义这个目标函数?

程序的过程视图应该如下所示:

代码语言:javascript
运行
复制
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)

但是,它会返回一个错误:

代码语言:javascript
运行
复制
ValueError: Cannot broadcast dimensions  (3, 252) (3,)

当我们将x表示为x = cvx.Variable(shape=(m,1))时,我们会得到另一个错误

代码语言:javascript
运行
复制
ValueError: The 'minimize' objective must resolve to a scalar.

Python版本: 3.8.8

CVXPY版本: 1.1.12

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-22 01:25:41

多亏了cvxpy社区,我重新表述了这个问题,现在它运行起来没有错误。

代码语言:javascript
运行
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67546018

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档