一笔成交在 10:50:03 打印。用来评判它的报价是在 10:48:17 发出的,那是最后一次有人改动它。没有哪条报价的时间戳恰好等于成交时间,所以普通连接什么也找不到。你需要对每笔成交取“此刻或之前的最新一条报价”,而 DuckDB 有专为此打造的连接。
用通俗的话说这个想法
我们在哪里。 SQL 技能用日线数据上的区间连接展示了 as-of 的思想。这里是 DuckDB 自己的 ASOF JOIN,作用于逐笔数据,并与 pandas 的对应物 merge_asof 并排,看它们如何回答同一个问题,以及各自在哪里更严格。下一个主题是 DuckDB 更友好的 SQL。
对其代码而言是最新的一条、但在成交发生时已很久没有更新的报价。只要存在报价,as-of 连接总能找到它;它有多旧要另外检查。
为什么相等连接什么也找不到
# 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,再检查时效
在 ON 子句里先写相等条件(symbol),最后写时间不等式:连接按代码匹配,再用 t.ts >= q.ts 选出最新的 q.ts。内连接的 ASOF JOIN 会丢掉没有更早报价的成交;ASOF LEFT JOIN 则用 NULL 保留它,要找出没有报价或报价过旧的成交就需要它。
# 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
pandas 中的同一个连接
pd.merge_asof(trades, quotes, on="ts", by="symbol") 就是对应物。它要求两个 DataFrame 都按时间键排序,否则报错,而 SQL 会替你排序。它默认的方向是向后,与 SQL 连接一致,direction="forward" 或 "nearest" 回答的是另一个问题:用成交之后才出现的报价就是前视。
# 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}与成交同一秒的报价算作有效(>=)。如果同一代码的两条报价时间戳相同,as-of 连接会在 DuckDB 和 pandas 中悄悄选其一,不告诉你选了哪个。若数据可能出现重复时间戳,请给报价加一个唯一键,例如序列号。
任务要求
- 1`asof_quotes` 与 `stale_trades`第一个用内连接
ASOF JOIN;第二个用ASOF LEFT JOIN加时效判断。 - 2`asof_pandas`
pd.merge_asof配合by="symbol",按时间排序,向后匹配。 - 3`slippage_bps`先
ASOF JOIN,再按代码GROUP BY,求价格相对中间价的平均值。
ASOF JOIN 给一笔成交配上了 40 分钟前的报价。这说明什么?实验:评分内容
4 个任务 · 100 分ASOF JOIN:asof_quotes25 分- 过期或缺失的报价:
stale_trades25 分 - pandas 对应:
asof_pandas25 分 - 按代码的滑点:
slippage_bps25 分