首页 > 解决方案 > python - 我如何在熊猫时间序列上执行以下任务

问题描述

这是我的假设股票(随机创建)和相应回报的时间序列的 df

np.random.seed(1)
df = pd.DataFrame(np.random.randint(200,800,100),index=pd.date_range('2015-01-01',periods=100,freq='D'),columns=['stock'])
df['rtns'] = df.stock.pct_change()
df.dropna(inplace=True)

我需要的是,对于给定的日期,如果我们期待 22 天(2015 年 3 月 1 日:2015 年 3 月 1 日:2015 年 1 月 24 日)的给定日期,那么我需要百分位数(第 5、10、25 日...... . 如下图所示)。只是为了澄清要根据回报(而不是股票价格)计算的百分位数。同样明智的是,我希望所有日期都相同。我们如何做到这一点?

已编辑 -

我已经附加了几天的输出。我不确定 np.percentile([array],0.05) 即第 5 个百分位数的 python 等效项是什么。我使用了 excel 函数 percentile([array],0.05) 来填充输出。

在此处输入图像描述

标签: pythonpandas

解决方案


其他方式:

for pct in [0.05, 0.1, 0.25, 0.5, 0.75, 0.95]:
    df[f"{int(pct*100)}th percentile"] = df['rtns'].rolling(22).quantile(pct).shift(-22)

>>> df.head()
            stock      rtns  ...  75th percentile  95th percentile
2015-01-02    435  0.835443  ...         0.251163         0.685605
2015-01-03    272 -0.374713  ...         0.263344         0.736752
2015-01-04    344  0.264706  ...         0.251163         0.736752
2015-01-05    329 -0.043605  ...         0.270500         1.347892
2015-01-06    783  1.379939  ...         0.270500         0.736752

推荐阅读