计算按股息调整的Pct变化

2024-10-03 13:24:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据:

https://docs.google.com/spreadsheets/d/15Dg0JYXoQyqIVokrVoSJOBogJw_bDCY-IoBGtleOlm8/edit?usp=sharing

我需要计算Pct\U Change\U ADJUSED列:

Pct变化调整=((值[1]+股息[1])/值[0]-1)

例如,对于第3行、第4行和第5行(Googlesheet),数据是:

2019-01-02 9072 A 1020.0000 0.0000 0.0200 0.0200 9072A

2019-01-03 9072 A 1040.4000 0.0000 0.0200 0.0200 9072A

2019-01-04 9072 A 1009.1880 52.0200 -0.0300 0.0200 9072A

Pct变化调整(第4行)=((1.040.4000+0.0000)/(1020.0000)-1)=0.0200

Pct变化调整(第5行)=((1.009.1880+52.02000)/(1040.4000)-1)=0.0200

有没有一种方法可以快速完成pct\U的更换?(而不是在数据中使用条件进行迭代)

到目前为止,我的Pct\ U变更代码是:

你知道吗数据框groupby(df[6])[3].pct\u变化(1)

谢谢你!你知道吗


Tags: 数据httpscomdocsgooglechangeeditsharing
2条回答

IIUC,最有可能的情况是,您可以执行以下操作:

df['Pct_Change_Adjusted'] = df.groupby(['Fund_ID', 'Fund_Series'], as_index=False) \
                              .apply(lambda x: (x.Value + x.Dividend)/x.Value.shift()-1) \
                              .reset_index(level=0, drop=True)

同样的事情,但更详细:

import numpy as np
import pandas as pd
import io

s = '''
Date    Fund_ID Fund_Series Value   Dividend
2019-01-02 9072 A 1020.0000 0.0000
2019-01-03 9072 A 1040.4000 0.0000
2019-01-04 9072 A 1009.1880 52.0200 
''';

df = pd.read_csv(io.StringIO(s),sep='\s')
print(df)

         Date  Fund_ID Fund_Series     Value  Dividend
0  2019-01-02     9072           A  1020.000      0.00
1  2019-01-03     9072           A  1040.400      0.00
2  2019-01-04     9072           A  1009.188     52.02

df['Pct_Change_Adjusted'] = df.groupby(['Fund_ID', 'Fund_Series'], as_index=False) \
                              .apply(lambda x: (x.Value + x.Dividend)/x.Value.shift()-1) \
                              .reset_index(drop=True).values[0]

print(df)

         Date  Fund_ID Fund_Series     Value  Dividend  Pct_Change_Adjusted
0  2019-01-02     9072           A  1020.000      0.00                  NaN
1  2019-01-03     9072           A  1040.400      0.00                 0.02
2  2019-01-04     9072           A  1009.188     52.02                 0.02

相关问题 更多 >