human
I am working on the file "2__Optimizing_Portfolios.ipynb".
The first task is:
Finally, let's see how Basin Hopping behaves best working with bonds and constraints.
Can you write Python code for it?

Give me a the Python code you requested?
assistant
#Here is the Python code you requested.

 class MyBounds(object):
        def __init__(self, xmax=[1.0,1.0,1.0,1.0,1.0], xmin=[0,0,0,0,0] ):
            self.xmax = np.array(xmax)
            self.xmin = np.array(xmin)
            
        def __call__(self, **kwargs):
            x = kwargs["x_new"]
            tmax = bool(np.all(x <= self.xmax))
            tmin = bool(np.all(x >= self.xmin))
            cons = bool(np.sum(x) <= 4)
            return tmax and tmin and cons
        
mybounds = MyBounds()

res = basinhopping(rosen, [1.3, 0.7, 0.8, 1.9, 1.2], minimizer_kwargs={"method": "BFGS"},
                   niter=200,accept_test=mybounds)

print(">>> basinhopping min: "+str(res.x)+" - min_value:"+str(rosen(res.x)))