df.resample("30min").ohlc() looks like a one-liner, and on round-the-clock data it is. On anything that follows a trading calendar it quietly produces empty bars, hourly bars that straddle the open, half-length bars after lunch, and daily candles with the wrong high and low. This post walks through pandas resample ohlc on minute-level data that follows the A-share session layout (09:30–11:30 and 13:00–15:00), and shows how to get bars that line up with the sessions.
The series being resampled is a synthetic per-minute "heat" score for one unnamed stock, plus a per-minute mention count. The same code applies to prices, spreads, order-book imbalance or any other intraday measurement. You only need pandas and NumPy.
The sample data
import numpy as np import pandas as pd rng = np.random.default_rng(11) days = pd.bdate_range("2026-11-09", periods=5) pieces = [] for d in days: am = pd.date_range(d + pd.Timedelta("09:30:00"), d + pd.Timedelta("11:29:00"), freq="1min") pm = pd.date_range(d + pd.Timedelta("13:00:00"), d + pd.Timedelta("14:59:00"), freq="1min") pieces.append(am.append(pm)) idx = pieces[0] for p in pieces[1:]: idx = idx.append(p) heat = 40 + np.cumsum(rng.normal(0, 0.6, len(idx))) burst = (idx >= "2026-11-11 10:05") & (idx < "2026-11-11 10:40") # a short news burst heat = heat + np.where(burst, 18, 0) ticks = pd.DataFrame( {"heat": heat.round(2), "mentions": rng.poisson(3, len(idx)) + burst * 12}, index=idx, ) print(ticks.shape) # (1200, 2): 240 minutes x 5 days Each minute is stamped at its start (09:30 means 09:30:00–09:30:59). Wednesday has a 35-minute burst between 10:05 and 10:40. It is useful later for checking whether the bars catch it.
Step 1: the basic pandas resample ohlc call
bars = ticks["heat"].resample("30min").ohlc() print(bars.head(6)) print(len(bars), "bars,", bars["open"].isna().sum(), "of them empty") open high low close 2026-11-09 09:30:00 40.02 42.37 37.24 37.26 2026-11-09 10:00:00 37.80 39.05 36.29 37.88 2026-11-09 10:30:00 37.73 41.33 37.61 40.46 2026-11-09 11:00:00 41.67 43.56 39.95 42.68 2026-11-09 11:30:00 NaN NaN NaN NaN 2026-11-09 12:00:00 NaN NaN NaN NaN 203 bars, 163 of them empty resample builds a regular grid from the first timestamp to the last, so it fills the lunch break, the overnight gap and the weekend with empty bins. 163 of 203 bars are empty. Drop them:
bars = bars.dropna(how="all") print(len(bars)) # 40 = 8 half-hour bars x 5 days Do not forward-fill these rows. A forward-filled lunch bar tells a chart or a model that the market was open and flat for 90 minutes, which distorts volatility estimates, rolling windows and anything that counts bars.
The 30-minute bars happen to line up with the sessions because 09:30 and 13:00 are both multiples of 30 minutes from midnight. Wednesday morning shows the burst clearly:
open high low close 2026-11-11 09:30:00 50.78 51.38 47.73 48.75 2026-11-11 10:00:00 49.37 68.85 49.13 67.52 2026-11-11 10:30:00 66.71 67.27 46.31 46.31 2026-11-11 11:00:00 46.46 48.32 43.84 45.83 Step 2: hourly bars and the offset trap
Switch to 60 minutes and the alignment breaks:
h = ticks["heat"].resample("60min").ohlc().dropna() print(h.loc["2026-11-11"].index.time) # 09:00, 10:00, 11:00, 13:00, 14:00 Bins are anchored to midnight, so the first bar is labelled 09:00 and contains only 09:30–09:59. The 11:00 bar holds 11:00–11:29. You get five bars per day with two of them half-length.
The usual fix is offset:
h2 = ticks["heat"].resample("60min", offset="30min").ohlc().dropna() print(h2.loc["2026-11-11"].index.time) # 09:30, 10:30, 12:30, 13:30, 14:30 The morning is now correct, but the afternoon is not. The 12:30 bar contains only 13:00–13:29, and the 14:30 bar contains only 14:30–14:59. A single offset cannot fit a market whose two sessions start at times that differ by a non-whole number of hours (09:30 and 13:00 are 3.5 hours apart).
Step 3: session-aligned bars with groupby and origin="start"
The clean way is to resample each session separately and let each one start its own grid. Build a key that identifies the date and session, group by it, and use origin="start" so the bins begin at the first timestamp in each group.
session = np.where(ticks.index.hour < 12, "am", "pm") key = ticks.index.strftime("%Y-%m-%d") + "-" + session hourly = ( ticks.groupby(key)["heat"] .resample("60min", origin="start") .ohlc() .droplevel(0) # drop the session key, keep the timestamp ) print(hourly.loc["2026-11-11"]) open high low close 2026-11-11 09:30:00 50.78 68.85 47.73 67.52 2026-11-11 10:30:00 66.71 67.27 43.84 45.83 2026-11-11 13:00:00 46.81 51.76 45.76 47.26 2026-11-11 14:00:00 47.93 51.34 45.08 51.34 Four full one-hour bars per day, two per session, each starting at the session open. The same pattern works for 15-minute, 2-hour or any other bar size. For a 2-hour bar you get exactly one bar per session.
Because the grouping happens before resampling, no empty lunch bins are created at all, so the dropna step is not needed here.
Step 4: label and closed, and why they matter for joins
By default pandas labels each bar with its left edge and includes the left edge in the bin (label="left", closed="left"). Plenty of data vendors label bars by their end time instead. If you join your bars to a vendor's bars, or to events stamped at bar close, mismatched labels shift everything by one bar.
right_lab = ticks["heat"].resample("30min", label="right", closed="left").ohlc().dropna() print(right_lab.loc["2026-11-11"].head(2)) open high low close 2026-11-11 10:00:00 50.78 51.38 47.73 48.75 2026-11-11 10:30:00 49.37 68.85 49.13 67.52 Same numbers, labels moved forward by 30 minutes. A bar labelled 10:00 now means "the bar that finished at 10:00". Pick one convention, write it down next to the code, and convert other sources to it before merging. When you feed bars into a backtest or any model that must not see the future, end-of-bar labels are often safer, because the label is the moment the bar's values are actually known.
Changing closed matters mostly for data stamped at the end of each minute (where 10:00 means the minute 09:59–10:00). Then closed="right" puts that observation in the 09:30–10:00 bar where it belongs.
Step 5: OHLC plus other columns with named aggregation
.ohlc() applies to every column, which is rarely what you want. On the whole frame it returns a MultiIndex with an OHLC for mentions too:
print(ticks.resample("30min").ohlc().columns.tolist()[:5]) # [('heat', 'open'), ('heat', 'high'), ('heat', 'low'), ('heat', 'close'), ('mentions', 'open')] An "open" of a mention count is meaningless. Use named aggregation to get OHLC for one column and a sum for the other in a flat frame:
agg = ( ticks.resample("30min") .agg(open=("heat", "first"), high=("heat", "max"), low=("heat", "min"), close=("heat", "last"), mentions=("mentions", "sum"), n_obs=("heat", "count")) .dropna(subset=["open"]) ) print(agg.loc["2026-11-11 09:30":"2026-11-11 11:00"]) open high low close mentions n_obs 2026-11-11 09:30:00 50.78 51.38 47.73 48.75 75 30 2026-11-11 10:00:00 49.37 68.85 49.13 67.52 376 30 2026-11-11 10:30:00 66.71 67.27 46.31 46.31 224 30 2026-11-11 11:00:00 46.46 48.32 43.84 45.83 98 30 first, max, min and last reproduce .ohlc() exactly. The n_obs column is worth keeping. When the source has gaps (a feed outage, a halted stock), a bar built from 4 minutes looks the same as one built from 30 unless you record the count. Filter or flag bars where n_obs is well below the expected value.
Note the dropna(subset=["open"]): summing an empty bin gives 0, not NaN, so dropna(how="all") would keep the lunch rows.
Step 6: building daily candles from intraday bars
Daily candles should be built from the intraday OHLC columns, each with its own rule. Resampling the closes is a common shortcut, and it is wrong.
daily = ( agg.resample("1D") .agg({"open": "first", "high": "max", "low": "min", "close": "last", "mentions": "sum"}) .dropna(subset=["open"]) ) print(daily.round(2)) shortcut = agg["close"].resample("1D").ohlc().dropna() print((daily["high"] - shortcut["high"]).round(2).tolist()) open high low close mentions 2026-11-09 40.02 45.71 36.29 40.83 686 2026-11-10 41.17 52.91 39.29 51.53 737 2026-11-11 50.78 68.85 43.84 51.34 1135 2026-11-12 51.25 55.83 42.10 55.83 756 2026-11-13 55.38 56.37 45.81 50.10 717 [0.8, 0.89, 1.33, 0.0, 1.84] The shortcut only sees one value per bar, so it misses any intrabar extreme. Here it understates the daily high on four of five days. The same error appears whenever you resample a resampled close series. Always carry the full OHLC through each level of aggregation.
"1D" works here because all rows of a session day share one calendar date. For markets with night sessions that cross midnight, define a trading-date column first and group by it instead.
Step 7: many tickers at once
With a long frame holding several tickers, group by ticker and resample in one chain:
a = ticks.assign(ticker="A") b = ticks.assign(ticker="B", heat=ticks["heat"] * 0.5 + 10) both = pd.concat([a, b]) per_ticker = ( both.groupby("ticker")["heat"] .resample("30min") .ohlc() .dropna() ) print(per_ticker.index.names) # ['ticker', None] print(per_ticker.loc["A"].head(2)) The result has a two-level index, ticker then timestamp. To combine this with session alignment, add the session key to the groupby: both.groupby(["ticker", key_series]). The key has to be a Series aligned to both, not a plain array built from ticks, because the long frame has twice as many rows.
Step 8: a quick use for the bars
With clean bars you can rank intervals by intrabar range, a simple way to find bursts of activity:
agg["range_pct"] = (agg["high"] - agg["low"]) / agg["open"] * 100 print(agg["range_pct"].nlargest(3).round(2)) 2026-11-11 10:00:00 39.94 2026-11-11 10:30:00 31.42 2026-11-10 09:30:00 16.74 The two Wednesday bars that hold the burst come out on top, far ahead of the next one. Pair this with the mentions sum and you have a basic "something happened here" detector that works at any bar size.
FAQ
Why does pandas resample ohlc return NaN rows?
Because resample creates a continuous time grid and fills bins with no data with NaN. For session data, drop them with dropna(how="all"), or avoid creating them by grouping by session before resampling.
What is the difference between offset and origin in resample?
offset shifts every bin edge by a fixed amount. origin sets the anchor the grid starts from: "start_day" (the default, midnight), "start" (the first timestamp), "epoch", or a specific timestamp. Combined with a groupby, origin="start" gives each group its own grid.
Can I resample tick data with irregular timestamps?
Yes. resample only needs a DatetimeIndex. It does not care about spacing. Make sure the index is sorted and timezone-consistent, and keep a count column so thin bars are visible.
Conclusion
pandas resample ohlc does the arithmetic correctly. The problems come from the time grid. Drop or avoid empty session bins, do not trust offset alone when sessions open at odd times, group by session with origin="start" for aligned bars, choose and document a label convention, use named aggregation when columns need different rules, and build daily candles from full intraday OHLC, not from closes.
For a live example of intraday heat for a single stock with the same bursty shape as the sample data, see Lava's Cambricon heat monitor. Lava tracks news-flow heat for A-share stocks and theme sectors and serves it over MCP and an API, a must-have for quant trading and heat monitoring for institutions and KOLs.
中文简介:本文讲 pandas resample().ohlc() 在有午休的交易时段数据上的正确用法:以 A 股 09:30–11:30、13:00–15:00 的分钟级热度为例,说明默认重采样为何生成大量空 bar、60 分钟 bar 用 offset 仍会在午后切出半根 bar,并给出按交易日+上下午分组、origin="start" 的对齐写法;还覆盖 label/closed 约定、用命名聚合同时算 OHLC 与提及数、从日内 OHLC 正确合成日线(而不是对收盘值再做 ohlc),以及多标的分组重采样。数据为合成样本,仅作方法演示。