Howwise RSS
Trading Software6 min read

Pandas Resample OHLC: Correct Bars, Labels and No Lookahead

Short answer

Pandas resample ohlc works by grouping a sorted DatetimeIndex into bins and applying first, max, min, last and sum. Use label='left', closed='left' for bar-start stamps, and shift(1) before joining bars to finer data.

Key takeaways
  • Use resample('5min', label='left', closed='left').agg(...) with first/max/min/last/sum on a sorted, de-duplicated DatetimeIndex.
  • A bar stamped with its start time is unknown until it ends, so shift higher-timeframe values by one bar before joining them to minute data.
  • Empty bins yield NaN prices and 0 volume; either drop them with dropna on close or forward-fill close and set open/high/low to it.
  • Daily bars for futures and FX need an exchange-session offset in a tz-aware index, not UTC midnight.
  • Prove correctness by asserting volume totals match the source and by recomputing bars on truncated data.

What is the correct pandas resample OHLC recipe for 1-minute data?

For bar data that already has open, high, low, close and volume columns, aggregate each column with its own function. First and last return the first and last non-NaN value in each bin in index order, so the index must be sorted ascending or they return the wrong rows silently.

The snippet below is self-contained. It builds a tiny frame, resamples to 5 minutes, and checks it against the raw data.

import pandas as pd

idx = pd.date_range('2024-03-04 09:30', periods=10, freq='1min', tz='America/New_York')
m1 = pd.DataFrame({
    'open':  [10,11,12,11,13,14,15,14,13,12],
    'high':  [11,12,13,13,14,15,16,15,14,13],
    'low':   [ 9,10,11,10,12,13,14,13,12,11],
    'close': [11,12,11,13,14,15,14,13,12,13],
    'volume':[100]*10}, index=idx)

assert m1.index.is_monotonic_increasing and not m1.index.has_duplicates

m5 = m1.resample('5min', label='left', closed='left').agg(
    {'open':'first','high':'max','low':'min','close':'last','volume':'sum'})

assert m5['volume'].sum() == m1['volume'].sum()
assert m5['open'].iloc[0] == m1['open'].iloc[0]
assert m5['close'].iloc[-1] == m1['close'].iloc[-1]
print(m5)
Tip: Pandas 2.2 renamed aliases: 'T' is now 'min', 'H' is 'h', 'M' is 'ME', 'Y' is 'YE', 'Q' is 'QE'. The old ones emit FutureWarning and later versions remove them.

How do I resample tick data to OHLC bars?

Ticks have one price and one size per row. Series.resample().ohlc() returns four columns, and volume is a separate sum. Convert epoch timestamps explicitly: pd.to_datetime(x, unit='ms', utc=True) for milliseconds, unit='ns' for nanoseconds. Using the wrong unit puts everything in 1970.

The gotcha: calling ohlc() on a DataFrame with several columns returns a column MultiIndex such as ('price','open'). Selecting a single Series avoids that. If you must use a DataFrame, flatten the columns.

A tick VWAP needs price times size summed per bin, divided by size summed. Count gives trade count. Empty bins give NaN for VWAP because 0/0 is undefined, which is correct.

t = ticks.sort_index()                       # ticks: index=DatetimeIndex UTC, cols price,size
# Deduplicate on a trade ID if the feed has one (e.g. t.drop_duplicates('trade_id')).

r = t['price'].resample('1min', label='left', closed='left')
bars = r.ohlc()                               # columns: open high low close
bars['volume'] = t['size'].resample('1min').sum()
bars['trades'] = t['price'].resample('1min').count()
notional = (t['price'] * t['size']).resample('1min').sum()
bars['vwap'] = notional / bars['volume'].where(bars['volume'] > 0)

# flatten if you used a DataFrame:
# g = t[['price']].resample('1min').ohlc(); g.columns = g.columns.get_level_values(-1)
Warning: Do not drop duplicate timestamps on ticks by index alone: several genuine trades share a millisecond. Deduplicate on a trade id, or on the full row if no id exists.

What do label and closed do, and how do they cause lookahead?

closed decides which edge of the bin is inclusive; label decides which edge becomes the timestamp. For most frequencies (min, h, D) both default to left. For 'ME', 'YE', 'QE', 'W' and similar, both default to right, so a monthly bar is stamped with the month end.

Left/left gives the bin [09:30, 09:35) stamped 09:30. That stamp is the bar start, but the close is only known at 09:35. If you join that row to other data on timestamp, a 09:31 minute row picks up a close from 09:34. That is lookahead.

The fix is a convention: either stamp bars with their close time and only use them from that instant, or keep start stamps and shift by one bar before use.

Right/right gives (09:30, 09:35] stamped 09:35. The stamp is honest about availability, but a trade at exactly 09:30:00 now falls into the previous bar, which usually surprises people with minute data stamped at bar start.

In the table, each Setting reads label/closed, in that order.

Setting (label/closed)BinStampTrade at 09:35:00 goes toSafe to use from
label='left', closed='left'[09:30, 09:35)09:30next bar (09:35)09:35, not the stamp
label='right', closed='right'(09:30, 09:35]09:35this bar (09:35)its stamp
label='left', closed='right'(09:30, 09:35]09:30this bar09:35, not the stamp
label='right', closed='left'[09:30, 09:35)09:35next barits stamp
Tip: Left/left plus an explicit available_at column (stamp + bar length) is the least confusing choice for intraday data, because the bin matches the exchange's own bar definition.

How do I join higher-timeframe bars to minute data without lookahead?

A daily or hourly value joined back to minute rows must come from the previous completed bar. Forward-filling a start-stamped daily close onto every minute of that day gives every minute the day's final close.

Two safe patterns: shift the HTF frame by one bar then reindex with ffill, or use merge_asof on an availability time. The test below then proves it by recomputing on truncated data.

h1 = m1.resample('1h', label='left', closed='left').agg(
    {'open':'first','high':'max','low':'min','close':'last','volume':'sum'})

# Pattern A: shift one HTF bar, then ffill onto minutes
prev_h = h1[['close']].shift(1).add_prefix('h1_')
m1a = m1.join(prev_h.reindex(m1.index, method='ffill'))

# Pattern B: explicit availability time + merge_asof
h1b = h1[['close']].copy()
h1b['available_at'] = h1b.index + pd.Timedelta('1h')
m1b = pd.merge_asof(m1.sort_index(), h1b.sort_values('available_at'),
                    left_index=True, right_on='available_at',
                    direction='backward', allow_exact_matches=True)

# Lookahead test: bars built from data cut at time T must equal full-data bars before T
def bars(df): return df.resample('5min', label='left', closed='left').agg(
    {'open':'first','high':'max','low':'min','close':'last','volume':'sum'})
T = m1.index[7]
full = bars(m1)
trunc = bars(m1[m1.index < T])
complete = trunc.index[trunc.index + pd.Timedelta('5min') <= T]
pd.testing.assert_frame_equal(full.loc[complete], trunc.loc[complete])
Warning: In live trading the last bar is partial until its end. Drop it, or act only when the next bar's first tick arrives. Treating an in-progress bar as closed repaints your signals.

How do I handle empty intervals, weekends and sessions?

resample creates a row for every bin between the first and last timestamp, including holidays and weekends. Sum of volume gives 0, while open, high, low and close are NaN. Pass min_count=1 to sum if you want NaN instead of 0. Note that 'first' and 'last' skip NaN values, so a bin with a NaN open and a valid later value picks the later one.

Choose by whether the gap is a real closure. Real closures (weekend, holiday, overnight): drop. Quiet market that is still open: carry the close forward.

Always do this on a tz-aware index in the exchange timezone. Convert with tz_convert('America/New_York') so DST shifts do not move your session by an hour.

Daily bars should follow session boundaries. For a US equity session starting 09:30 local, use offset or origin. For futures and FX with a 17:00 New York roll, an offset of 17h on a New York index stops UTC midnight from splitting a session.

SituationActionCode
Weekend or holiday binsDropbars.dropna(subset=['close'])
Open market, no tradesCarry forwardc = b['close'].ffill(); b['close']=c; b[['open','high','low']] = b[['open','high','low']].apply(lambda s: s.fillna(c))
Regular hours onlyFilter before resamplingm1.between_time('09:30','15:59')
Daily from 09:30 startOffsetresample('1D', offset='9h30min')
Daily from 17:00 rollOffset on NY tzresample('1D', offset='17h')
Volume NaN not 0min_count['volume'].resample('5min').sum(min_count=1)
ny = m1.tz_convert('America/New_York')
rth = ny.between_time('09:30', '15:59')
daily = rth.groupby(rth.index.date).agg(
    {'open':'first','high':'max','low':'min','close':'last','volume':'sum'})

# futures/FX: session starts 17:00 New York, label by session start
fx = ny.resample('1D', offset='17h', label='left', closed='left').agg(
    {'open':'first','high':'max','low':'min','close':'last','volume':'sum'}).dropna(subset=['close'])
Warning: Around DST changes, a fixed UTC offset session differs by an hour from local time, and a 23 or 25 hour local day is possible. Check bar counts on the two transition dates in your data.

How do I make resampling fast on large tick data?

Resample is vectorised, but the cost grows with row count and with object dtypes. Use float64 or float32 prices and int sizes, and keep the DatetimeIndex sorted before the call.

For files that do not fit in memory, read chunks and keep bars from the previous chunk's final bin as incomplete. Concatenate chunks of ticks aligned on bar boundaries, then aggregate once. Merging already-aggregated partial bars requires first of opens, max of highs, min of lows, last of closes and sum of volume.

pd.Grouper(freq='1min') inside groupby is equivalent and lets you group by symbol too. Polars group_by_dynamic does the same job multi-threaded, and is the usual alternative when pandas is too slow.

# pandas: bars per symbol
out = (ticks.sort_index()
       .groupby(['symbol', pd.Grouper(freq='1min')])
       .agg(open=('price','first'), high=('price','max'), low=('price','min'),
            close=('price','last'), volume=('size','sum')))

# polars
import polars as pl
bars = (pl.read_parquet('ticks.parquet').sort('ts')
        .group_by_dynamic('ts', every='1m', closed='left', label='left', group_by='symbol')
        .agg(pl.col('price').first().alias('open'), pl.col('price').max().alias('high'),
             pl.col('price').min().alias('low'), pl.col('price').last().alias('close'),
             pl.col('size').sum().alias('volume')))

Common questions

Why are my resampled opens and closes wrong?

Almost always the index is unsorted or has out-of-order rows, so first and last follow row order instead of time. Call sort_index() before resampling and confirm with index.is_monotonic_increasing.

Why does resample ohlc return a MultiIndex of columns?

Calling ohlc() on a DataFrame produces a level for each input column and one for open, high, low, close. Call it on a single Series, or set df.columns = df.columns.get_level_values(-1) for a single-input frame.

Can I resample 5-minute bars into hourly bars?

Yes, apply the same aggregation (first, max, min, last, sum) to the 5-minute columns. Never run ohlc() on already-built close prices, as that discards true highs and lows.

Why do I get weekend bars with NaN?

Resample fills every bin between the first and last timestamp, including closed periods. Remove them with dropna(subset=['close']) or filter by session before aggregating.

How do I resample to a monthly bar without a lookahead?

Monthly frequencies such as 'ME' default to label='right', stamping the bar with the month end date at midnight, which precedes that day's trading. Shift by one bar or stamp with the actual last trading timestamp before joining to daily data.

Related topics:pandasresampleohlcvbacktestinglookahead-bias