古洛比有没有一个特定的绝对值方法?

2024-04-30 00:44:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想计算目标函数中两个矩阵之和的绝对值,但出于某种原因,我一直收到错误消息“一元操作数类型错误-:'GenExpr'”

#Data
hyperparameter = 0.5
weightss = np.array([0.25, 0.25, 0.25, 0.25])
weightss
transactional_costs = np.array([0.01, 0.01, 0.01, 0.01])
transactional_costs

# Add matrix variable for the stocks
x = m.addMVar(len(stocks))

# Objective is to maximize the return rate and minimize the risk
portfolio_objective = delta @ x - hyperparameter * (x @ sigma @ x) - gp.abs_(transactional_costs @ realweights - transactional_costs @ weightss)

m.setObjective(portfolio_objective, GRB.MAXIMIZE)

我曾尝试计算线投资组合目标之外的绝对值部分,但仍然遇到同样的问题。谁能给我指路吗

更新:数据来自雅虎财经

closes = np.transpose(np.array(data.Close)) # matrix of daily closing prices
absdiff = np.diff(closes)                   # change in closing price each day
reldiff = np.divide(absdiff, closes[:,:-1]) # relative change in daily closing price
delta = np.mean(reldiff, axis=1)            # mean price change
sigma = np.cov(reldiff)                     # covariance (standard deviations)
std = np.std(reldiff, axis=1)               # standard deviation

Tags: the目标错误npchangearraypricematrix
1条回答
网友
1楼 · 发布于 2024-04-30 00:44:33

我在Gurobi工作,我只是检查了源代码,并验证了绝对值函数不适用于Gurobi Python(gurobipy)矩阵接口。所以你有两个选择:

  1. 使用代数语法,它支持绝对值通用表达式

  2. 自己对绝对值函数进行建模;由于绝对值函数是凸函数,因此可以使用标准数学变换将abs(z)替换为zp+zn,其中z=zp-znzp,zn分别是表示绝对值函数正部分和负部分的非负决策变量

相关问题 更多 >