0

I would like to calculate the absolute value of the sum of two matrices in my objective function but for some reason I kept on getting the error message " bad operand type for unary -: '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)

I have tried calculating the part for the absolute value outside the line portfolio_objective but I still encounter the same problem. Could someone give me a direction?

Update: the data is from yahoo finance

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
edwina lai
  • 37
  • 3
  • what is `delta @x` ? Did you mean to multiply them? – Albin Paul Aug 20 '21 at 12:31
  • 1
    Please provide a [minimal **reproducible** example](https://stackoverflow.com/help/minimal-reproducible-example). Otherwise it's hard to help since there are still multiple variables missing. And please [don't upload images of your code](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question). – joni Aug 20 '21 at 12:57
  • yes, delta and x are both matrices – edwina lai Aug 20 '21 at 14:53

1 Answers1

0

I work at Gurobi and I just checked the source code and verified that the absolute value function is not available for the Gurobi Python (gurobipy) matrix interface. So you have two options:

  1. Use the algebraic syntax, which supports absolute value general expressions.

  2. Model the absolute value function yourself; since your absolute value function is convex, you can use the standard mathematical transformation to replace abs(z) by zp+zn, where z=zp-zn and zp,zn are nonnegative decision variables that represent the positive and negative portion of the absolute value function, respectively.

Greg Glockner
  • 5,433
  • 2
  • 20
  • 23
  • Thank you for your suggestions. I am trying to understand it as I am still a beginner (sorry for that): so abs(z), where z = zp-zn, should be replaced by zp+zn? Thank you again for your time! Your help is greatly appreciated! – edwina lai Aug 21 '21 at 15:54