A Tick-Backtesting Pipeline: Resampling Ticks to Bars in QuestDB, Feeding a Python Strategy
A single L2 feed can produce tens of millions of ticks a day. Pulling them all into pandas for a backtest will blow up memory and speed before the strategy ever finishes. The common workaround pushes resampling (tick → 1s/1m bars) into Python as well, which just moves the bottleneck from “the strategy is slow” to “the aggregation is slow.”
QuestDB is a good fit for cutting the pipeline in the middle: storage and resampling live in the database, strategy logic and equity math live in Python. Bar-level data is a few thousand times smaller than the tick stream, so Python can hold it in memory and iterate fast, while the aggregation throughput that QuestDB is built for does the heavy lifting.
market data → ILP into ticks table → SQL SAMPLE BY into 1s/1m bars (OHLCV)
→ Python fetches bars (REST / iob) → per-bar strategy loop → equity curve
1. Table design: one table for many instruments, SYMBOL underneath
CREATE TABLE ticks (
symbol SYMBOL, -- high-cardinality strings: SYMBOL is cheaper to store & join
price DOUBLE,
size DOUBLE,
side CHAR -- 'B' buy / 'S' sell
) TIMESTAMP (ts) PARTITION BY DAY;
CREATE TABLE bars_1m (
symbol SYMBOL,
open DOUBLE,
high DOUBLE,
low DOUBLE,
close DOUBLE,
volume DOUBLE
) TIMESTAMP (ts) PARTITION BY DAY;
Ticks partition by day: hot data stays local, cold data converts to Parquet on object storage — the standard retention trio covered in the data-retention article. Many instruments share one tick table, distinguished by the symbol column (a SYMBOL type).
Writes go over ILP with nanosecond timestamps:
ILP: ticks,5000 symbol=600519.SS price=1688.50 size=100 side=B ts=1753344000000000000
2. SQL resampling: SAMPLE BY into bars
-- 1-minute OHLCV, grouped per instrument
INSERT INTO bars_1m
SELECT symbol,
first(price) AS open,
max(price) AS high,
min(price) AS low,
last(price) AS close,
sum(size) AS volume
FROM ticks
WHERE ts IN '2026-07-24'
GROUP BY symbol, SAMPLE BY 1m;
Note the GROUP BY symbol, SAMPLE BY 1m form: it groups by instrument first, then windows each instrument into 1-minute buckets, so two symbols’ bars can never mix.
For cross-timezone backtests, give SAMPLE BY a timezone so windows align to exchange sessions instead of UTC:
SELECT symbol, ts, close
FROM bars_1m
WHERE ts IN '$last 90d'
SAMPLE BY 1d TIMEZONE('Asia/Shanghai');
Indicators can be precomputed in SQL before Python ever touches the data, e.g. a 20-bar rolling volatility:
SELECT ts, symbol, close,
stddev(close, 20) OVER (
PARTITION BY symbol ORDER BY ts
RANGE BETWEEN '19' MINUTE PRECEDING AND CURRENT ROW
) AS roll_vol
FROM bars_1m
WHERE symbol = '600519.SS';
3. The Python side: fetch bars, run the strategy, print the equity
Pull bars via the REST endpoint (just pip install pandas requests):
import requests, pandas as pd, io
URL = "http://localhost:8812"
def fetch_bars(symbol: str, since: str) -> pd.DataFrame:
q = (f"SELECT ts, open, high, low, close, volume FROM bars_1m "
f"WHERE symbol='{symbol}' AND ts IN '{since}' ORDER BY ts")
r = requests.get(f"{URL}/query", params={"query": q, "type": "csv"}, timeout=30)
r.raise_for_status()
return pd.read_csv(io.StringIO(r.text))
def backtest_ma(df: pd.DataFrame, fast=5, slow=20, fee=0.0003):
df = df.sort_values("ts").reset_index(drop=True)
df["ma_fast"] = df.close.rolling(fast).mean()
df["ma_slow"] = df.close.rolling(slow).mean()
df["pos"] = (df.ma_fast > df.ma_slow).shift(1).astype(int) # critical: shift(1)
df["ret"] = df.close.pct_change().fillna(0)
df["strat_ret"] = df.pos * df.ret - (df.pos != df.pos.shift(1)).abs() * fee
df["equity"] = (1 + df.strat_ret).cumprod()
return df
df = fetch_bars("600519.SS", "2026-09-01")
res = backtest_ma(df)
print(res.equity.iloc[-1], "final multiple; MDD:",
(res.equity / res.equity.cummax() - 1).min())
The shift(1) is the lifeblood of this pipeline: you only know the position to hold on bar t+1 after bar t closes. Signals must lag by one bar, or you have a look-ahead function and the equity curve is worthless.
4. Three details that quietly break backtests
① Bar-timestamp convention. SAMPLE BY emits the window’s start time, while several data vendors label bars with the window’s end. Unify the convention before aligning across sources, or every 1-minute bar is off by a minute and every trigger fires at the wrong time.
② The first bar is ragged. On a data gap, the first 1m bar may hold 30 seconds of volume and drag the mean down systematically. Common fixes: WHERE count() > N to drop ragged windows, or flag them with a count(*) in the same GROUP BY.
③ Don’t skip fees and slippage. The fee=0.0003 above is one-sided commission; a fast-turnover strategy needs a slippage term on top. The more optimistic your cost assumptions, the wider the gap to live trading — old advice, nobody fixes it.
5. Sizing the thing
QuestDB’s job here is the throughput: single-node ILP writes at millions of rows per second, and bar aggregation is a built-in SQL op — no intermediate data ships to Python. Rule of thumb: a day of ticks lands on disk at a few to a few dozen GB (Parquet cold), and resampling to 1m bars shrinks that by 500x or more. Python then fetches a full month of bars in a single request, milliseconds of transfer.
To go further, bolt on ASOF JOIN for fill-price matching (“the last traded price before my order time”) to simulate execution slippage bar by bar — that’s the subject of its own article.
Next steps
- Retention & hot/cold tiers:
TO PARQUET+ TTLs — see the compression & retention post. - Alerting & anomaly detection: a rolling z-score in one SQL statement.
- Point the bar table at Grafana and plot the equity curve directly.