![](/img/trans.png)
[英]How to create supervised learning dataset from time series data in python
[英]How to create visualization from time series data in a .txt file in python
我有一个包含三列的 .txt 文件:时间、股票代码、价格。 时间间隔为 15 秒。 看起来这个上传到 jupyter notebook 并放入 Pandas DF。
time ticker price
0 09:30:35 EV 33.860
1 00:00:00 AMG 60.430
2 09:30:35 AMG 60.750
3 00:00:00 BLK 455.350
4 09:30:35 BLK 451.514
... ... ... ...
502596 13:00:55 TLT 166.450
502597 13:00:55 VXX 47.150
502598 13:00:55 TSLA 529.800
502599 13:00:55 BIDU 103.500
502600 13:00:55 ON 12.700
# NOTE: the first set of data has the data at market open for -
# every other time point, so that's what the 00:00:00 is.
#It is only limited to the 09:30:35 data.
我需要创建一个函数,它接受一个输入(股票代码),然后创建一个条形图,以 5 分钟的时间刻度显示数据(数据是每 20 秒一次,所以每 15 个时间点)。
到目前为止,我已经考虑过将 hh:mm:ss 的“mm”部分分开,以获取另一列中的分钟数,然后正确使用一个看起来像这样的 for 循环:
for num in df['mm']:
if num %5 == 0:
print('tick')
然后以某种方式为每 5 分钟的数据将“刻度”附加到“时间”列(我不确定我将如何执行此操作),然后使用时间列作为索引并且仅使用带有“刻度”索引的数据在其中(某种 if 语句)。 我不确定这是否有意义,但我对此空白。
您应该看看 pandas 中的内置函数。 在以下示例中,我使用的是日期 + 时间格式,但将一种格式转换为另一种格式应该不难。
%matplotlib inline
import pandas as pd
import numpy as np
dates = pd.date_range(start="2020-04-01", periods=150, freq="20S")
df1 = pd.DataFrame({"date":dates,
"price":np.random.rand(len(dates))})
df2 = df1.copy()
df1["ticker"] = "a"
df2["ticker"] = "b"
df = pd.concat([df1,df2], ignore_index=True)
df = df.sample(frac=1).reset_index(drop=True)
在这里您可以尝试查看输出
df1.set_index("date")\
.resample("5T")\
.first()\
.reset_index()
我们只考虑05:00
、 10:00
等的第一个元素。 一般来说,我们需要一个groupby
对每个股票做同样的事情
out = df.groupby("ticker")\
.apply(lambda x: x.set_index("date")\
.resample("5T")\
.first()\
.reset_index())\
.reset_index(drop=True)
def plot_tick(data, ticker):
ts = data[data["ticker"]==ticker].reset_index(drop=True)
ts.plot(x="date", y="price", kind="bar", title=ticker);
plot_tick(out, "a")
然后你可以改进情节,或者最终尝试使用plotly 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.