gpt4 book ai didi

python - PANDAS 中的滚动产品超过 30 天的时间窗口

转载 作者:行者123 更新时间:2023-11-30 23:04:54 27 4
gpt4 key购买 nike

我正在尝试为金融事件分析准备数据,并希望计算买入并持有异常返回 (BHAR)。对于测试数据集,我有三个事件(由 event_id 表示),对于每个事件,我有 272 行,从 t-252 天到 t+20 天(由变量 表示)时间)。对于每一天,我还有股票的返回数据 (ret) 以及预期返回 (Exp_Ret),这是使用市场模型计算得出的。以下是数据示例:

index   event_id    time    ret       vwretd    Exp_Ret
0 0 -252 0.02905 0.02498 nan
1 0 -251 0.01146 -0.00191 nan
2 0 -250 0.01553 0.00562 nan
...
250 0 -2 -0.00378 0.00028 -0.00027
251 0 -1 0.01329 0.00426 0.00479
252 0 0 -0.01723 -0.00875 -0.01173
271 0 19 0.01335 0.01150 0.01398
272 0 20 0.00722 -0.00579 -0.00797
273 1 -252 0.01687 0.00928 nan
274 1 -251 -0.00615 -0.01103 nan

这就是问题所在。我想计算每天的以下BHAR公式:

enter image description here

所以,以上面的公式为例,如果我要计算10天买入并持有的异常 yield ,我就需要计算(1+ret_t=0)x(1+ret_t=1 )...x(1+ret_t=10),然后对预期返回进行同样的操作,(1+Exp_Ret_t=0)x(1+Exp_Ret_t=1)...x(1+Exp_Ret_t=10),然后从前者中减去后者。

我使用 rolling_apply 取得了一些进展,但它并没有解决我的所有问题:

df['part1'] = pd.rolling_apply(df['ret'], 10, lambda x : (1+x).prod())

这似乎正确地实现了 BHAR 方程的左侧,因为它将添加正确的乘积——尽管它将输入向下两行的值(可以通过移位来解决)。但一个问题是,数据框中存在三个不同的“组”(3 个事件),如果窗口向前推进超过 30 天,它可能会开始使用下一个事件的产品。我尝试使用 rolling_apply 实现 groupby 但不断收到错误:TypeError: 'Series' 对象是可变的,因此无法对它们进行哈希处理

df.groupby('event_id').apply(pd.rolling_apply(df['ret'], 10, lambda x : (1+x).prod()))

我确信我在这里缺少一些基本的东西,所以任何帮助将不胜感激。我可能只需要从不同的角度来看待它。这里有一个想法:最后,我最感兴趣的是获得从 time=0 开始的 30 天和 60 天买入并持有的异常 yield 。那么,也许更容易选择 time=0 时的每个事件,然后计算 future 30 天的乘积?我不确定如何才能最好地解决这个问题。

预先感谢您提供任何见解。

最佳答案

# Create sample data.
np.random.seed(0)
VOL = .3
df = pd.DataFrame({'event_id': [0] * 273 + [1] * 273 + [2] * 273,
'time': range(-252, 21) * 3,
'ret': np.random.randn(273 * 3) * VOL / 252 ** .5,
'Exp_Ret': np.random.randn(273 * 3) * VOL / 252 ** .5})

# Pivot on time and event_id.
df = df.set_index(['time', 'event_id']).unstack('event_id')

# Calculated return difference from t=0.
df_diff = df.ix[df.index >= 0, 'ret'] - df.loc[df.index >= 0, 'Exp_Ret']

# Calculate cumulative abnormal returns.
cum_returns = (1 + df_diff).cumprod() - 1

# Get 10 day abnormal returns.
>>> cum_returns.loc[10]
event_id
0 -0.014167
1 -0.172599
2 -0.032647
Name: 10, dtype: float64

关于python - PANDAS 中的滚动产品超过 30 天的时间窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33455163/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com