Python pandas dataframe groupby ticker中的对数返回
我喜欢根据股票价格(adjclose)计算一个包含多个股票和价格的数据框架中每个股票的日志回报 此类数据帧的示例:Python pandas dataframe groupby ticker中的对数返回,python,pandas,Python,Pandas,我喜欢根据股票价格(adjclose)计算一个包含多个股票和价格的数据框架中每个股票的日志回报 此类数据帧的示例: import pandas as pd import numpy as np f = {'date': ['2020-11-25', '2020-11-24', '2020-11-23', '2020-11-25', '2020-11-24', '2020-11-23'], 'ticker': ['AAPL', 'AAPL', 'AAPL', 'AIR', 'AI
import pandas as pd
import numpy as np
f = {'date': ['2020-11-25', '2020-11-24', '2020-11-23', '2020-11-25', '2020-11-24', '2020-11-23'],
'ticker': ['AAPL', 'AAPL', 'AAPL', 'AIR', 'AIR', 'AIR'],
'adjclose': [116.029999, 115.169998, 113.849998, 29.510000, 29.540000, 27.890000]
}
df = pd.DataFrame(f)
df.set_index('date', inplace=True)
数据帧df:
ticker adjclose
date
2020-11-25 AAPL 116.029999
2020-11-24 AAPL 115.169998
2020-11-23 AAPL 113.849998
2020-11-25 AIR 29.510000
2020-11-24 AIR 29.540000
2020-11-23 AIR 27.890000
按照这里提出的想法
df.sort_值(按=['ticker','date'],升序=True,原地=True)
df
df['return']=df.groupby(['ticker'])['adjclose'].pct\u change()
np.log(df['adjclose']/df['adjclose'].shift(1))
`df['log_return'] = np.log(df.groupby(['ticker'])['adjclose'] / df.groupby(['ticker'])['adjclose'].shift(1))`
我得到一个错误:
ValueError:操作数无法与形状(3,2)(6,2)一起广播。
你能在这个话题上帮我吗?
非常感谢您可以这样做,我们将日志返回计算应用到每个
d
,这是groupby中的组:
df.groupby('ticker').apply(lambda d: d.assign(log_return = np.log(d['adjclose'] / d['adjclose'].shift(1)) ))
输出
date ticker adjclose log_return
ticker
AAPL 2 2020-11-23 AAPL 113.849998 NaN
1 2020-11-24 AAPL 115.169998 0.011528
0 2020-11-25 AAPL 116.029999 0.007439
AIR 5 2020-11-23 AIR 27.890000 NaN
4 2020-11-24 AIR 29.540000 0.057477
3 2020-11-25 AIR 29.510000 -0.001016
而不是按股票价格分组考虑设置日期和股票行情的多指标。我认为这将解决您的问题,并可能执行得更快。
`df['log_return'] = np.log(df.groupby(['ticker'])['adjclose'] / df.groupby(['ticker'])['adjclose'].shift(1))`
df.groupby('ticker').apply(lambda d: d.assign(log_return = np.log(d['adjclose'] / d['adjclose'].shift(1)) ))
date ticker adjclose log_return
ticker
AAPL 2 2020-11-23 AAPL 113.849998 NaN
1 2020-11-24 AAPL 115.169998 0.011528
0 2020-11-25 AAPL 116.029999 0.007439
AIR 5 2020-11-23 AIR 27.890000 NaN
4 2020-11-24 AIR 29.540000 0.057477
3 2020-11-25 AIR 29.510000 -0.001016