我有一系列每日百分比回报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
我可以通过将初始值的值设置为1并使用cumprod()
ret_index = (1 + returns).cumprod()
ret_index[0] = 1
给我这样的东西:
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
所以我整个系列的累积复合百分比回报率约为236%。
我的问题:我想计算系列中每年的累积复合百分比回报率(2003年,2004年...... 2010年)。
我能想到的唯一方法是迭代我的初始系列,按年切片,将第一个元素设置为1,并计算每年的回报。我认为有更简单的方法使用datetime(索引是Datetimeindex)和重新采样。
有人可以帮忙吗?
答案 0 :(得分:3)
对我而言,它会返回一些不同的结果,但我认为您需要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
答案 1 :(得分:2)
我明白了:
returns_y = ret_index.resample('A-DEC', how='last').pct_change()
得到:
Out[206]:
return
date
2003-12-31 NaN
2004-12-31 0.108821
2005-12-31 0.049118
2006-12-31 0.157945
2007-12-31 0.054937
2008-12-31 -0.369976
2009-12-31 0.264642
2010-12-31 0.150634
如果我将每日系列值更改为从2002-12-30开始(我得到的值的最后一个日期:
Out[206]:
return
date
2003-12-31 0.057843
2004-12-31 0.108821
2005-12-31 0.049118
2006-12-31 0.157945
2007-12-31 0.054937
2008-12-31 -0.369976
2009-12-31 0.264642
2010-12-31 0.150634
答案 2 :(得分:1)
我无法得到这个答案returns_y = ret_index.resample('A-DEC', how='last').pct_change()
我认为 how='last' 已被弃用?
这是我的解决方案,从 S&P500 每日回报的数据框开始:
print(daily_df)
daily_df['Return'] = (1 + daily_df).cumprod()
annual_df = pd.DataFrame(daily_df['Return'].resample('A').last().pct_change())
print(daily_df)
print(annual_df)
输出:
Daily Return
Date
2002-12-31 0.000489
2003-01-02 0.033200
2003-01-03 -0.000484
2003-01-06 0.022474
2003-01-07 -0.006545
...
2010-12-27 0.000613
2010-12-28 0.000771
2010-12-29 0.001009
2010-12-30 -0.001508
2010-12-31 -0.000191
[2016 rows x 1 columns]
Daily Return Return
Date
2002-12-31 0.000489 1.000489
2003-01-02 0.033200 1.033705
2003-01-03 -0.000484 1.033205
2003-01-06 0.022474 1.056425
2003-01-07 -0.006545 1.049512
... ...
2010-12-27 0.000613 1.430014
2010-12-28 0.000771 1.431117
2010-12-29 0.001009 1.432561
2010-12-30 -0.001508 1.430401
2010-12-31 -0.000191 1.430128
[2016 rows x 2 columns]
Return
Date
2002-12-31 NaN
2003-12-31 0.263804
2004-12-31 0.089935
2005-12-31 0.030010
2006-12-31 0.136194
2007-12-31 0.035296
2008-12-31 -0.384858
2009-12-31 0.234542
2010-12-31 0.127827