R语言to.period函数indexAt=firstof按小时周期失效问题
xts包to.period()函数indexAt="firstof"参数在小时周期下失效的问题
问题详情
- 使用
to.period()处理单变量xts对象,指定周期为"hours"且indexAt="firstof"时,返回结果的索引为每小时的最后时刻(与indexAt="lastof"效果一致),而非预期的每小时起始时刻。 - 尝试使用
indexAt="startof"时,虽能得到接近预期的结果,但由于周日交易起始时间晚1分钟,会导致索引不一致,无法作为替代方案。 - 有非官方说法称
indexAt参数仅支持月度和季度周期,但无官方文档明确说明,且startof参数在小时周期下可正常工作,因此疑问firstof参数失效的原因。
代码示例
原数据(USOil)
head(USOil) [,1] 2022-01-02 23:01:00 75.740 2022-01-02 23:01:00 75.740 2022-01-02 23:02:00 75.807 2022-01-02 23:03:00 75.688 2022-01-02 23:04:00 75.659 2022-01-02 23:05:00 75.661
使用indexAt="firstof"的结果
head(to.period(USOil, "hours", indexAt = "firstof")) USOil.Open USOil.High USOil.Low USOil.Close 2022-01-02 23:59:00 75.740 75.900 75.646 75.828 2022-01-03 00:59:00 75.827 76.069 75.805 75.946 2022-01-03 01:59:00 75.926 75.981 75.586 75.638 2022-01-03 02:59:00 75.658 75.658 75.476 75.498 2022-01-03 03:59:00 75.498 75.886 75.498 75.859 2022-01-03 04:59:00 75.818 75.854 75.756 75.764
预期结果
USOil.Open USOil.High USOil.Low USOil.Close 2022-01-02 23:00:00 75.740 75.900 75.646 75.828 2022-01-03 00:00:00 75.827 76.069 75.805 75.946 2022-01-03 01:00:00 75.926 75.981 75.586 75.638 2022-01-03 02:00:00 75.658 75.658 75.476 75.498 2022-01-03 03:00:00 75.498 75.886 75.498 75.859 2022-01-03 04:00:00 75.818 75.854 75.756 75.764
使用indexAt="startof"的结果
head(to.period(USOil, "hours", indexAt = "startof")) USOil.Open USOil.High USOil.Low USOil.Close 2022-01-02 23:01:00 75.740 75.900 75.646 75.828 2022-01-03 00:00:00 75.827 76.069 75.805 75.946 2022-01-03 01:00:00 75.926 75.981 75.586 75.638 2022-01-03 02:00:00 75.658 75.658 75.476 75.498 2022-01-03 03:00:00 75.498 75.886 75.498 75.859 2022-01-03 04:00:00 75.818 75.854 75.756 75.764
内容的提问来源于stack exchange,提问作者Sphin
相关产品推荐
相关产品推荐

