簡體   English   中英

如何從python中的.txt文件中的時間序列數據創建可視化

[英]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)

每 5 分鍾重新采樣一次時間序列

在這里您可以嘗試查看輸出

df1.set_index("date")\
   .resample("5T")\
   .first()\
   .reset_index()

我們只考慮05:0010: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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM