【问题标题】:CVXPY: How to maximize dot product of two vectorsCVXPY:如何最大化两个向量的点积
【发布时间】:2021-08-05 07:38:20
【问题描述】:

假设我们有三个特征,每个特征有 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

【问题讨论】:

  • 您的returns 是一个矩阵。它应该是一个向量(与 x 长度相同)。
  • 感谢您的评论+1;请参阅发布的答案。
  • @sci9,刚刚发现这个javacodexamples.com/examples/…。是你发的吗?还是这是公然抄袭?

标签: python optimization array-broadcasting portfolio cvxpy


【解决方案1】:

感谢 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-01
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 2016-05-07
    • 2017-10-21
    相关资源
    最近更新 更多