Pandas grouper date_time as per the market hours (Indian Stock Exchange)

Viewed 181

Below data is in the interval of 5 mins

Dataframe names as df:

script_id date_time open high low close volume
0 201 2019-02-04 14:55:00 1408.05 1408.05 1407 1408 2384
1 201 2019-02-04 15:00:00 1408 1410.6 1407.2 1408.85 12621
2 201 2019-02-04 15:05:00 1408.85 1410.45 1407.05 1407.05 3880
3 201 2019-02-04 15:10:00 1407.05 1409.4 1404.85 1404.85 12992
4 201 2019-02-04 15:15:00 1404.85 1408.7 1403.5 1404.25 30803
5 201 2019-02-04 15:20:00 1404.25 1405 1402.7 1404.8 14624
6 201 2019-02-04 15:25:00 1404.8 1405 1402.05 1403.8 8407
7 201 2019-02-05 09:15:00 1400 1416.05 1400 1410.75 17473

trying to group it in 10 mins by executing below code:

df_f = df.groupby(['script_id', pd.Grouper(key='date_time', freq='10T', origin='start')])\
                        .agg(open=pd.NamedAgg(column='open', aggfunc='first'),
                            high=pd.NamedAgg(column='high', aggfunc='max'),
                            low=pd.NamedAgg(column='low', aggfunc='min'),
                            close=pd.NamedAgg(column='close', aggfunc='last'),
                            volume=pd.NamedAgg(column='volume', aggfunc='sum'))\
                            .reset_index()
            print(df_f)

Result:

result

Expected Result:- 0,1,2 are as expected below should be for 3 and there should not be 4.

script_id date_time open high low close volume
3 201 2019-02-04 15:25:00 1404.8 (value of 6) 1416.05 (highest among 6 & 7) 400 (lowest among 6 & 7) 1410.75 (value of 7) 25880 (sum of 6 & 7)

How can we combine last two 5min tf to one 10min tf?

Note:- There are possibilities to have holiday gap as well between two days

enter image description here

1 Answers

Maybe:

a = {'script_id': 'first', 'date_time': 'first', 'open': 'first', 'high':'max', 'low':'min', 'close':'last', 'volume':'sum'}

print(df.groupby(df.index // 2).agg(a))

   script_id            date_time     open     high      low    close  volume
0        201  2019-02-04 14:55:00  1408.05  1410.60  1407.00  1408.85   15005
1        201  2019-02-04 15:05:00  1408.85  1410.45  1404.85  1404.85   16872
2        201  2019-02-04 15:15:00  1404.85  1408.70  1402.70  1404.80   45427
3        201  2019-02-04 15:25:00  1404.80  1416.05  1400.00  1410.75   25880
Related