优化函数求最大值

2024-04-18 19:50:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数,我想最大化超额收益取决于分配给输入的权重。输入不是持有量的典型权重,而是分配给特定输入数据的权重。然后根据分配给它们的权重来累积输入数据,从而创建一个新变量。选择前三大持股,然后确定这三大持股的超额收益率高于基准。我的目标是通过对输入数据进行完美的权值组合,最大限度地提高3种持股的超额收益。本质上,我想知道什么样的输入变量组合创造了最高的预期回报。你知道吗

下面是我到目前为止的代码。不幸的是当我运行scipy.优化.最小化,它根本不会改变重量。对于每个输入变量,我从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)

主要数据如下:

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

我非常感谢你的帮助!你知道吗


Tags: the数据lennanlongreturnspd权重