How to create multiple plots for a specific time frame using DatetimeIndex in Python

Viewed 37

I have a data frame of "AAPL" (Here the whole dataset) in which I have 1-minute values:

    open    high    low close   volume  trade_count vwap
timestamp                           
2021-01-04 09:00:00+00:00   133.31  133.49  133.0200    133.4900    26666   87  133.233024
2021-01-04 09:01:00+00:00   133.49  133.49  133.4900    133.4900    1240    26  133.490887
2021-01-04 09:02:00+00:00   133.60  133.60  133.5000    133.5000    1217    30  133.523558
2021-01-04 09:03:00+00:00   133.51  133.51  133.5100    133.5100    741 18  133.569825
2021-01-04 09:04:00+00:00   133.77  133.77  133.7000    133.7200    1970    30  133.725553
... ... ... ... ... ... ... ...
2021-12-31 00:55:00+00:00   177.65  177.65  177.6000    177.6000    883 17  177.605028
2021-12-31 00:56:00+00:00   177.51  177.60  177.5100    177.5900    1425    17  177.596316
2021-12-31 00:57:00+00:00   177.68  177.70  177.5400    177.7000    1968    29  177.645234
2021-12-31 00:58:00+00:00   177.69  177.69  177.5901    177.5901    823 16  177.645200
2021-12-31 00:59:00+00:00   177.68  177.68  177.6500    177.6500    1152    33  177.655091

The index in data frame is in DatetimeIndex format:

DatetimeIndex(['2021-01-04 09:00:00+00:00', '2021-01-04 09:01:00+00:00',
               '2021-01-04 09:02:00+00:00', '2021-01-04 09:03:00+00:00',
               '2021-01-04 09:04:00+00:00', '2021-01-04 09:05:00+00:00',
               '2021-01-04 09:06:00+00:00', '2021-01-04 09:07:00+00:00',
               '2021-01-04 09:08:00+00:00', '2021-01-04 09:09:00+00:00',
               ...
               '2021-12-31 00:49:00+00:00', '2021-12-31 00:50:00+00:00',
               '2021-12-31 00:51:00+00:00', '2021-12-31 00:53:00+00:00',
               '2021-12-31 00:54:00+00:00', '2021-12-31 00:55:00+00:00',
               '2021-12-31 00:56:00+00:00', '2021-12-31 00:57:00+00:00',
               '2021-12-31 00:58:00+00:00', '2021-12-31 00:59:00+00:00'],
              dtype='datetime64[ns, UTC]', name='timestamp', length=207156, freq=None)

My aim is to compare 1-minute closing prices in a specific time frame (09:00:00 - 10:00:00) for every day. In this regard, I would like to create multiple charts for every trading day for 09:00:00-10:00:00 time duration.

2 Answers

I'm not sure if I fully understand the question and I used random data since I don't know where to find your dataset, but the principle should be the same since you want to separate by date/time and not actual values. I included comments in the code to explain what I'm trying to do.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import datetime

#Creating dataset (using random data for example)
t = pd.date_range('01-04-2021 09:00:00','31-12-2021 00:59:00',freq='1T')
df = pd.DataFrame(np.random.randint(999,size=(len(t),3)), index=t)
df.rename(columns={0: "open", 1: "low_close", 2: "high_close"}, inplace=True)

#Separating the data, first based on time, then based on date
interval = df.between_time('09:00','10:00') #Only contains data between 09:00 and 10:00
days_df = interval.groupby([interval.index.date]) #Make a seperate group (dataframe) for each day

#Make a separate image for each day (361 images)
for key,group in days_df:
    fig,ax = plt.subplots()
    ax.plot(group.open)

#Get data for a specific day and plot it
march19 = days_df.get_group(datetime.date(2021,3,19))
march19.plot()

I provide a similar answer, like Alex. Major problem is, that matplotlib cannot plot datetime.time objects, only datetime.datetime objects. Therefore I had to introduce a "dummy date". I strip the date from every timestamp and add for plotting the dummy date for each timestamp. This leads to an alignment of all daily closing prices.

You may remove the strptime code, as you have already datetime objects in your data frame. I had strings, because I imported test data from a test csv.

import datetime
import pandas as pd
import matplotlib.pyplot as plt

#read in data
df=pd.read_csv("test_csv.txt", delimiter=",")

#create two new columns based on "timestamp" column. Split date and time.
df["date"]=df["timestamp"].apply(lambda x: datetime.datetime.strptime(x, "%Y-%m-%d %H:%M:%S+00:00").date())
df["time"]=df["timestamp"].apply(lambda x: datetime.datetime.strptime(x, "%Y-%m-%d %H:%M:%S+00:00").time())
grp_trading_day=df.groupby("date")

#plot aligned data
dummy_date = datetime.date.today()
for trading_day, grp in grp_trading_day:
     x = grp["time"].apply(lambda x: datetime.datetime.combine(dummy_date, x))
     y = grp["close"]
     plt.plot(x, y)
plt.show()
Related