python - 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) 来填充输出。
解决方案
其他方式:
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
推荐阅读
- xml - 如何在不重写整个查询的情况下重写此 xquery 以删除子节点?
- r - 变异列并修改小标题中的列名
- r - R Markdown - 如何导出为 PDF 文件?
- python - Python中的Excel复制粘贴方式
- apache-kafka - KIP-500:用自我管理的元数据仲裁替换 ZooKeeper
- php - 使用 php 检查 ip 是否与 ip 列表中包含的任何 ip 匹配
- java - 如何使用 dagger 限定符注解来提供不同的 OkHttpClient 构建器?
- ios - 在 WKWebview 中突出显示文本
- reactjs - 多选不起作用,只给出最后点击的值
- javascript - 使用 Jackson ObjectMapper 将 Java HashMap 序列化为 JSON