我试图在设置约束时最小化目标函数,使得x中的所有元素都相同。我的挑战是x中的元素数量不固定。现在,我有约束1:x [0] = x [1],约束2:x [1] = x [2]等。但是,元素的数量可以增长,我不能预设所有的限制。我想知道我是否可以使用循环来更动态地设置这些约束?
'Minimize risks'
def objective(x):
x = np.matrix(x)
return x.dot(covariance_matrix).dot(x.transpose())
'Make sure weight_AC equals weight_BB'
def constraint1(x):
x = np.matrix(x)
return np.float(x[0,0]) - np.float(x[0,1])
'Make sure weight_BB equals weight_GS'
def constraint2(x):
x = np.matrix(x)
return np.float(x[0,1]) - np.float(x[0,2])
'Make sure weight_GS equals weight_AAPL'
def constraint3(x):
x = np.matrix(x)
return np.float(x[0,2]) - np.float(x[0,3])
'Total weight equals 1'
def constraint4(x):
x = np.matrix(x)
result = 1
for i in range(0,x.size):
result = result - x[0,i]
return result
con1 = {'type': 'eq', 'fun': constraint1}
con2 = {'type': 'eq', 'fun': constraint2}
con3 = {'type': 'eq', 'fun': constraint3}
con4 = {'type': 'eq', 'fun': constraint4}
cons = ([con1, con2, con3, con4])
solution = minimize(objective,x0,method='SLSQP',constraints = cons)