2

I am using SciPy to minimize the variance:

port_returns=[]
port_variance=[]
for p in range(4000):
    weights = np.random.random(5)
    weights /=np.sum(weights)
    port_returns.append(np.sum(returns.mean()*245*weights))
    port_variance.append(np.sqrt(np.dot(weights.T, np.dot(returns.cov()*245, weights))))

def min_variance(weights):
    return np.array(port_variance)

cons = {'type':'eq', 'fun':lambda x: np.sum(x)-1}    
bnds = tuple((0,1) for x in range(245))
optv = sco.minimize(min_variance, 245*[1.0/245,], method='SLSQP', 
                    bounds=bnds, constraints=cons)

I tried to run this function but got the error below:

File "D:\Python27\lib\site-packages\scipy\optimize\_minimize.py", line 458, in minimize
  constraints, callback=callback, **options)    
File "D:\Python27\lib\site-packages\scipy\optimize\slsqp.py", line 370, in _minimize_slsqp
  raise ValueError("Objective function must return a scalar")    
ValueError: Objective function must return a scalar

How can I return a scalar value?

4
  • How can I return a scalar value? Just do it :) Seriously, show us the implementation of the objective function min_variance and the data that goes in, then somebody may be able to tell you how to fix the problem. Commented May 17, 2017 at 6:08
  • Welcome to Stack Overflow! You can take the tour first and learn How to Ask a good question and create a Minimal, Complete, and Verifiable example. That makes it easier for us to help you. As a minimum, this question does not tell us what noa or min_variance is. Commented May 17, 2017 at 6:10
  • 3
    "np.array([port_returns,port_variance,port_returns/port_variance])": you'll want to minimize one of these, not all three. Commented May 17, 2017 at 10:01
  • Even with the added code it's hard to tell what is your minimization variable. It sort of looks like weights but port_variance is calculated before hand. And as for the immediate error, min_variance returns an array, not a single 'cost' value. I suspect you need to step back and run some demo cases, to get a clearer idea of what this function is doing. Commented May 17, 2017 at 15:57

1 Answer 1

1

upgrade scipy to v1.0. It was a bug in 0.19

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.