σμ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
  • 日本語
  • 中文
Polars skill›Module 2 · Joins, time and windows›Topic 2.1·~50 minIntermediate

Joins and as-of joins

Skill positionModule 2 of 3 · Topic 1 of 3
2.1 Joins and as-of joins
—Lab score— / 100Total XP—Streak—
Lecture0% read

3 min readCode examples: 3

  1. 01The idea in plain words
  2. 02Attach a column, and find what has no match
  3. 03Match to the latest earlier row
  4. 04A tolerance for stale matches
  5. 05What the tasks ask

Prices tell you what happened; fundamentals tell you why it might matter. Putting them in one table needs a join, and the join that most often goes wrong in quant work is the one on time. A price on 3 March should carry the revenue the market knew on 3 March, not the revenue reported on 20 March. The as-of join exists to make that match by date, and getting it right is what keeps a backtest from peeking at the future.

01

The idea in plain words

Where we are. Topic 3 summarised within one table. Here two tables meet. The first half is ordinary key joins: attach a column, find what has no match. The second half is the time join. The quarterly fundamentals come from the same dataset as in the SQL skill, where the as-of idea was taught in portable form; join_asof is the Polars operator for it.

DefinitionAs-of join

A join that matches each row of the left table to the latest row of the right table at or before its time, instead of an exactly equal key. It needs both tables sorted by time, and an optional tolerance can refuse matches that are too old.

02

Attach a column, and find what has no match

A left join keeps every row of the left table and fills the new columns with nulls where nothing matched, so the table never silently shrinks. An inner join would drop those rows without a word. An anti join answers the audit question directly: which symbols in my prices have no sector? Run it after any join to see what you lost or never had.

main.pyPython
# Left join: KO has no sector in the lookup, so its sector is null; the anti join names the gapjoined = join_sector(bars, sectors)print(joined.group_by("symbol").agg(pl.col("sector").first()).sort("symbol").rows())print("rows kept:", joined.height, "of", bars.height)print("no sector for:", symbols_without_sector(bars, sectors))
[('AAPL', 'Tech'), ('JNJ', 'Health'), ('JPM', 'Banks'), ('KO', None), ('XOM', 'Energy')]
rows kept: 33493 of 33493
no sector for: ['KO']
03

Match to the latest earlier row

Each filing becomes visible on its filed date, not on the quarter's end. latest_filing sorts both frames by time, then join_asof walks them together: for every price it takes the newest filing of the same symbol on or before that day, by="symbol" keeping the symbols apart. Before a symbol's first filing the revenue is null, which is correct, because nothing was known yet.

main.pyPython
# KO around its first filing in the data (24 April 2019): null before, then the report that was publicko = latest_filing(bars, filings).filter((pl.col("symbol") == "KO") & (pl.col("date") >= pl.date(2019, 4, 22)) & (pl.col("date") <= pl.date(2019, 4, 26)))for row in ko.rows():    print(row)
('KO', datetime.date(2019, 4, 22), 42.1946, datetime.date(2019, 2, 21), 7058000000)
('KO', datetime.date(2019, 4, 23), 42.915, datetime.date(2019, 2, 21), 7058000000)
('KO', datetime.date(2019, 4, 24), 42.7105, datetime.date(2019, 2, 21), 7058000000)
('KO', datetime.date(2019, 4, 25), 42.5862, datetime.date(2019, 4, 25), 8020000000)
('KO', datetime.date(2019, 4, 26), 42.96, datetime.date(2019, 4, 25), 8020000000)
04

A tolerance for stale matches

The latest filing can be a year old. With tolerance=timedelta(days=max_days) the join refuses a match older than that and leaves nulls instead. recent_filing makes that choice explicit: a revenue figure from three quarters ago should not be presented as current. The number of nulls that appear is itself information about how complete the fundamentals are.

main.pyPython
# How many price rows have no filing at all, and how many have none within 100 daysanywhere = latest_filing(bars, filings)["revenue"].null_count()recent = recent_filing(bars, filings, 100)["revenue"].null_count()print("no filing yet:", anywhere, "| none in the last 100 days:", recent, "| of", bars.height, "rows")
no filing yet: 21903 | none in the last 100 days: 25684 | of 33493 rows
Join on the date it was known, not the date it is about

A quarter ends on one date and the report comes out weeks later. Joining on the period end hands the model revenue that nobody had yet, which flatters every backtest. Always join fundamentals on the filing date. Check by looking at a row just before and just after a filing: the number must change on the filing day, not earlier.

05

What the tasks ask

  1. 1
    `join_sector` and `symbols_without_sector`bars.join(sectors, on="symbol", how="left"); how="anti", then distinct symbols sorted.
  2. 2
    `latest_filing` and `recent_filing`Sort both frames by time, then join_asof(right, left_on="date", right_on="filed", by="symbol", strategy="backward"); add tolerance=timedelta(days=max_days); sort by symbol and date.

Key takeaways

  • Left keeps, inner drops Use a left join to keep every row, and an anti join to audit the gaps.
  • As-of means latest earlier Sort both sides by time and match with by and backward.
  • Use the date it was known The filing date, never the period end. Next: dates and dynamic grouping.
Quick check
A model joins quarterly revenue to daily prices on the quarter's end date and shows great results. What is the most likely problem?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • Attach a column: join_sector25 pts
  • Who has no match: symbols_without_sector25 pts
  • Match to the latest earlier row: latest_filing25 pts
  • Only if recent enough: recent_filing25 pts
Explorer · lab-4-1
▾ lab-4-1
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-4-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-4-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