Pandas Groupby 几何平均数?

Pandas Groupby Geometric Average?

我正在尝试为我的投资组合计算股票 returns,这需要按年对百分比进行“几何平均”。

为简单起见,我有一个如下所示的数据框:

日期Returns

2013-06-01 1%
2013-07-01 5%
2013-08-01 -4%
2014-01-01 12%
2014-02-01 -9%

我希望输出显示:

日期地理位置 Return 2013 1.8% 2015 年 1.9%

推导出:(1+.01)(1+.05)(1+-.04) = 1.8%

我可以按年使用 groupby 函数,但它只对我求和,我无法使用几何平均值。有人可以帮忙吗?

谢谢!

请注意,您要求的是累积乘积,这与几何平均值的通常定义不同。

df["returns"] = 1 + .01*df.Returns.str.split("%").str[0].astype(int)
df["geom_ave"] = df.groupby(df.Date.dt.year).returns.transform("prod")

输出:

        Date Returns  returns  geom_ave
0 2013-06-01      1%     1.01   1.01808
1 2013-07-01      5%     1.05   1.01808
2 2013-08-01     -4%     0.96   1.01808
3 2014-01-01     12%     1.12   1.01920
4 2014-02-01     -9%     0.91   1.01920

如果你想要几何平均数,你可以试试:

from scipy import stats
series = df.groupby(df.Date.dt.year).returns.apply(stats.gmean)