我想计算目标函数中两个矩阵之和的绝对值,但出于某种原因,我一直收到错误消息“一元操作数类型错误-:'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
我在Gurobi工作,我只是检查了源代码,并验证了绝对值函数不适用于Gurobi Python(gurobipy)矩阵接口。所以你有两个选择:
使用代数语法,它支持绝对值通用表达式
自己对绝对值函数进行建模;由于绝对值函数是凸函数,因此可以使用标准数学变换将
abs(z)
替换为zp+zn
,其中z=zp-zn
和zp,zn
分别是表示绝对值函数正部分和负部分的非负决策变量相关问题 更多 >
编程相关推荐