固定时间窗(而不是固定nb)大Pandas的滚动平均值。观察结果)

2024-04-29 13:46:05 发布

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

我有一个有两列的数据帧和一个3级索引结构。列是价格和成交量,指数是交易者股票交易日。在

我想在我的数据中计算每个交易者股票组合过去50天的价格和成交量的滚动平均值。在

这就是我目前所想到的。在

test=test.set_index(['date','trader', 'stock'])

test=test.unstack().unstack()

test=test.resample("1D")

test=test.fillna(0)

test[[col+'_norm' for col in test.columns]]=test.apply(lambda x: pd.rolling_mean(x,50,50))

test.stack().stack().reset_index().set_index(['trader', 'stock','date']).sort_index().head()

也就是说,我将数据集拆开两次,这样我就只剩下时间轴了,我可以计算出我的变量的50天滚动平均值,因为50个观测值对应于50天(在对数据重新取样之后)。在

问题是我不知道如何为滚动平均变量创建正确的名称

test[[col+'_norm' for col in test.columns]]

TypeError:只能将元组(而不是“str”)连接到元组

有什么问题吗?我的算法真的正确吗? 非常感谢!在


Tags: 数据testnormdateindex交易者stock价格
1条回答
网友
1楼 · 发布于 2024-04-29 13:46:05

{cd1>的原始列名称可以与的结果连在一起:

means = pd.rolling_mean(test, 50, 50)
means.columns = [('{}_norm'.format(col[0]),)+col[1:] for col in means.columns]
test = pd.concat([test, means], axis=1)

^{pr2}$

收益率

                         foo  foo_norm
trader stock date                     
0      0     2000-01-01    0       NaN
             2000-01-02    0       NaN
             2000-01-03    0       NaN
             2000-01-04    0       NaN
             2000-01-05    0       NaN
...

相关问题 更多 >