Pandas 中的自定义时间序列重采样 [英] Custom time series resampling in Pandas
本文介绍了Pandas 中的自定义时间序列重采样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 1m 频率的带有 OHLC 数据的 df:
I have a df with OHLC data in a 1m frequency:
Open High Low Close
DateTime
2005-09-06 18:00:00 1230.25 1231.50 1230.25 1230.25
2005-09-06 18:01:00 1230.50 1231.75 1229.25 1230.50
.
.
2005-09-07 15:59:00 1234.50 1235.50 1234.25 1234.50
2005-09-07 16:00:00 1234.25 1234.50 1234.25 1234.25
我需要做一个适合期货交易时间数据的自定义"重采样,其中:
I need to do a "custom" resample that fits futures hours data where:
- 每天从前一天的 18:00:00 开始(周一从周日 18:00:00 开始)
- 每天在当天的 16:00:00 结束
- 时间戳应为收盘时间,而非开盘时间.
重新采样后,输出应该是:
After doing the resample, the output should be:
Open High Low Close
DateTime
2005-09-07 16:00:00 1230.25 1235.50 1229.25 1234.25
地点:
- 打开 = 2005-09-06 18:00:00 的第一个(打开列)
- 高 = 从 2005-09-06 18:00:00 到 2005-09-07 16:00:00 的最大值(高列)
- 低 = 从 2005-09-06 18:00:00 到 2005-09-07 16:00:00 的分钟(低列)
- 关闭 = 最后一次(关闭列)在 2005-09-07 16:00:00
我试过了:
- 更改参数规则和基数,但没有用.
- 尝试重新索引但没有成功.
我使用了以下方法":
conversion = {'Open': 'first', 'High': 'max', 'Low': 'min', 'Close': 'last'}
推荐答案
import pandas as pd
df = pd.read_table('data', sep='\s{2,}')
# Make sure the index is a DatetimeIndex
df.index = pd.DatetimeIndex(df.index)
# discard rows whose time falls between 16:00 and 18:00
df = df.between_time('18:00', '16:00', include_start=True, include_end=True)
proxy = df.index + pd.DateOffset(hours=6)
result = df.groupby(proxy.date).agg(
{'Open': 'first', 'High': 'max', 'Low': 'min', 'Close': 'last'})
result = result.reindex(columns=['Open','High','Low','Close'])
print(result)
收益
Open High Low Close
2005-09-07 1230.25 1235.5 1229.25 1234.25
<小时>
上面的代码创建了一个代理日期,该日期是通过向索引中的每个日期时间添加 6 小时来计算的.然后将此代理日期用作 groupby
值.
In [112]: proxy = pd.DatetimeIndex(df.index) + pd.DateOffset(hours=6)
要查看代理值如何与索引对应:
To see how the proxy values correspond to the index:
In [116]: pd.Series(proxy.date, index=df.index)
Out[116]:
DateTime
2005-09-06 18:00:00 2005-09-07
2005-09-06 18:01:00 2005-09-07
2005-09-07 15:59:00 2005-09-07
2005-09-07 16:00:00 2005-09-07
dtype: object
这篇关于Pandas 中的自定义时间序列重采样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文