Missing Bars in OHLCV Data for Backtesting: Audit and Fix
Handling missing bars in OHLCV data for backtesting starts with building the expected timestamp index, diffing it against your data, and separating real closures from true gaps. Then you drop, flag, limit-fill or refetch each gap by its size.
- Compare the data against an expected index (exchange calendar for equities and futures, fixed frequency for 24/7 crypto), because a raw diff() cannot tell a holiday from a vendor drop.
- Forward-filling creates synthetic zero-volume bars that shrink ATR, create fake zero returns and allow fills at prices that never traded.
- Never backward-fill or interpolate prices, since both use future information and interpolation smooths volatility.
- Use a tolerance policy: fill at most 1 to 2 bars on liquid symbols, invalidate indicator warm-up after larger gaps, and refetch or exclude a symbol-day with more than about 1 percent missing.
- Keep raw data untouched, log every change, write the gap report to a file and re-run the audit as a test on each data refresh.
Which gaps are legitimate and which are missing bars in OHLCV data for backtesting?
A gap in an OHLCV series is only a problem if the market was supposed to produce a bar there. Weekends, exchange holidays, early closes, overnight sessions and lunch breaks (several Asian exchanges) are expected closures. Treating them as holes and filling them manufactures bars that never existed.
Real missing data is different: a vendor dropped a batch, your downloader skipped a page, the exchange had an outage or a halt, or the vendor omits bars with no trades. These need a per-case decision. The table separates the cases that look identical in a raw diff.
| Gap type | Real missing data? | How to recognise it | Default handling |
|---|---|---|---|
| Weekend, holiday, early close, lunch break | No | Absent from the calendar schedule | Leave as is, never fill |
| Exchange outage or trading halt | Partly (market did not trade) | In the calendar, no bars from any vendor | Flag, block entries, gap-aware fills |
| Vendor drop or download error | Yes | In the calendar, but another source has the bars | Refetch from a second source |
| No-trade minute on an illiquid symbol | No, but bars may be omitted | Isolated single bars, other symbols have them | Flag as no-trade, or fill with volume 0 |
| Duplicate or shifted timestamps | Looks like a gap | DST jump, open-stamp vs close-stamp mix | Fix the timestamps, do not fill |
How do I build the expected timestamp index?
For equities and futures, take the session schedule from pandas_market_calendars (exchange_calendars works similarly) and expand it to bar stamps. The schedule includes early closes and per-session open and close times, and it is in UTC, so keep both indexes tz-aware in UTC and convert only for display.
Use closed='left' when your bars are stamped at the bar open, and closed='right' when stamped at the bar close. Getting this wrong shifts every bar by one interval and makes the first or last bar of every session look missing or extra.
For 24/7 crypto there is no calendar, so use pd.date_range(start, end, freq='1min', tz='UTC') and accept that real maintenance windows will show up as gaps.
import numpy as np
import pandas as pd
import pandas_market_calendars as mcal
def expected_index(cal_name, start, end, freq="1min", bar_stamp="open"):
if cal_name is None: # 24/7 crypto
return pd.date_range(start, end, freq=freq, tz="UTC", inclusive="left")
cal = mcal.get_calendar(cal_name) # e.g. "NYSE", "CME_Equity"
sched = cal.schedule(start_date=start, end_date=end)
closed = "left" if bar_stamp == "open" else "right"
return mcal.date_range(sched, frequency=freq, closed=closed)
def gap_audit(df, expected, freq="1min", symbol=""):
step = pd.Timedelta(freq)
df = df.sort_index()
df = df[~df.index.duplicated(keep="last")]
df.index = df.index.tz_convert("UTC")
expected = expected[(expected >= df.index[0]) & (expected <= df.index[-1])]
missing = expected.difference(df.index)
pct = 100 * len(missing) / max(len(expected), 1)
rows = []
gaps = df.index.to_series().diff()
for t, g in gaps[gaps > step].items():
prev = t - g
n = int(((expected > prev) & (expected < t)).sum())
rows.append({"symbol": symbol, "start": prev + step, "end": t - step,
"missing_bars": n,
"kind": "real_gap" if n > 0 else "closure"})
report = pd.DataFrame(rows)
return report, pct, missing
# usage
# exp = expected_index("NYSE", "2024-01-01", "2024-06-30", "1min")
# rep, pct, miss = gap_audit(df, exp, "1min", "SPY")
# rep[rep.kind == "real_gap"].to_csv("gap_report_SPY.csv")How do I find gaps and bad bars in OHLCV data with pandas?
Run structural checks before the gap diff, because duplicates and disorder corrupt it. Sort, drop duplicate stamps, then assert index.is_monotonic_increasing and index.is_unique. The diff-based report above already groups each hole into a run with start, end and bar count; divide the count of missing bars by the expected count for the percentage missing per symbol.
Plenty of bad data is not missing at all. These checks catch it:
| Symptom | Likely cause | Check |
|---|---|---|
| Duplicate timestamps | Overlapping download pages, vendor restatement | df.index.duplicated().sum() |
| Out-of-order rows | Concatenated CSVs | df.index.is_monotonic_increasing |
| high < low, or open/close outside high-low | Vendor error, bad merge | (df.high < df.low) | (df.close > df.high) | (df.close < df.low) |
| NaN or zero prices | Placeholder rows | df[['open','high','low','close']].le(0).any(axis=1) |
| Zero volume bars | No trades or synthetic fill | df.volume.eq(0).mean() |
| Stale repeated closes | Vendor forward-filled upstream | Runs of identical close with volume 0 |
| Gap or duplicate hour twice a year | DST: local naive timestamps | Look at the 02:00 transition, convert to UTC |
| Every session short by one bar | Open-stamp vs close-stamp mix | Compare first and last stamp of a session with the schedule |
Why does forward-filling missing candles bias a backtest?
Forward-fill makes a bar that never traded. Its close equals the previous close, its range is zero and its return is exactly 0. Every statistic computed over bars now includes fake observations.
ATR is the clearest example. With Wilder smoothing (alpha = 1/14), each flat bar has true range 0, so ATR is multiplied by 13/14 per bar. After 14 synthetic bars it is about 0.35 of its old value, and after 30 it is about 0.11. A volatility-scaled position size or a stop distance based on that ATR is then far too tight or far too large.
RSI and EMA are bar-count based too, but they fail differently. With Wilder smoothing, a flat bar (change = 0) decays the average gain and the average loss by the same 13/14 factor, so their ratio does not change and RSI stays frozen at its pre-gap value for the whole flat stretch. The first real bar after the gap then moves it in one jump. The EMA, meanwhile, converges to a stale price. That bar also carries the whole move as one return spike, which can trigger a breakout signal that was really an overnight-style jump.
Backward-fill and interpolation are worse because they use the next real price to build earlier bars. That is look-ahead. Linear interpolation also smooths the path, lowering measured volatility and inflating Sharpe.
def atr(df, n=14):
pc = df.close.shift()
tr = pd.concat([df.high - df.low,
(df.high - pc).abs(),
(df.low - pc).abs()], axis=1).max(axis=1)
return tr.ewm(alpha=1 / n, adjust=False).mean()
def ffill_bars(df, expected):
out = df.reindex(expected)
out["synthetic"] = out.close.isna()
c = out.close.ffill()
for col in ("open", "high", "low", "close"):
out[col] = out[col].fillna(c) # O=H=L=C=previous close
out["volume"] = out.volume.fillna(0) # never ffill volume
return out
# before/after: compare
# atr(df_raw) (holes, bar-count windows span more time)
# atr(ffill_bars(df, exp)) (decays toward 0 inside the gap)
# and mask instead of fill:
def mask_after_gap(ind, synthetic, n=14):
# NaN the indicator for n bars after any missing bar
bad = synthetic.astype(int).rolling(n, min_periods=1).max().astype(bool)
return ind.mask(bad)What should I do with missing bars in OHLCV data for backtesting: drop, flag, fill or refetch?
Dropping gaps keeps only real bars but leaves holes in the time index. A 20-bar rolling window then spans more wall-clock time than expected, and symbols no longer line up on the same rows. Flagging keeps the grid and carries a mask, so signals and entries can be skipped while the data stays honest.
For several symbols, build a union calendar and give each symbol an availability mask. Do not drop a timestamp for all symbols because one is missing, since that deletes valid data and shifts everyone's windows.
| Gap type and size | Liquid instrument | Illiquid or sparse symbol | Policy |
|---|---|---|---|
| Closure (holiday, weekend, lunch) | Any | Any | Leave alone, never fill |
| Real gap 1 to 2 bars | Limited fill, flagged | Treat as no-trade, volume 0 | Fill, set synthetic flag, no entries on it |
| Real gap 3 to N bars (N about 5 to 30) | Flag, NaN indicator warm-up | Flag | Refetch first, else invalidate window |
| Large gap or missing session | Refetch from second source | Refetch | If still missing, mark day untradable |
| More than about 1% missing per symbol-day | Exclude or refetch | Exclude | Log and drop that symbol-day from the test |
| Exchange halt or outage | Real market state | Real market state | Keep gap, use gap-aware fills |
How do gaps affect fill simulation, and how do I refetch candles with ccxt?
A stop or limit order that is gapped through must fill at the next available price, not the order price. For a sell stop at 98 where the next real bar opens at 95, the fill is min(open, stop) = 95. Filling at 98 gives an optimistic 3 points of slippage that never existed. Orders must also never execute on synthetic bars, so check the tradable flag before matching.
For crypto, ccxt fetch_ohlcv paginates with since and limit, and the per-call cap varies by exchange. A page can return fewer candles than the limit, and advancing by limit instead of by the last timestamp can silently skip candles. Always advance from the last returned timestamp, and repair gaps by refetching only the missing range.
import ccxt
ex = ccxt.binance({"enableRateLimit": True})
def refetch(symbol, tf, start, end, limit=1000):
tf_ms = ex.parse_timeframe(tf) * 1000
since, end_ms, out = ex.parse8601(start), ex.parse8601(end), []
while since < end_ms:
page = ex.fetch_ohlcv(symbol, tf, since=since, limit=limit)
if not page:
break
out += page
since = page[-1][0] + tf_ms # advance by last stamp, not by limit
df = pd.DataFrame(out, columns=["ts", "open", "high", "low", "close", "volume"])
df.index = pd.to_datetime(df.pop("ts"), unit="ms", utc=True)
return df[~df.index.duplicated()].loc[:end]
def fill_sell_stop(bar_open, stop):
return min(bar_open, stop) # gap-through fills at the open How do I make the audit repeatable?
Keep raw files read-only and write cleaned data to a separate path, with a change log listing every filled, dropped or refetched range. That makes any result traceable to a specific data state.
Turn the audit into a test that runs whenever data refreshes. Assert unique, sorted indexes, no OHLC violations, and that every remaining real_gap is either logged as accepted or below your threshold. Fail the run if the percentage missing for any symbol exceeds the limit, and save the report to a file next to the data version.
- Load raw data, convert to UTC, sort and deduplicate.
- Build the expected index from the calendar or fixed frequency.
- Run gap_audit and save the report per symbol.
- Refetch real gaps from a second source, then re-audit.
- Apply the policy table, adding synthetic and tradable flags.
- Assert no real gaps remain outside the accepted list, then write the cleaned data.
Common questions
How do I detect missing timestamps in a pandas time series?
Build the expected DatetimeIndex and call expected.difference(df.index) to list the missing stamps. For a quick check without a calendar, compute df.index.to_series().diff() and select values greater than the bar interval.
Does a zero-volume bar mean data is missing?
Not necessarily. On illiquid symbols a minute with no trades is real, and some vendors emit it as a flat bar with volume 0 while others omit it. Treat it as no-trade, not as a price observation, and keep it out of fills.
Is it ever safe to forward fill OHLCV data?
For 1 to 2 bars on a liquid instrument it is usually a small distortion if you set volume to 0, use O=H=L=C=previous close and flag the bar. Beyond that, indicators and fills are distorted enough that you should mask or refetch instead.
Why do my indicators differ between vendors for the same symbol?
Rolling windows count bars, so a vendor that omits empty bars gives a different window than one that emits flat bars. Different session definitions, timestamp conventions and adjustment for splits and dividends also change the inputs.
Should I drop rows where any symbol is missing in a multi-symbol backtest?
No. Dropping the timestamp for everyone discards valid data and shifts every symbol's windows. Use a union calendar with a per-symbol availability mask so a missing symbol is simply untradable on that bar.