Daniel Abramov
Daniel Abramov

Reputation: 41

How to create bound in scipy.optimize so optimizer can't reach more than 1 in summary of vector?

I have a function what takes params as vector. I need to restrict any of the vector variables be less than 0 and vector should be summary equal to 1

I've tried to find something in goolge and scipy docs. No luck so far.

def portfolio_optimization(weight_vector):
    return np.sqrt(cov_table.dot(weight_vector).sum())

bound what I need to apply:

sum(weight_vector) = 1
0 < weight_vector[i] < 1

Upvotes: 1

Views: 2460

Answers (1)

SuperKogito
SuperKogito

Reputation: 2966

The first condition is a constraint (sum(w)=1), as for the second you can use bounds for it. Here is a small example on how to use scipy.optimize.minimize with a weights vector having 4 elements:

import numpy as np
from scipy.optimize import minimize


# objective function
func   = lambda w: np.sqrt(cov_table.dot(w).sum())

# constraint: sum(weights) = 1
fconst = lambda w: 1 - sum(w)
cons   = ({'type':'eq','fun':fconst})

# initial weights
w0   = [0, 0, 0, 0]

# define bounds
b    = (0.0, 1.0) 
bnds = (b, b, b, b)

# minimize
sol  = minimize(func,
                w0,
                bounds      = bnds,
                constraints = cons)
print(sol)

*Don't forget to assign a value to cov_table for the code to work.

Upvotes: 4

Related Questions