且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python函数仅返回第一个值,而不返回数据框

更新时间:2023-02-19 11:12:49

return语句必须在for循环之后,如果您希望在第一个循环中使用整个列表,则只返回该值.只需删除for循环的返回值即可.

return statement must be after the for loop if you want whole list in your case during the first loop only the value is returned. just remove the return from for loop it will work fine.

def portfolioReturns (securities, quintilesNo, perReturns):
    '''
    this function receives 
    1)securities: array with the security names and values ** for the purpose of our work the names
    should already be sorted
    2)quintilesNo: the number of portfolios we want to create 
    3)perReturns: an array with the returns that will be used for performance measuremnt

    It returns an array with the returns for each portfolio

    '''

    # we calculate the number of securities per portfolio 
    stdFolioSize = np.divmod(securities.size, quintilesNo)[0] # we take the floor division
    folioReturn = [] # pd.DataFrame()
    # we create portfolios with equal number of securities except of the last one where we use all the remaining securities
    for k in range(0, quintilesNo, 1): # in folio list we store the name of the securities we must include in each portfolio
        if k < (quintilesNo - 1):           
            folioList = securities.index.get_level_values(1)[k * stdFolioSize : (k + 1) * stdFolioSize]

        else: # the last portfolio will also include the remainder securities 
            folioList = securities.index.get_level_values(1)[k * stdFolioSize : securities.size]

        # now that we have the list of the securities to be included in the folio, we use the table
        # with the periodical returns to check the performance. The portfolio we construct is equally weighted

        # first we drop one index(the first index of the country) and then we store all the periodical returns in one-array 
        perRetFinalTable = pd.DataFrame(perReturns.reset_index(level = 0, drop = True)).T  

        # using the list of the bonds we want to include in our portfolio we pick the bond returns and
        # we store them in one array. Then we calculate the folio return
        folio = perRetFinalTable[folioList]
        folioReturn = np.append(folioReturn, folio.sum(axis = 1) * (1 / folio.size))
        folioReturn = pd.DataFrame(folioReturn).T
        # folioReturn = pd.Series(folioReturn).T

    return (folioReturn)