优化功能以找到最大值

时间:2017-02-19 16:23:22

标签: python pandas numpy optimization scipy

我有一个函数我想根据分配给输入的权重最大化超额回报。输入不是持有的典型权重,而是分配给特定输入数据的权重。然后,基于分配给它们的权重累积输入数据以创建新变量。选择前3个持股,然后通过基准确定这3个持股的超额回报。我的目标是通过对输入数据进行权重的完美组合,最大化3个馆藏的超额收益。本质上,我想知道输入变量的哪种组合创造了最高的预期回报。

以下是我目前所拥有的代码。不幸的是,当我运行scipy.optimize.minimize时,它根本不会改变权重。我为每个输入变量以0.5开始它们,最后它们保持在0.5。

weights = np.array([0.5]*len(maindata.columns))

def ret(weights):

    spyreturn = pd.Series()
    portfolioreturn = pd.Series()

    maindata = pd.DataFrame(maindata*weights).sum(axis=1)
    holdings = maindata.sort_values(ascending=False)[:longamount]

    returns = pd.read_csv('Pulls in the daily return data for the stocks from computer')
    returns = returns.set_index('Date')

    spyreturns = pd.read_csv('Pulls in the daily return data for the benchmark from computer')
    spyreturns = spyreturns.set_index('Date')

    long['weight'] = 1/len(long)

    longreturns = returns[long.index]

    longreturns.replace(np.NaN,0,inplace=True)
    weightlong = longreturns*(1/len(long))

    longportfolio = weightlong.sum(axis=1)

    totalportfolio = longportfolio
    totalportfolio = totalportfolio[1:]
    portfolioreturn = portfolioreturn.append(totalportfolio)
    spyreturns = spyreturns[1:]
    spyreturn = spyreturn.append(spyreturns)

    portfolioreturn1 = portfolioreturn+1
    portfolioreturncum = portfolioreturn1.cumprod()-1
    del spyreturn[0]
    spyreturns1 = spyreturn+1
    spyreturnscum = spyreturns1.cumprod()-1

    excessreturn = float(portfolioreturncum[-1:])-float(pd.Series(spyreturnscum[-1:]))
    excessreturn = excessreturn*-1
    return excessreturn

from scipy.optimize import fmin_ncg, fmin
results = fmin_ncg(ret,weights)

以下是maindata:

ticker,column0,column1,column2,column3,column4                                                       
IQ112350,  4.003915,       NaN,       NaN,  0.730028,  3.740035   
IQ121729, -1.812199,  0.080070, -1.044188, -1.367218, -1.560262   
IQ126269,  1.579733, -0.073775,  0.384691,  0.605217,  1.197185   
IQ128209,  0.640059,       NaN,       NaN,  0.347553,       NaN   
IQ140283, -1.569323, -0.168380, -1.269472, -0.044812,       NaN   
IQ19691,   0.263715,  0.126087,  0.371266,  0.386789,  0.498745   
IQ21127,   0.264036,  1.394952,  0.875616,       NaN,  0.180892   
IQ21171,  -0.059215,  0.128939,  0.844162,  2.702458,       NaN   
IQ21835,   1.184896,  1.439033,  0.727373,  0.701876,  0.999958   
IQ22247,   0.371498,  0.482316,  0.446124,  0.432492,  2.579207

我非常感谢任何帮助!

0 个答案:

没有答案