pandasdataframeresample

How to handle discrete times with df.resample?


Trading hours are from 9:00 to 10:15, from 10:30 to 11:15, from 11:15 to 11:30, from 13:30 to 15:00

The 30-minute K-line time in the trading software is as follows: 9:00 to 9:30, 9:30 to 10:00, 10:00 to 10:45, 10:45 to 11:15, 11:15 to 13:15, 13:15 to 14:45 , 14:45 to 15:00

If the time I get from df.resample is continuous, how can I make it appear the same as in the trading software?

Input:

df.resample('30T').agg({'open':'first','high':'max','low':'min','close':'last','volume':'sum'})

Output:

enter image description here

10:15 to 10:45 because the market is closed for 15 minutes, so the trading time is 30 minutes

I use the 1-minute K-line to synthesize the 30-minute K-line, so I try

df2=df.reset_index()
r=df2.index//30
df2.groupby(r).agg({'date':'last','open':'first','high':'max','low':'min','close':'last','volume':'sum'})

But the last candlestick must be from 14:45 to 15:00


Solution

  • Hope to help everyone.

    df=df.reset_index()
    trading_hour=['09:30','10:00','10:45','11:15','13:45','14:15','14:45','15:00','21:30','22:00','22:30','23:00']
    m30=df['date'].dt.strftime('%H:%M').isin(trading_hour).shift().fillna(False)
    res=df.groupby(m30.cumsum()).agg({'date':'last','open':'first','high':'max','low':'min','close':'last','volume':'sum'})