σμ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 3 · Interop and the query engine›Topic 3.2·~45 minIntermediate

The lazy API and query plans

Skill positionModule 3 of 3 · Topic 2 of 5
3.2 The lazy API and query plans
—Lab score— / 100Total XP—Streak—
Lecture0% read

3 min readCode examples: 4

  1. 01The idea in plain words
  2. 02A recipe, not data
  3. 03Read the plan
  4. 04One query over many files
  5. 05What the tasks ask

An eager query does each step the moment you write it. A lazy query only writes the steps down, then looks at the whole list, throws away the work it does not need, and runs what is left once. On big files that difference is the one between waiting and not waiting.

01

The idea in plain words

Where we are. Topics 1 to 7 used the eager API. Here the same operations are written against a LazyFrame. We scan a file without reading it, build a query, read the plan the optimizer made, and collect. The two payoffs are reading fewer columns and filtering rows while reading, and both show up in the plan text.

DefinitionLazy evaluation

A way of running a query in which each step only adds to a plan, and nothing is computed until you ask for the result. Because the whole plan is known first, the engine can reorder steps and skip data that the result never needs.

02

A recipe, not data

pl.scan_csv(path) returns a LazyFrame at once, without touching the file. You can still ask what the columns will be with collect_schema(), and you chain filter, select, group_by exactly as before. Each call returns another LazyFrame. Only collect() reads the file and returns a real DataFrame.

main.pyPython
# Scan KO: a LazyFrame whose columns are known, with nothing read yetlazy = scan_bars(folder, "KO")print(type(lazy).__name__, lazy.collect_schema().names())print("after a filter it is still", type(lazy.filter(pl.col("volume") > 0)).__name__)print("collect gives", type(lazy.collect()).__name__, "with", lazy.collect().height, "rows")
LazyFrame ['symbol', 'date', 'open', 'high', 'low', 'close', 'volume']
after a filter it is still LazyFrame
collect gives DataFrame with 6699 rows
03

Read the plan

explain() prints the plan Polars will run. Compare what we wrote with what it runs: we scanned the whole file, filtered, then selected one column, but the plan shows PROJECT 2/6 COLUMNS, so only two of the six columns are read, and the date test sits as a SELECTION inside the scan, so rows are dropped while reading. The optimizer did both on its own. explain(optimized=False) shows the plan as written.

main.pyPython
# The query we wrote, and the lines of the optimized plan that show what Polars skipsquery = pl.scan_csv("data/KO.csv", try_parse_dates=True).filter(pl.col("date") >= date(2020, 1, 1)).select(pl.col("close").mean())for line in query.explain().splitlines():    if "PROJECT" in line or "SELECTION" in line or "SCAN" in line:        print(line.strip())print("mean close since 2020:", round(mean_close_since(folder, "KO", date(2020, 1, 1)), 3))
Csv SCAN [data/KO.csv]
PROJECT 2/6 COLUMNS
SELECTION: col("date") >= 2020-01-01
mean close since 2020: 60.542
04

One query over many files

Scans can be stacked with pl.concat, still lazily, so five files become one query: filter, group, sort, and a single collect() at the end. If you must run several different queries, hand them all to pl.collect_all([...]): Polars runs them in parallel and computes shared parts, such as a common scan, once.

main.pyPython
# One lazy query over all five files, collected once at the endsymbols = ["AAPL", "JPM", "XOM", "JNJ", "KO"]summary = summary_lazy(folder, symbols, date(2025, 1, 1))print(summary.select("symbol", "bars", pl.col("mean_close").round(2), "max_volume").rows())
[('AAPL', 410, 251.74, 261775450), ('JNJ', 410, 197.08, 25620954), ('JPM', 410, 294.31, 27170689), ('KO', 410, 73.08, 53357493), ('XOM', 410, 125.89, 53942143)]
main.pyPython
# Two different queries, collected togetherlatest, earliest = collect_many([scan_bars(folder, "KO").tail(1), scan_bars(folder, "KO").head(1)])print("first close", earliest["close"][0], "| last close", latest["close"][0])
first close 19.4546 | last close 91.1
Stay lazy until the end

The moment you call collect() or read_csv, the data is in memory and the optimizer has nothing left to optimize. Build the whole query first, collect once, and collect only what you need: filter and select before the collect, never after. Use eager frames for small results you want to look at.

05

What the tasks ask

  1. 1
    `scan_bars` and `mean_close_since`pl.scan_csv(..., try_parse_dates=True), select with pl.lit(symbol), no collect; then filter, select(mean), collect().item().
  2. 2
    `summary_lazy` and `collect_many`A list of scans with with_columns(pl.lit(s)), pl.concat, filter, group_by("symbol").agg(...), sort, one collect(); pl.collect_all(frames).

Key takeaways

  • Scan, don't read scan_csv returns a recipe; only collect() reads and computes.
  • The plan shows the savings explain() reports fewer columns read and the filter applied inside the scan.
  • Collect once Build the whole query, then collect() or collect_all. Next: streaming and larger-than-memory data.
Quick check
You call pl.read_csv("big.csv"), then .filter(...) and .select("close"). Why is pl.scan_csv("big.csv") with the same two calls and a collect() usually faster?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • A recipe, not data: scan_bars25 pts
  • Filter before reading: mean_close_since25 pts
  • One query, many files: summary_lazy25 pts
  • Collect together: collect_many25 pts
Explorer · lab-8-1
▾ lab-8-1
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-8-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

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