【问题标题】:How to create visualization from time series data in a .txt file in python如何从 python 中的 .txt 文件中的时间序列数据创建可视化
【发布时间】:2020-05-09 19:56:34
【问题描述】:

我有一个包含三列的 .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')

然后以某种方式将“tick”附加到“时间”列中每 5 分钟的数据(我不确定我会如何做到这一点),然后使用时间列作为索引并且只使用带有“勾选”索引(某种 if 语句)。我不确定这是否有意义,但我对此表示空白。

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    你应该看看 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)
    

    每 5 分钟重新采样时间序列

    这里可以试试看输出

    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。

    【讨论】:

    • 非常感谢!我明天试试这个。
    猜你喜欢
    • 2021-03-25
    • 2019-10-09
    • 2016-03-20
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2020-02-06
    • 1970-01-01
    相关资源
    最近更新 更多