gpt4 book ai didi

python - 检查 Pandas 中是否存在所有 12 个月后,如何将月返回转换为年返回?

转载 作者:太空宇宙 更新时间:2023-11-03 17:32:23 24 4
gpt4 key购买 nike

我有月度返回,我想将它们转换为每家公司的年度返回(使用 cusip6,我正在使用 CRSP 数据)。我也想只保留那些有 12 个月的年份。我目前正在使用以下代码,但我想知道 pandas 中是否有内置函数可以做到这一点?`

def monthly_to_ann_ret(data):
""" funtion to check if all 12 months are present and
calculate yearly returns from monthly returns
"""
data['year'] = data['date'].dt.year
data.sort(['cusip6','year'],inplace = True)
data_grouped = data.groupby(['cusip6','year'])
annual_df = pd.DataFrame()
for name,group in data_grouped:
if group.shape[0] == 12:
group.loc['RET'] = 1 + group['RET']
group['yearly_RET'] = group['RET'].cumprod() - 1
annual_df = annual_df.append(group.iloc[-1])
else:
continue
return annual_df`

最佳答案

我觉得你的方法很不错。这是另一种方法 FWIW,它更简洁一些,并使用 nth 作为捷径。

以下是 2 家公司 46 个月的一些样本数据(只是缺少第一个月和最后一个月)。

stocks = pd.DataFrame({ 
'cusip6':np.repeat( [1234,5678], 24 ),
'date':np.tile( pd.date_range('1/1/2011', periods=24, freq='M'), 2 ),
'return':(np.random.choice([1.005,1.010,1.015],48)) })
stocks = stocks.iloc[1:-1]

然后使用一些 groupby 内容(包括 nth),您可以相当紧凑地完成此操作。

stocks['year']=stocks.date.dt.year
stocks['cum_return'] = stocks.groupby(['cusip6','year']).cumprod()
stocks.groupby(['cusip6','year']).nth(11)

cum_return date return
cusip6 year
1234 2012 1.115614 2012-12-31 1.010
5678 2011 1.149248 2011-12-31 1.015

为了进行比较,如果我们使用 tail(1) 而不是 nth(11),我们只会获得上个月的数据,无论是 11 号还是 12 号月。

stocks.groupby(['cusip6','year']).tail(1)

cusip6 date return year cum_return
11 1234 2011-12-31 1.010 2011 1.110064
23 1234 2012-12-31 1.010 2012 1.115614
35 5678 2011-12-31 1.015 2011 1.149248
46 5678 2012-11-30 1.015 2012 1.126687

关于python - 检查 Pandas 中是否存在所有 12 个月后,如何将月返回转换为年返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31711059/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com