我构建了一个函数,将 5 个投资组合的收益附加到一个数据帧中,我想将其返回到一个变量。当我在函数中逐行运行命令(一种调试)时,我最终得到的变量“folioReturn”(这是我希望脚本返回的变量)具有正确数量的值(例如 5)。但是如果我调用该函数,则仅返回数据帧的第一个值。有谁知道我如何获得整个数据框?
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)
您基本上太早退出了该功能。
这里有两个示例,可以让您更容易理解:
def test():
lst = []
for num in range(10):
lst = num
return lst
def test2():
lst = []
for num in range(10):
lst.append(num)
return lst
print(test()) # Output: 0
print(test2()) # Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In test
我们创建一个名为的列表变量lst
,然后在 for 循环内,我们覆盖lst
与当前变量num
然后立即发出return
语句,仅返回0
因为它是 for 循环中的第一个条目。
In test2
然而,我们在循环开始时做同样的事情,而不是覆盖lst
我们改为使用该方法list.append()
这增加了num
到已经创建的列表。
完成整个 for 循环后,我们使用return
返回变量的语句lst
现在包含来自的所有值0
to 9
.
编辑:看来我没能解决这个问题actual你的代码有问题。有两个主要错误:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)