Sumanth Lingappa
Sumanth Lingappa

Reputation: 536

pandas OHLC aggregation resample with time of OHLC

I am converting 1 minute candle to 5 minute candle as below:

df = df.resample("5min").agg({
'stock_name': 'first', 
'tr_open': 'first', 
'tr_high': 'max', 
'tr_low': 'min', 
'tr_close': 'last'
})

For some reason, I need the time when OHLC values were taken for this aggregation.

Meaning, tr_time_high should contain the time when the tr_high was HIGH in this 5min candle etc.

How can I achieve this in Pandas?

Thanks in advance.

Upvotes: 1

Views: 604

Answers (1)

Corralien
Corralien

Reputation: 120439

I prefer used groupby_agg instead resample_agg in your case to allow naming aggregation. Try:

df.groupby(pd.Grouper(freq='5T')).agg(
   stock=('stock_name', 'first'),
   open=('tr_open', 'first'),
   high=('tr_high', 'max'),
   low=('tr_low', 'min'),
   close=('tr_close', 'last'),
   time_high=('tr_high', 'idxmax'),
)

Upvotes: 1

Related Questions