计算熊猫的累计复合收益

Win*_*981 5 python dataframe pandas

我有一系列的每日百分比回报率returns

                   Returns
Date
2003-03-03         0.0332
2003-03-04         0.0216
2003-03-05         0.0134
...
2010-12-29         0.0134
2010-12-30         0.0133
2010-12-31        -0.0297
Run Code Online (Sandbox Code Playgroud)

我可以由初始值的值设置为1,并使用计算的返回索引 cumprod()

ret_index = (1 + returns).cumprod()

ret_index[0] = 1
Run Code Online (Sandbox Code Playgroud)

这给了我这样的东西:

Date
2003-03-03         1.0000
2003-03-04         1.0123
2003-03-05         1.1334
...
2010-12-29         2.3344
2010-12-30         2.3544
2010-12-31         2.3643
Run Code Online (Sandbox Code Playgroud)

所以,我的累计复配比例的回报为全系列约236%。

我的问题:我想计算系列(2003、2004 ... 2010)中每年的累计复合百分比回报。

我能想到的唯一方法是遍历我的初始系列,按年分割,将第一个元素设置为1,然后计算每年的回报。我认为使用datetime(索引是Datetimeindex)和重采样有任何更简单的方法。

有人可以帮忙吗?

jez*_*ael 5

对我来说,它返回的结果有些不同,但是我认为您需要groupby

a = df.add(1).cumprod()
a.Returns.iat[0] = 1
print (a)
             Returns
Date                
2003-03-03  1.000000
2003-03-04  1.055517
2003-03-05  1.069661
2010-12-29  1.083995
2010-12-30  1.098412
2010-12-31  1.065789

def f(x):
    #print (x)
    a = x.add(1).cumprod()
    a.Returns.iat[0] = 1
    return a

print (df.groupby(df.index.year).apply(f))

             Returns
Date                
2003-03-03  1.000000
2003-03-04  1.055517
2003-03-05  1.069661
2010-12-29  1.000000
2010-12-30  1.026878
2010-12-31  0.996380
Run Code Online (Sandbox Code Playgroud)