σμ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 2 · Working with Python›Topic 2.1·~40 minIntermediate

Python integration with pandas Polars and Arrow

Skill positionModule 2 of 3 · Topic 1 of 2
2.1 Python integration with pandas Polars and Arrow
—Lab score— / 100Total XP—Streak—
Lecture0% read

3 min readCode examples: 4

  1. 01The idea in plain words
  2. 02In from pandas, out as Arrow
  3. 03Polars in, Polars out
  4. 04Python inside SQL
  5. 05Streaming a result
  6. 06What the tasks ask

A research notebook mixes tools: pandas for a quick look, Polars for a fast transform, Arrow to hand data to another process, SQL for the heavy aggregation. Moving a table between them by writing and re-reading files wastes time. DuckDB reads each of them where they sit and returns the answer in whichever form you ask for.

01

The idea in plain words

Where we are. Topics 1 to 4 used DuckDB from Python with plain results. This one is about the borders: getting data in from pandas, Polars and Arrow, getting results out in their forms, calling Python from SQL, and streaming a big result. The next topic keeps a database on disk.

DefinitionZero-copy

Sharing data between two libraries by pointing both at the same memory instead of duplicating it. DuckDB, Arrow and Polars use compatible columnar layouts, so many hand-offs between them copy nothing, or only small pieces.

02

In from pandas, out as Arrow

main.pyPython
# A pandas DataFrame in, a pyarrow Table outframe = load_frame("KO")table = frame_to_arrow(frame, "SELECT date, close FROM frame ORDER BY date DESC LIMIT 3")print(type(table).__name__, table.schema.names, table.num_rows)print(table.to_pylist())
Table ['date', 'close'] 3
[{'date': datetime.date(2026, 8, 21), 'close': 91.1}, {'date': datetime.date(2026, 8, 20), 'close': 90.5}, {'date': datetime.date(2026, 8, 19), 'close': 90.35}]
03

Polars in, Polars out

A Polars DataFrame is found by variable name just like a pandas one, and .pl() returns the result as Polars. Writing the grouping in SQL here is a choice: it lets one query combine a Polars frame with a pandas frame, an Arrow table and a file, which none of those libraries can do alone.

main.pyPython
# Two Polars frames stacked, summarised in SQL, returned as a Polars frameboth = pl.concat([load_polars("KO"), load_polars("JNJ")])print(polars_summary(both))
shape: (2, 3)
┌────────┬──────┬────────────┐
│ symbol ┆ days ┆ mean_close │
│ ---    ┆ ---  ┆ ---        │
│ str    ┆ i64  ┆ f64        │
╞════════╪══════╪════════════╡
│ JNJ    ┆ 6699 ┆ 87.439377  │
│ KO     ┆ 6699 ┆ 33.39018   │
└────────┴──────┴────────────┘
04

Python inside SQL

create_function registers an ordinary Python function under a SQL name, with its argument and return types. SQL then calls it row by row. It is flexible but slower than a built-in expression, so use it for logic SQL cannot express and keep simple arithmetic in SQL. A NULL argument gives a NULL result without calling your function.

main.pyPython
# SQL calls the Python function by name, row by rowadd_bps_function(con, "move_bps")print(con.sql("SELECT date, round(move_bps(close, open), 1) AS move_bps FROM bars WHERE symbol = 'KO' ORDER BY date DESC LIMIT 3"))print(con.sql("SELECT move_bps(NULL, 10.0) AS null_in"))
┌────────────┬──────────┐
│    date    │ move_bps │
│    date    │  double  │
├────────────┼──────────┤
│ 2026-08-21 │     27.5 │
│ 2026-08-20 │     35.5 │
│ 2026-08-19 │    198.7 │
└────────────┴──────────┘

┌─────────┐
│ null_in │
│ double  │
├─────────┤
│    NULL │
└─────────┘
05

Streaming a result

fetchall() and .df() build the whole result in memory. to_arrow_reader(n) returns an iterator of Arrow batches of up to n rows, produced as you ask for them, so you can total, write out or discard each batch and never hold the table. It is how a result bigger than memory is processed.

main.pyPython
# 33,493 rows read in batches of 10,000, one at a timeprint(batch_sizes(con, "SELECT * FROM bars", 10000))
[10000, 10000, 10000, 3493]
Conversions can copy, and names are looked up

.df() on a large result builds a full pandas copy, and a pandas column of Python objects (not NumPy numbers) converts slowly. A DataFrame found by variable name is whichever object has that name in the calling code at that moment, so rename carefully and avoid two DataFrames sharing a name in different scopes.

06

What the tasks ask

  1. 1
    `frame_to_arrow` and `polars_summary`Query a DataFrame by name and return the result as Arrow or Polars.
  2. 2
    `add_bps_function`con.create_function with DOUBLE types, so SQL can call your Python.
  3. 3
    `batch_sizes`to_arrow_reader(n) and a loop over the batches, without fetchall().

Key takeaways

  • Data stays where it is pandas, Polars and Arrow objects are queried by name, with little or no copying.
  • Choose the output form .df(), .pl(), .to_arrow_table() or a streaming reader, whichever the next step wants.
  • Python in SQL is a tool, not a default Use it for logic SQL cannot express. Next: persisted databases.
Quick check
A query returns 40 million rows and you only need their total. Which approach keeps memory low?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • pandas in, Arrow out: frame_to_arrow25 pts
  • Polars in, Polars out: polars_summary25 pts
  • Python inside SQL: add_bps_function25 pts
  • Stream a big result: batch_sizes25 pts
Explorer · lab-5-1
▾ lab-5-1
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-5-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

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