Scipy通过约束最大化

时间:2016-05-13 07:00:22

标签: pandas scipy minimize maximize

目的是找到每个因子的优化权重,以最大化特定值。 Scipy仅提供优化以最小化函数,因此我在此处使用负号来查找最大值。代码看起来不错,scipy最终可以成功终止,但没有返回任何解决方案。有人可以帮忙吗?

import pandas as pd
import numpy as np
from scipy.optimize import minimize

df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'))

# the sum of weights should be 1.
cons = ({'type': 'eq',
        'fun' : lambda x: np.array(sum(x)-1)},
        {'type': 'ineq',
        'fun' : lambda x: np.array([a for a in x])})

# wt should be a list like [0.2, 0.3, 0.5]
def optimizewt(wt):
    s = df[list('ABC')]
    r = df['D']

    # rule to calculate the weighted total score of each row
    ts = lambda x: x*wt

    # apply the rule to get weighted total scores
    f = ts(s)
    a = f.sum(axis = 1)

    # sort the list ascending
    a.sort(ascending=True)
    l = len(a)

    # replace the largest and smallest two scores. set others to 0.
    a[0:2] = 1
    a[(l-2):] = -1
    a[2:(l-2)] = 0

    # multiply the two lists. return the average of the calculated list.
    return -np.mean(a*r)

res = minimize(optimizewt, [0.5,0.5,0.], constraints=cons)

print(res.x)

0 个答案:

没有答案
相关问题