Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
提高Python for循环的性能?_Python_Python 3.x_Pandas_Dataframe - Fatal编程技术网

提高Python for循环的性能?

提高Python for循环的性能?,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,Dataframe,我试图写一个代码来构造数据框架,它由投资组合的协整对组成,股票价格是协整的。在这种情况下,投资组合中的股票从标准普尔500指数中选择,它们的权重相等 此外,对于某些经济问题,投资组合必须包括相同的部门 例如: 如果一个投资组合中的股票来自[IT]和[Financial]部门,则第二个portoflio必须选择[IT]和[Financial]部门的股票 一个投资组合中没有正确数量的股票,所以我考虑每个投资组合中大约有10到20只股票。然而,当考虑到组合时,这是500选择10,所以我有一个计算时间的

我试图写一个代码来构造数据框架,它由投资组合的协整对组成,股票价格是协整的。在这种情况下,投资组合中的股票从标准普尔500指数中选择,它们的权重相等

此外,对于某些经济问题,投资组合必须包括相同的部门

例如: 如果一个投资组合中的股票来自[IT]和[Financial]部门,则第二个portoflio必须选择[IT]和[Financial]部门的股票

一个投资组合中没有正确数量的股票,所以我考虑每个投资组合中大约有10到20只股票。然而,当考虑到组合时,这是500选择10,所以我有一个计算时间的问题

以下是我的代码:

def adf(x, y, xName, yName, pvalue=0.01, beta_lower=0.5, beta_upper=1):
    res=pd.DataFrame()
    regress1, regress2 = pd.ols(x=x, y=y), pd.ols(x=y, y=x)
    error1, error2 = regress1.resid, regress2.resid
    test1, test2 = ts.adfuller(error1, 1), ts.adfuller(error2, 1)
    if test1[1] < pvalue and test1[1] < test2[1] and\
    regress1.beta["x"] > beta_lower and regress1.beta["x"] < beta_upper:
        res[(tuple(xName), tuple(yName))] = pd.Series([regress1.beta["x"], test1[1]])
        res = res.T
        res.columns=["beta","pvalue"]
        return res
    elif test2[1] < pvalue and regress2.beta["x"] > beta_lower and\
    regress2.beta["x"] < beta_upper:
        res[(tuple(yName), tuple(xName))] = pd.Series([regress2.beta["x"], test2[1]])
        res = res.T
        res.columns=["beta","pvalue"]
        return res
    else:
        pass




def coint(dataFrame, nstocks = 2, pvalue=0.01, beta_lower=0.5, beta_upper=1):
    # dataFrame = pandas_dataFrame, in this case, data['Adj Close'], row=time, col = tickers
    # pvalue = level of significance of adf test
    # nstocks = number of stocks considered for adf test (equal weight)
    # if nstocks > 2, coint return cointegration between portfolios
    # beta_lower = lower bound for slope of linear regression
    # beta_upper = upper bound for slope of linear regression

    a=time.time()
    tickers = dataFrame.columns
    tcomb = itertools.combinations(dataFrame.columns, nstocks)
    res = pd.DataFrame()
    sec = pd.DataFrame()
    for pair in tcomb:
        xName, yName = list(pair[:int(nstocks/2)]), list(pair[int(nstocks/2):])
        xind, yind = tickers.searchsorted(xName), tickers.searchsorted(yName)
        xSector = list(SNP.ix[xind]["Sector"])
        ySector = list(SNP.ix[yind]["Sector"])
        if set(xSector) == set(ySector):
            sector = [[(xSector, ySector)]]
            x, y = dataFrame[list(xName)].sum(axis=1), dataFrame[list(yName)].sum(axis=1)
            res1 = adf(x,y,xName,yName)
            if res1 is None:
                continue
            elif res.size==0:
                res=res1
                sec = pd.DataFrame(sector, index = res.index, columns = ["sector"])
                print("added : ", pair)
            else:
                res=res.append(res1)
                sec = sec.append(pd.DataFrame(sector, index = [res.index[-1]], columns = ["sector"]))
                print("added : ", pair)
    res = pd.concat([res,sec],axis=1)
    res=res.sort_values(by=["pvalue"],ascending=True)
    b=time.time()
    print("time taken : ", b-a, "sec")
    return res
当nstocks=2时,这大约需要263秒,但随着nstocks的增加,循环需要的时间比一天多

我使用pandas_datareader.data从雅虎财经收集了“Adj Close”数据 索引是时间,列是不同的标记


如果您有任何建议或帮助,我们将不胜感激。

我不知道您有哪台计算机,但我建议您使用某种多处理循环。我并没有认真研究过您的代码,但据我所知,res和sec可以移动到共享内存对象中,并且单个循环与多处理并行


如果你有一个像样的CPU,它可以提高性能4-6倍。如果你有机会使用某种HPC,它可以创造奇迹

我不知道你有什么电脑,但我建议你对循环使用某种多重处理。我并没有认真研究过您的代码,但据我所知,res和sec可以移动到共享内存对象中,并且单个循环与多处理并行


如果你有一个像样的CPU,它可以提高性能4-6倍。如果你有机会使用某种HPC,它可以创造奇迹

我建议使用探查器来缩小最耗时的调用范围,循环的数量是否达到预期的通过次数?。Python 3在标准库中有一个探查器:

您可以在代码中调用它:

import cProfile
cProfile.run('your_function(inputs)')
或者如果脚本是一个更容易的入口点:

python -m cProfile [-o output_file] [-s sort_order] your-script.py

我建议使用探查器来缩小最耗时的调用范围,循环的数量是否达到预期的通过次数?。Python 3在标准库中有一个探查器:

您可以在代码中调用它:

import cProfile
cProfile.run('your_function(inputs)')
或者如果脚本是一个更容易的入口点:

python -m cProfile [-o output_file] [-s sort_order] your-script.py