A trade prints at 10:50:03. The quote it should be judged against was posted at 10:48:17, the last time anyone changed it. No quote has exactly the trade's timestamp, so an ordinary join finds nothing. You need "the latest quote at or before this moment", for every trade, and DuckDB has a join built for exactly that.
The idea in plain words
Where we are. The SQL skill showed the as-of idea with a range join on daily data. Here it is DuckDB's own ASOF JOIN, on ticks, next to its pandas twin merge_asof, so you can see both answer the same question and where each is stricter. The next topic is DuckDB's friendlier SQL.
A quote that was the latest one for its symbol but had not been updated for a long time when the trade happened. An as-of join always finds a quote if one exists; how old it is must be checked separately.
Why equality finds nothing
# A synthetic day of quotes and trades for two symbolsprint(len(quotes), "quotes,", len(trades), "trades")print(con.sql("SELECT * FROM quotes WHERE symbol = 'AAA' ORDER BY ts LIMIT 3"))print(con.sql("SELECT * FROM trades WHERE symbol = 'AAA' ORDER BY ts LIMIT 2"))
60 quotes, 25 trades ┌─────────────────────┬─────────┬────────┬────────┐ │ ts │ symbol │ bid │ ask │ │ timestamp │ varchar │ double │ double │ ├─────────────────────┼─────────┼────────┼────────┤ │ 2026-08-21 09:55:26 │ AAA │ 19.5 │ 19.54 │ │ 2026-08-21 09:56:22 │ AAA │ 19.48 │ 19.52 │ │ 2026-08-21 10:02:33 │ AAA │ 19.3 │ 19.34 │ └─────────────────────┴─────────┴────────┴────────┘ ┌─────────────────────┬─────────┬────────┬───────┐ │ ts │ symbol │ price │ qty │ │ timestamp │ varchar │ double │ int64 │ ├─────────────────────┼─────────┼────────┼───────┤ │ 2026-08-21 10:02:11 │ AAA │ 19.35 │ 200 │ │ 2026-08-21 10:07:33 │ AAA │ 19.22 │ 400 │ └─────────────────────┴─────────┴────────┴───────┘
# An equality join on the timestamp matches almost no trades; ASOF matches the ones with an earlier quoteprint(con.sql("SELECT count(*) AS exact_matches FROM trades t JOIN quotes q ON q.symbol = t.symbol AND q.ts = t.ts").fetchall())print(len(asof_quotes(con)), "of", len(trades), "trades have a quote at or before them")
[(0,)] 25 of 25 trades have a quote at or before them
ASOF JOIN, then check the age
In the ON clause put the equality (symbol) first and the time inequality last: the join matches per symbol, then picks the latest q.ts with t.ts >= q.ts. An inner ASOF JOIN drops a trade with no earlier quote; ASOF LEFT JOIN keeps it with NULLs, which is what you want to find trades priced with no quote or with an old one.
# Each trade with the quote in force, and how old that quote wasprint(con.sql(""" SELECT t.ts, t.symbol, t.price, q.bid, q.ask, epoch(t.ts - q.ts) AS age_s FROM trades t ASOF LEFT JOIN quotes q ON t.symbol = q.symbol AND t.ts >= q.ts ORDER BY t.ts LIMIT 5"""))print(len(stale_trades(con, 600)), "trades on a quote older than 10 minutes or on none")
┌─────────────────────┬─────────┬────────┬────────┬────────┬────────┐ │ ts │ symbol │ price │ bid │ ask │ age_s │ │ timestamp │ varchar │ double │ double │ double │ double │ ├─────────────────────┼─────────┼────────┼────────┼────────┼────────┤ │ 2026-08-21 10:02:11 │ AAA │ 19.35 │ 19.48 │ 19.52 │ 349.0 │ │ 2026-08-21 10:07:33 │ AAA │ 19.22 │ 19.25 │ 19.29 │ 196.0 │ │ 2026-08-21 10:14:00 │ AAA │ 19.0 │ 19.15 │ 19.19 │ 351.0 │ │ 2026-08-21 10:38:32 │ AAA │ 18.45 │ 18.8 │ 18.84 │ 1028.0 │ │ 2026-08-21 11:00:05 │ BBB │ 26.1 │ 26.26 │ 26.3 │ 679.0 │ └─────────────────────┴─────────┴────────┴────────┴────────┴────────┘ 12 trades on a quote older than 10 minutes or on none
The same join in pandas
pd.merge_asof(trades, quotes, on="ts", by="symbol") is the twin. It needs both frames sorted by the time key and it raises an error if they are not, where SQL sorts for you. Its default direction is backward, like the SQL join, and direction="forward" or "nearest" would answer a different question: using a quote that came after the trade is look-ahead.
# The pandas join agrees with the DuckDB one; an unsorted frame is refusedprint(asof_pandas(trades_df, quotes_df) == asof_quotes(con))try: pd.merge_asof(trades_df.iloc[::-1], quotes_df, on="ts", by="symbol")except ValueError as error: print("ValueError:", error)
True ValueError: left keys must be sorted
# Average slippage against the mid price, per symbol, in basis pointsprint({symbol: round(value, 1) for symbol, value in slippage_bps(con).items()})
{'AAA': -31.4, 'BBB': 12.9}A quote stamped at the same second as the trade counts as in force (>=). If two quotes of one symbol share a timestamp, an as-of join picks one of them without saying which, in both DuckDB and pandas. Give quotes a unique key, such as a sequence number, if your data can repeat a timestamp.
What the tasks ask
- 1`asof_quotes` and `stale_trades`An inner
ASOF JOINfor the first; anASOF LEFT JOINand an age test for the second. - 2`asof_pandas`
pd.merge_asofwithby="symbol", sorted by time, looking backward. - 3`slippage_bps`An
ASOF JOINfollowed by aGROUP BYsymbol and an average of price against the mid.
ASOF JOIN attaches to a trade a quote that is 40 minutes old. What does that tell you?Lab · what's graded
4 tasks · 100 ptsASOF JOIN:asof_quotes25 pts- Stale or missing quotes:
stale_trades25 pts - The pandas twin:
asof_pandas25 pts - Slippage per symbol:
slippage_bps25 pts