我有一个文件,其中包含货币对(片段)的买/卖价:
RateDateTime RateBid RateAsk
2020-01-22 00:00:00.5945505 0.849190 0.849450
2020-01-22 00:00:00.5945526 0.849080 0.849520
2020-01-22 00:00:00.5945537 0.849040 0.849600
2020-01-22 00:00:00.5945552 0.849290 0.849610
2020-01-22 00:00:00.5946302 0.849300 0.849610
2020-01-22 00:00:02.5946370 0.849400 0.849610
2020-01-22 00:00:04.5946408 0.849400 0.849540
2020-01-22 00:00:04.5946432 0.849590 0.849730
2020-01-22 00:00:04.5946435 0.849160 0.849730
2020-01-22 00:00:04.5946438 0.849570 0.849940
2020-01-22 00:00:22.5946828 0.849560 0.849940
2020-01-22 00:00:37.5947048 0.849570 0.849940
我编写了此脚本来提取日期时间,买入和卖出价格,并以30秒为间隔找到平均和买入和卖出价格:
from datetime import datetime as dt
import pandas as pd
import re
date = []
bid = []
ask = []
time_format = "%Y-%m-%d %H:%M:%S"
with open("2020-01-22_pro_EURGBP.txt", "r") as prices:
next(prices)
for line in prices:
date_string = re.findall("\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}", line)[0]
date_parsed = dt.strptime(date_string, time_format)
date.append(date_parsed)
split = line.split()
bid.append(split[2])
ask.append(split[3])
df = pd.DataFrame({"Bid": bid, "Ask": ask}, dtype="float64", index=date)
mean = df.resample("30S").mean()
first = df.resample("30S").first()
final = pd.merge(mean, first, left_index=True, right_index=True)
final = final.rename(
columns={
"Bid_x": "Average Bid",
"Ask_x": "Average Ask",
"Bid_y": "First Bid",
"Ask_y": "First Ask",
}
)
final = final.rename_axis("Datetime")
print(final)
具有以下输出代码段:
Average Bid Average Ask First Bid First Ask
Datetime
2020-01-22 00:00:00 0.849325 0.849662 0.84919 0.84945
2020-01-22 00:00:30 0.849570 0.849937 0.84957 0.84994
2020-01-22 00:01:00 0.849501 0.849819 0.84956 0.84994
但是,例如,对于00:00:00到00:00:29.9999999之间的时间,我希望它四舍五入到00:00:30窗口,从00:00:30到00:00:59.9999999到00:01:00窗口等。我不确定如何解决这个问题。
答案 0 :(得分:0)
如果您使用的是熊猫的日期时间,则可以使用舍入方法:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.round.html
https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliases
类似:
date.round('min')