python - 熊猫仅在数据框中的特定时间之间合并股票数据
问题描述
我有 2017 年到 2019 年的每分钟股票数据。我只想保留每天 9:16 之后的数据,因此我想将 9:00 到 9:16 之间的任何数据转换为 9:16 的值,即:
09:16 的值应该是
open
: 9:00 - 9:16 的第一个数据的值,这里是 116.00high
: 9:00 - 9:16 的最高值,此处为 117.00low
:从 9:00 到 9:16 的最低值,这里是 116.00close
:这将是 9:16 的值,这里是 113.00
open high low close
date
2017-01-02 09:08:00 116.00 116.00 116.00 116.00
2017-01-02 09:16:00 116.10 117.80 117.00 113.00
2017-01-02 09:17:00 115.50 116.20 115.50 116.20
2017-01-02 09:18:00 116.05 116.35 116.00 116.00
2017-01-02 09:19:00 116.00 116.00 115.60 115.75
... ... ... ... ...
2029-12-29 15:56:00 259.35 259.35 259.35 259.35
2019-12-29 15:57:00 260.00 260.00 260.00 260.00
2019-12-29 15:58:00 260.00 260.00 259.35 259.35
2019-12-29 15:59:00 260.00 260.00 260.00 260.00
2019-12-29 16:36:00 259.35 259.35 259.35 259.35
这是我尝试过的:
#Get data from/to 9:00 - 9:16 and create only one data item
convertPreTrade = df.between_time("09:00", "09:16") #09:00 - 09:16
#combine modified value to original data
df.loc[df.index.strftime("%H:%M") == "09:16" ,
["open","high","low","close"] ] = [convertPreTrade["open"][0],
convertPreTrade["high"].max(),
convertPreTrade["low"].min(),
convertPreTrade['close'][-1] ]
但这不会给我准确的数据
解决方案
d = {'date': 'last', 'open': 'last',
'high': 'max', 'low': 'min', 'close': 'last'}
# df.index = pd.to_datetime(df.index)
s1 = df.between_time('09:00:00', '09:16:00')
s2 = s1.reset_index().groupby(s1.index.date).agg(d).set_index('date')
df1 = pd.concat([df.drop(s1.index), s2]).sort_index()
细节:
用于DataFrame.between_time
过滤数据帧中介df
于以下时间之间的09:00
行09:16
:
print(s1)
open high low close
date
2017-01-02 09:08:00 116.0 116.0 116.0 116.0
2017-01-02 09:16:00 116.1 117.8 117.0 113.0
用于DataFrame.groupby
将此过滤后的数据框分组并使用字典s1
进行date
聚合d
:
print(s2)
open high low close
date
2017-01-02 09:16:00 116.1 117.8 116.0 113.0
用于DataFrame.drop
从原始数据帧df
中删除介于 time 之间的行09:00-09:16
,然后用于pd.concat
将其与 连接s2
,最后用于DataFrame.sort_index
对索引进行排序:
print(df1)
open high low close
date
2017-01-02 09:16:00 116.10 117.80 116.00 113.00
2017-01-02 09:17:00 115.50 116.20 115.50 116.20
2017-01-02 09:18:00 116.05 116.35 116.00 116.00
2017-01-02 09:19:00 116.00 116.00 115.60 115.75
2019-12-29 15:57:00 260.00 260.00 260.00 260.00
2019-12-29 15:58:00 260.00 260.00 259.35 259.35
2019-12-29 15:59:00 260.00 260.00 260.00 260.00
2019-12-29 16:36:00 259.35 259.35 259.35 259.35
2029-12-29 15:56:00 259.35 259.35 259.35 259.35
推荐阅读
- c++ - 如果其他错误:如何使它打印任何数字?
- javascript - Jquery 计算器基础价格 + 25%
- python - 如何逐个单元格比较 2 个数据帧并返回单元格级别的更改
- eclipse - 如何将 Eclipse 工作区导入 IntelliJ
- azure-sql-data-warehouse - Azure SQL 数据仓库 - 分页
- java - 如何使用 Kerberos 在 hive UDF 中获得 HBase 连接?
- asp.net-mvc - 如何在 ASP.Net MVC 中使用 LINQ Lambda 连接三个表并将其放入 ViewModel?
- python-2.7 - sklearn.SVC 中的独立 SVC 行是做什么的?
- azure-functions - Azure 函数计时器 SQL 客户端失败
- javascript - 如何在 onmousedown 事件中打印变量 javascript?