Resample Tick Data to OHLCV in Pandas Without Lookahead
To resample tick data to OHLCV in pandas, sort trades by time, set a UTC DatetimeIndex, then join price.resample('1min', label='left', closed='left').ohlc() with size.resample('1min').sum(). Bars are stamped at their start, so shift them before use.
- Sort by timestamp with a stable sort before resampling, because first and last follow row order, not time order.
- With label='left', closed='left' a bar stamped 09:30 holds [09:30, 09:31) and is only known at 09:31, so join it to signals only after shifting one bar or restamping it to its close.
- Fill empty bars with the previous close for open, high, low and close, set volume to 0, and add an is_filled flag instead of forward-filling volume.
- Fill gaps only inside trading sessions; overnight and weekend gaps in equities and futures are not missing data.
- Prove there is no leakage by comparing 5m bars built from 1m bars with 5m bars built from ticks, and by truncating the ticks at time T.
How do I resample tick data to OHLCV bars in pandas?
Resampling needs a DatetimeIndex, so start with four preconditions. Parse timestamps to datetime64 in UTC, because string or mixed-offset timestamps give object columns that cannot be resampled correctly. Sort by time with a stable sort. Drop duplicate trades, using the trade id if the feed has one. Then set the timestamp as the index.
The core recipe uses .ohlc() on the price series and a sum on the size series, then joins the two. Because .ohlc() on a Series returns flat columns, there is no MultiIndex to flatten here. A MultiIndex only appears if you call .agg(['first','max']) on a DataFrame column, and in that case you flatten it with out.columns = [b for a, b in out.columns].
import pandas as pd
df['timestamp'] = pd.to_datetime(df['timestamp'], utc=True)
df = df.sort_values(['timestamp', 'trade_id'], kind='stable')
df = df.drop_duplicates('trade_id').set_index('timestamp')
r = df.resample('1min', label='left', closed='left')
bars = r['price'].ohlc()
bars['volume'] = r['size'].sum()
# Equivalent with an agg dict (gives a MultiIndex you must flatten)
alt = r.agg({'price': ['first', 'max', 'min', 'last'], 'size': 'sum'})
alt.columns = ['open', 'high', 'low', 'close', 'volume']A copy-paste ticks_to_ohlcv function with a worked example
The function below applies every precondition, computes volume, trade count, dollar volume and VWAP, handles empty bars, and can stamp bars at their start or end. The fill option takes 'none', 'session' (fill only within each calendar day of the session window) or 'all' (fill everything, for 24/7 markets).
Deduplication only happens when you pass seq, a trade-id or sequence column, and it drops rows that repeat that id. With no seq, the function does not deduplicate at all, because (timestamp, price, size) cannot tell a replayed print from two genuine identical fills. If your feed replays messages on reconnect and has no id, clean it upstream.
The example feeds five trades, deliberately out of order, through a 1-minute call. The output table follows the code.
| bar (UTC) | open | high | low | close | volume | trades | vwap | is_filled |
|---|---|---|---|---|---|---|---|---|
| 09:30 | 100.0 | 100.5 | 100.0 | 100.5 | 15 | 2 | 100.1667 | False |
| 09:31 | 101.0 | 101.0 | 100.8 | 100.8 | 30 | 2 | 100.9333 | False |
| 09:32 | 100.8 | 100.8 | 100.8 | 100.8 | 0 | 0 | NaN | True |
| 09:33 | 100.2 | 100.2 | 100.2 | 100.2 | 15 | 1 | 100.2000 | False |
import pandas as pd
from pandas.tseries.frequencies import to_offset
def ticks_to_ohlcv(df, freq='1min', tz='UTC', fill='none', session=None,
stamp='start', ts='timestamp', price='price', size='size',
seq=None, side=None):
'''fill: 'none' | 'session' | 'all'. session: ('09:30', '16:00') in tz.
stamp: 'start' = bar open time, 'end' = bar close time (safe to merge_asof).
seq: trade-id or sequence column. Used as the tie-break sort key and to
drop duplicate rows. If seq is None, NO deduplication is done, because
(timestamp, price, size) cannot distinguish replays from genuine identical
prints. Dedupe upstream if your feed has no trade id.'''
d = df.copy()
d[ts] = pd.to_datetime(d[ts], utc=True)
keys = [ts] + ([seq] if seq else [])
d = d.sort_values(keys, kind='stable')
if seq:
d = d.drop_duplicates(subset=[seq])
d = d.set_index(ts).tz_convert(tz)
d['_notional'] = d[price] * d[size]
if side:
d['_buy'] = d[size].where(d[side] == 'buy', 0.0)
r = d.resample(freq, label='left', closed='left')
out = r[price].ohlc()
out['volume'] = r[size].sum()
out['trades'] = r[size].count()
out['dollar_volume'] = r['_notional'].sum()
out['vwap'] = out['dollar_volume'] / out['volume'].where(out['volume'] > 0)
if side:
out['buy_volume'] = r['_buy'].sum()
out['sell_volume'] = out['volume'] - out['buy_volume']
if session: # filter AFTER resampling so bins stay aligned
out = out.between_time(*session, inclusive='left')
out['is_filled'] = out['trades'].eq(0)
if fill != 'none':
if fill == 'session':
prev = out['close'].groupby(out.index.date).ffill()
else:
prev = out['close'].ffill()
for c in ('open', 'high', 'low', 'close'):
out[c] = out[c].where(~out['is_filled'], prev)
out['volume'] = out['volume'].fillna(0)
if stamp == 'end':
out.index = out.index + to_offset(freq)
return out
ticks = pd.DataFrame({
'timestamp': ['2024-03-04 09:30:40', '2024-03-04 09:30:05', '2024-03-04 09:31:00',
'2024-03-04 09:31:30', '2024-03-04 09:33:10'],
'price': [100.5, 100.0, 101.0, 100.8, 100.2],
'size': [5, 10, 20, 10, 15]})
print(ticks_to_ohlcv(ticks, '1min', fill='all'))Why do my open and close values come out wrong or NaN?
'first' and 'last' (and the first and last column of .ohlc()) mean the first and last rows in each bin as stored, not the earliest and latest by time. If a CSV was merged from several files or a feed delivered late prints out of order, the open and close are arbitrary. A stable sort on [timestamp, sequence or trade id] fixes it, and stability keeps same-timestamp trades in feed order.
Use this checklist by symptom.
| Symptom | Likely cause | Fix |
|---|---|---|
| Open/close differ between runs or files | Unsorted rows; first/last follow row order | sort_values([ts, seq], kind='stable') before set_index |
| Open/close wrong only within one second | Ties at the same timestamp, unstable sort or no sequence column | Add trade id or sequence as the second sort key |
| Bars shifted by whole hours | Naive timestamps assumed local, or mixed offsets | pd.to_datetime(..., utc=True), then tz_convert for display |
| Error or object dtype index | Timestamps left as strings or epoch integers | Parse with unit='ms' or 'us' for epochs, then set_index |
| NaN OHLC rows | No trades in that interval | Apply the fill policy and flag with is_filled |
| Volume too high | Duplicate prints from reconnect replays | Dedupe on trade id, never on (timestamp, price, size) |
| Bars disagree with a vendor | Different closed/label rule or session filter | Match the vendor convention; see the boundary table below |
| Signal sees the future | Start-stamped bar joined at its own timestamp | Shift one bar or stamp at close and use merge_asof |
What do label and closed do, and where does the lookahead come from?
closed decides which edge of the interval is inclusive, and label decides which edge names the bar. For fixed frequencies such as 'min', 'h' and 'D', pandas defaults to left/left. For end-anchored frequencies ('ME', 'YE', 'QE', 'W' and similar) it defaults to right/right. A tick-bar script that works on '1min' can therefore change behaviour when you switch to month-end bars.
With left/left a bar stamped 09:30 holds [09:30, 09:31) and is complete only at 09:31. Take three trades: 100.5 at 09:30:40, 101.0 at 09:31:00 and 100.8 at 09:31:30. The boundary trade at exactly 09:31:00 lands in different bars depending on closed.
| Convention | Bar label | Bin contents | Result |
|---|---|---|---|
| closed='left', label='left' | 09:30 | [09:30, 09:31) | close 100.5 |
| closed='left', label='left' | 09:31 | [09:31, 09:32) | open 101.0, close 100.8 |
| closed='right', label='right' | 09:31 | (09:30, 09:31] | open 100.5, close 101.0 |
| closed='right', label='right' | 09:32 | (09:31, 09:32] | only 100.8 |
bars_start = ticks_to_ohlcv(ticks, '1min', fill='all') # stamped at start
bars_end = ticks_to_ohlcv(ticks, '1min', fill='all', stamp='end') # stamped at close
# LEAK: the 09:31 bar contains trades up to 09:31:59, yet a signal at 09:31:00 reads its close
bad = signals.join(bars_start['close'])
# FIX 1: shift one bar, so each row sees only the last COMPLETED bar
good1 = signals.join(bars_start['close'].shift(1))
# FIX 2: stamp at close and take the latest bar known at or before the signal
good2 = pd.merge_asof(signals.sort_index(), bars_end[['close']],
left_index=True, right_index=True, direction='backward')How should empty intervals and market gaps be handled?
Resample emits a row for every interval between the first and last trade. Empty ones have NaN open, high, low and close. In current pandas, a sum on an empty Series bin gives 0 and count gives 0, but older versions or min_count settings can return NaN, so apply fillna(0) to volume and trades explicitly.
The standard repair has three parts. Forward-fill only the close. Set open, high and low of an empty bar to that prior close, so the bar is flat. Keep volume at 0 and mark the row with is_filled. Never forward-fill volume or trade count, because that invents liquidity.
For equities and futures, filling overnight, weekend or holiday gaps pretends trading continued. Resample first, filter to session hours with between_time (or an exchange calendar for holidays and half days), then fill within each day. That is what fill='session' does in the function above. For 24/7 crypto, fill='all' is appropriate.
Mind the end of the session. A closing-auction print stamped 16:00:00 falls outside [09:30, 16:00), so decide whether it belongs in a separate closing bar or is dropped on purpose.
How do I add VWAP, buy/sell volume and filter trade conditions?
VWAP is the sum of price times size divided by the sum of size per bar. The mean of prices is not VWAP, because it weights a 1-share print the same as a 10,000-share print. Compute notional as a column first, then take two vectorized sums, as in the function. Avoid .apply with lambdas, which runs Python per group and is orders of magnitude slower.
Trade count is .count() on any non-null column, and dollar volume is the notional sum. For a buy/sell split, use the feed's aggressor side: put size where side == 'buy' into one column and take the remainder as sell volume. Without a side field, a tick-rule guess is an estimate and should be labelled as one.
Tick-built bars have open != previous close, by design, because the open is the first trade of the interval. Do not patch that. The one exception is a forward-filled empty bar, whose open is the prior close by construction. The first trade of a session is often an opening auction print, so decide whether it counts as the open.
Many consolidated equity feeds carry condition codes for auctions, odd lots, cancelled or corrected trades, and off-exchange prints. Filter on those codes before resampling, per your venue's code table, or highs and lows will include prints that were not regular trades.
Which alternatives exist, and how do I prove there is no leakage?
resample, pd.Grouper and floor grouping all bin on time but behave differently. For odd widths like '7min' or '13min', bins anchor to origin='start_day' (midnight in the index time zone) by default, so a width that does not divide 24 hours evenly drifts relative to the day. Use origin='epoch' for a universal grid, or offset='30min' to make 1h bars start at 09:30.
| Method | Empty bins | Use when |
|---|---|---|
| df.resample('5min', label='left', closed='left') | Emitted as NaN or 0 | Default choice; clean regular grid |
| df.groupby(pd.Grouper(freq='5min', label='left', closed='left')) | Emitted | You also group by symbol: Grouper(freq=...) plus 'symbol' |
| df.groupby(df.index.floor('5min')) | Skipped | Fast ad hoc bins on sparse data; reindex to restore the grid |
| Polars group_by_dynamic('ts', every='5m', closed='left', label='left') | Skipped unless upsampled | Large Parquet files; needs sorted ts |
- Build 1m bars from ticks with fill='none'.
- Aggregate them to 5m with first, max, min, last and sum, and compare with 5m bars built directly from ticks.
- Truncate the ticks at time T, rebuild, and assert that bars completed before T are identical to the full-data bars.
AGG = {'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last', 'volume': 'sum'}
def test_no_leakage(ticks, T):
b1 = ticks_to_ohlcv(ticks, '1min')
via_1m = b1.resample('5min', label='left', closed='left').agg(AGG)
direct = ticks_to_ohlcv(ticks, '5min')[list(AGG)]
live = direct['volume'] > 0
pd.testing.assert_frame_equal(via_1m[live], direct[live],
check_dtype=False, check_freq=False)
T = pd.Timestamp(T, tz='UTC')
cut = ticks[pd.to_datetime(ticks['timestamp'], utc=True) < T]
full = ticks_to_ohlcv(ticks, '5min')
part = ticks_to_ohlcv(cut, '5min')
done = part.index < T.floor('5min') # bars fully closed before T
pd.testing.assert_frame_equal(part[done], full.loc[part.index[done]],
check_dtype=False, check_freq=False)Common questions
Why is volume NaN instead of 0 in empty bars?
Sum over an empty bin returns 0 by default in modern pandas, but min_count=1 or some older versions return NaN. Apply volume.fillna(0) after resampling so the result does not depend on version or settings.
Should I use label='right' for trading bars?
Only if you also accept closed='right', which moves a trade at exactly the boundary into the earlier bar. A safer way to get close-time stamps is to resample with left/left and add the bar width to the index. That keeps boundary behaviour unchanged and lets merge_asof pick the last known bar.
Why don't my bars match my vendor's bars?
The usual causes are the closed rule at the boundary, whether the bar is stamped at its start or its end, and which trade conditions the vendor excludes. Compare a few boundary trades and one bar's volume, and adopt the vendor's convention.
Can I resample unsorted data without sorting?
Resample will run, but first and last follow row order, so open and close are unreliable. Sorting is cheap compared with debugging wrong candles.
Do I need to forward-fill bars for backtesting?
Fill within sessions if your strategy needs a regular grid, and keep the is_filled flag so fills and statistics can ignore synthetic bars. Do not fill across closed periods, because that creates trading that never happened.