σμ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.3·~45 minAdvanced

Streaming and larger-than-memory data

Skill positionModule 3 of 3 · Topic 3 of 5
3.3 Streaming and larger-than-memory data
—Lab score— / 100Total XP—Streak—
Lecture0% read

3 min readCode examples: 3

  1. 01The idea in plain words
  2. 02Write while you read
  3. 03Read only what the query needs
  4. 04When a step must go piece by piece
  5. 05What the tasks ask

Our five stocks fit in memory with room to spare, but the habits you build now decide what happens on fifty years of tick data. The question to ask of every step is how much of the file it has to hold at once. Polars lets you answer: a chunk, not the file.

01

The idea in plain words

Where we are. Topic 8 introduced the lazy API. This topic uses it on data that is bigger than you want in memory. Three tools: sink_parquet writes a lazy query to disk as it runs, scan_parquet reads only the columns and row groups the query needs, and slice lets you walk through a result in fixed-size chunks when a step really must be done piece by piece.

DefinitionLarger-than-memory

Data too big to hold in RAM at once. It can still be processed by reading it in pieces and keeping only a small running result, so the memory used depends on the size of a piece, not on the size of the data.

02

Write while you read

Collecting a query puts its whole result in memory. sink_parquet(path) is the lazy alternative: Polars runs the query and writes the result straight to the file in batches, so a result bigger than RAM is fine. It also converts: here five CSV files become a single Parquet file, which is smaller and much faster to read back.

main.pyPython
# Five CSV files into one Parquet file, written by sink_parquet without collecting anythingshutil.rmtree("lake", ignore_errors=True)os.makedirs("lake")rows = bars_to_parquet("data", SYMBOLS, "lake/bars.parquet")csv_mb = sum(os.path.getsize(f"data/{s}.csv") for s in SYMBOLS) / 1e6print(rows, "rows | CSV", round(csv_mb, 1), "MB -> Parquet", round(os.path.getsize("lake/bars.parquet") / 1e6, 1), "MB")
33493 rows | CSV 1.7 MB -> Parquet 0.7 MB
03

Read only what the query needs

scan_parquet keeps the file lazy and Parquet stores each column separately, so a query that touches three columns out of seven reads only those three. The yearly volume below never loads open, high, low or close. Combined with a filter on a sorted column, whole row groups are skipped as well, which is why Parquet beats CSV on big data.

main.pyPython
# Yearly volume from the Parquet file: only symbol, date and volume are readyearly = yearly_volume("lake/bars.parquet")print(yearly.filter(pl.col("symbol") == "KO").head(3).rows())print("rows in the answer:", yearly.height, "from", rows, "rows in the file")
[('KO', 2000, 3620485497), ('KO', 2001, 3269679676), ('KO', 2002, 3921594525)]
rows in the answer: 135 from 33493 rows in the file
04

When a step must go piece by piece

Not everything can be written as one lazy query: you may call a library that wants a real DataFrame, or train on batches. lazy.slice(offset, length).collect() gives you rows offset to offset + length, one chunk at a time, and you keep only a small running total. The loop below counts rows per symbol while holding at most chunk_rows rows. split_by_symbol goes the other way and cuts one file into many with a lazy filter and sink_parquet for each piece.

main.pyPython
# Count rows per symbol in chunks of 10,000, then split the file into one file per symbolprint(symbol_counts_chunked("lake/bars.parquet", 10_000))written = split_by_symbol("lake/bars.parquet", "lake/by_symbol")print(written, "->", sorted(os.listdir("lake/by_symbol"))[:2], "...")
{'AAPL': 6699, 'JNJ': 6699, 'JPM': 6698, 'KO': 6699, 'XOM': 6698}
['AAPL', 'JNJ', 'JPM', 'KO', 'XOM'] -> ['AAPL.parquet', 'JNJ.parquet'] ...
Choose the chunk size on purpose

A tiny chunk makes the loop slow, because every piece pays a fixed cost to start. A huge one defeats the purpose. Pick the largest chunk that comfortably fits in memory, and prefer one lazy query or a sink_ to a hand-written loop whenever the work can be written that way.

05

What the tasks ask

  1. 1
    `bars_to_parquet` and `yearly_volume`Scans with pl.lit(s), pl.concat, sink_parquet, then count with scan_parquet; scan_parquet, select, group_by on symbol and dt.year(), sum, sort, collect().
  2. 2
    `symbol_counts_chunked` and `split_by_symbol`Row count, then range(0, total, chunk_rows) with slice(offset, chunk_rows).collect() and a running dict; unique symbols, then a lazy filter and sink_parquet for each.

Key takeaways

  • Memory follows the chunk Hold a piece and a small running result, never the whole file.
  • Sink and scan sink_parquet writes as it runs and scan_parquet reads only what the query touches.
  • Slice when you must slice(offset, length) walks a lazy query in chunks. Next: custom functions beyond expressions.
Quick check
A 40 GB CSV does not fit in memory. You need the total volume per symbol. Which approach keeps memory small?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • Write while you read: bars_to_parquet25 pts
  • Read only what you need: yearly_volume25 pts
  • Walk through it in chunks: symbol_counts_chunked25 pts
  • Split a big file: split_by_symbol25 pts
Explorer · lab-9-1
▾ lab-9-1
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-9-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

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