σμ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.4·~40 minAdvanced

Custom functions beyond expressions

Skill positionModule 3 of 3 · Topic 4 of 5
3.4 Custom functions beyond expressions
—Lab score— / 100Total XP—Streak—
Lecture0% read

3 min readCode examples: 3

  1. 01The idea in plain words
  2. 02Your own expression, at full speed
  3. 03Python on every value: the slow rung
  4. 04Python once per group, and your own namespace
  5. 05What the tasks ask

Polars is fast because it runs expressions in compiled code on whole columns. The moment you hand it a Python function, that speed is traded for flexibility. Knowing the ladder of options, and stopping on the lowest rung that does the job, is what keeps a pipeline fast.

01

The idea in plain words

Where we are. Topics 1 to 9 stayed with built-in expressions. This one is about the four ways to go beyond them. Compose your own expression in a function, which costs nothing. Call Python on every value with map_elements, which is the slow last resort. Aggregate to lists and use plain Python once per group. And register a namespace so that your own expressions read like built-ins.

DefinitionUser-defined function

Your own Python function used inside a query. Polars cannot look inside it or optimize it, and calls it once per value or group from compiled code, which is why it is slower than a built-in expression that does the same work.

02

Your own expression, at full speed

An expression is a value in Python: you can build it in a function and return it. zscore_expr("close", 20) is nothing but a recipe made of rolling_mean and rolling_std, so Polars optimizes and runs it like any built-in. The caller adds .over("symbol") and .alias(...), which is why the function returns an expression and not a frame. This is the first thing to reach for, and it covers most reuse.

main.pyPython
# A reusable expression: the caller decides the window per symbol and the nameexpr = zscore_expr("close", 20)print(type(expr).__name__)z = bars.with_columns(expr.over("symbol").alias("z20"))latest = z.group_by("symbol").agg(pl.col("z20").last()).sort("symbol")print([(s, round(v, 2)) for s, v in latest.rows()])
Expr
[('AAPL', -0.41), ('JNJ', 1.44), ('JPM', -1.04), ('KO', 2.05), ('XOM', 1.5)]
03

Python on every value: the slow rung

map_elements(fn, return_dtype=...) calls your function for each value and collects the results. It can do anything Python can do, such as call a library or run a branch of if statements, at the price of a Python call per value, often fifty to a hundred times slower. Always say return_dtype, so Polars does not have to guess, and check first whether a built-in does the same, as with the square root below.

main.pyPython
# The same square root by Python function and by built-in expression: the same numbers, very different costby_python = apply_python(bars, "close", lambda x: x ** 0.5).get_column("close_py")built_in = bars.select(pl.col("close").sqrt()).get_column("close")print("same to 1e-9:", max(abs(a - b) for a, b in zip(by_python, built_in)) < 1e-9, "| values:", by_python.len())
same to 1e-9: True | values: 33493
04

Python once per group, and your own namespace

Some logic is naturally sequential, such as the longest run of rising days: each step depends on the one before. Aggregate each symbol's closes into a list with group_by(...).agg(pl.col("close")), and loop over those few lists in plain Python. That is five Python loops instead of thirty-three thousand calls. When you have an expression you use everywhere, pl.api.register_expr_namespace("qc") on a small class makes it callable as pl.col("close").qc.drawdown(), which reads exactly like a built-in and is still fully optimized, because it only composes expressions.

main.pyPython
# Python once per symbol on aggregated lists, then a namespace that reads like a built-inprint(longest_up_streaks(bars).rows())register_namespace("qc")worst = bars.select(pl.col("close").qc.drawdown().over("symbol").alias("dd")).get_column("dd").min()print("deepest drawdown of any stock:", round(worst, 3))
[('AAPL', 12), ('JNJ', 13), ('JPM', 10), ('KO', 10), ('XOM', 11)]
deepest drawdown of any stock: -0.818
Climb only as high as you must

Ask in this order: can built-in expressions do it? Can I compose them in a function? Does the logic work on one list per group? Only then use map_elements. Each rung up costs speed, and a Python function is also invisible to the optimizer, so it cannot be pushed down into a scan.

05

What the tasks ask

  1. 1
    `zscore_expr` and `apply_python`Return (col - col.rolling_mean(w)) / col.rolling_std(w) as an expression; with_columns(pl.col(name).map_elements(fn, return_dtype=pl.Float64).alias(f"{name}_py")).
  2. 2
    `longest_up_streaks` and `register_namespace`group_by("symbol", maintain_order=True).agg(pl.col("close")), a plain loop per list, a frame of results; @pl.api.register_expr_namespace(name) on a class that keeps self._expr.

Key takeaways

  • Compose before you call A function that returns an expression keeps full speed and optimization.
  • `map_elements` is the last rung One Python call per value; always give return_dtype.
  • Namespaces make it read like Polars register_expr_namespace adds your methods to every expression. Next: the capstone, a monthly bar builder.
Quick check
You need the square root of a column. Which is best?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • Your own expression: zscore_expr25 pts
  • Python on every value: apply_python25 pts
  • Python on aggregated lists: longest_up_streaks25 pts
  • A namespace of your own: register_namespace25 pts
Explorer · lab-10-1
▾ lab-10-1
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-10-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

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