python - 从 pandas(cumpound) 的日返回率计算月返回率

标签 python pandas

我试图计算特定股票的月返回率,但我想不出一个不使用大量 for 循环的好方法。 df 具有以下形式

           MSFT-US  AAPL-US    GE    RF
 20150501    1.01   -0.33   -0.60   0.000
 20150504    0.32    0.06    0.16   0.000
 20150505   -1.19   -0.10    0.34   0.000
 20150506   -0.31    0.62   -0.20   0.000
 20150507    0.39    0.03   -0.43   0.000
 20150508    1.21   -0.54   -0.21   0.000
 20150511   -0.39    0.67   -0.11   0.000
 20150512   -0.27    0.00    0.11   0.000
 20150513    0.01    0.02   -0.06   0.000
 20150514    1.01   -0.10   -0.36   0.000
 20150515    0.05   -0.26   -0.01   0.000
 20150518    0.44    0.72   -0.09   0.000
 20150519   -0.09   -0.08    0.03   0.000
 20150520   -0.05    0.21   -0.09   0.000
 20150521    0.23   -0.31    0.09   0.000
 20150522   -0.22   -0.11   -0.14   0.000
 20150526   -1.01   -0.04   -0.02   0.000
 20150527    0.93    0.33   -0.39   0.000
 20150528   -0.11    0.11    0.07   0.000
 20150529   -0.58    0.02    0.05   0.000

所以我想要这样的东西(但复合不是总和):

         MSFT-US   AAPL-US     GE      RF
 201505    1.36     0.92     -1.89    0.00

最佳答案

假设您的日期列名为 'date':

df['month'] = df['date'].astype(str).str[:6]

monthly_total = df.groupby('month').sum().drop('date', axis='columns')

给你

        MSFT-US  AAPL-US    GE   RF
month                              
201505     1.38     0.92 -1.86  0.0

要获得复合 yield ,我们需要将每个值加 1,然后使用 .prod():

df[['MSFT-US', 'AAPL-US', 'GE', 'RF']] += 1
monthly_total = df.groupby('month').prod().drop('date', axis='columns')

给我们:

         MSFT-US   AAPL-US        GE   RF
month                                    
201505  0.008739  0.946043  0.070769  1.0

关于python - 从 pandas(cumpound) 的日返回率计算月返回率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52217911/

相关文章:

python - 强制 numpy 创建对象数组

python - 在Python中,如何识别和替换每个句子开头的数值?

java - 从 Excel 电子表格中读取手动插入的文本

合并数据帧时 Pandas 'multi-index' 问题

python - Pandas - 计算字符字段中逗号的数量

python - 将生成的 PIL 图像保存到 django 中的 ImageField 中

python - 如何每隔 x 小时在 bash 脚本中重新启动 python 脚本?

python - Replace() 没有找到日期,也没有转换为另一个字符串

python - 从数据框中删除具有特定值的连续重复项

python - Pandas dataframe 到以 ID 作为键的字典