σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
DuckDB skill›Module 1 · Querying data in place›Topic 1.3·~45 minIntermediate

ASOF JOIN and its pandas twin

Skill positionModule 1 of 3 · Topic 3 of 4
1.3 ASOF JOIN and its pandas twin
—Lab score— / 100Total XP—Streak—
Lecture0% read

3 min readCode examples: 5

  1. 01The idea in plain words
  2. 02Why equality finds nothing
  3. 03ASOF JOIN, then check the age
  4. 04The same join in pandas
  5. 05What the tasks ask

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.

01

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.

DefinitionStale quote

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.

02

Why equality finds nothing

main.pyPython
# 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 │
└─────────────────────┴─────────┴────────┴───────┘
main.pyPython
# 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
03

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.

main.pyPython
# 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
04

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.

main.pyPython
# 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
main.pyPython
# 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}
Ties and duplicates

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.

05

What the tasks ask

  1. 1
    `asof_quotes` and `stale_trades`An inner ASOF JOIN for the first; an ASOF LEFT JOIN and an age test for the second.
  2. 2
    `asof_pandas`pd.merge_asof with by="symbol", sorted by time, looking backward.
  3. 3
    `slippage_bps`An ASOF JOIN followed by a GROUP BY symbol and an average of price against the mid.

Key takeaways

  • Match on the latest, not the equal ASOF JOIN takes the latest row at or before each time, per symbol.
  • Backward only Matching a later quote is look-ahead; keep pandas on backward.
  • Matching is not freshness Check a quote's age separately, and use LEFT to see trades with none. Next: friendly SQL.
Quick check
ASOF JOIN attaches to a trade a quote that is 40 minutes old. What does that tell you?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • ASOF JOIN: asof_quotes25 pts
  • Stale or missing quotes: stale_trades25 pts
  • The pandas twin: asof_pandas25 pts
  • Slippage per symbol: slippage_bps25 pts
Explorer · lab-3-1
▾ lab-3-1
…
bash · in-browser
learner@quantcraft:~/lab-3-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-3-1 goes back to the starter files and the terminal is cleared. Your current solution will be lost — this can't be undone.

Will be reset
  • main.py → starter code
  • Terminal history and test output
  • Unsubmitted changes
Will be kept
  • Best lab score
  • Your XP and streak
  • Lecture progress and notes