σμ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 1 · DataFrames and expressions›Topic 1.2·~45 minIntermediate

Expressions

Skill positionModule 1 of 3 · Topic 2 of 3
1.2 Expressions
—Lab score— / 100Total XP—Streak—
Lecture0% read

3 min readCode examples: 4

  1. 01The idea in plain words
  2. 02Add columns and keep rows
  3. 03Choose per row with when/then
  4. 04What the tasks ask

The core idea of Polars fits in one sentence: you do not tell it how to compute a column, you describe the column, and it works out how. pl.col("close") / pl.col("open") - 1 is an object, an expression. Nothing is computed until you put it in a context such as select or filter, and then Polars runs it over the whole column in parallel across all your cores.

01

The idea in plain words

Where we are. Topic 1 read and inspected a frame. This topic is the vocabulary used by everything after it: grouping, windows, joins and time are all expressions in different contexts. It is also where Polars differs most from pandas, which would write a cell-by-cell loop or an apply where Polars writes one expression.

DefinitionExpression

A description of a computation on columns that Polars can run later, in parallel, over the whole column. It is built from pl.col, pl.lit, arithmetic and methods, and it only produces values when placed in a context such as select, with_columns or filter.

02

Add columns and keep rows

with_columns takes any number of expressions and adds each as a column; alias names the result. Because the expressions in one call are independent, Polars runs them side by side. filter takes a boolean expression and keeps the rows where it is true. Here .abs() is a method on the expression, so a big fall and a big rise both count as a big move.

main.pyPython
# Two new columns in one call: the day's range and its returnwide = with_range(df)print(wide.columns[-2:])print(wide.select(pl.col("range_pct").max().alias("widest range"), pl.col("return_pct").min().alias("worst day")).row(0))
['range_pct', 'return_pct']
(0.2732250486450573, -0.15722320825938052)
main.pyPython
# Days when the stock moved more than 10% from open to close, either waybig = big_moves(df, 0.10)print(big.height, "of", df.height, "days")print(big.select("symbol").to_series().value_counts().sort("symbol").rows())
50 of 33493 days
[('AAPL', 14), ('JPM', 31), ('XOM', 5)]
03

Choose per row with when/then

pl.when(condition).then(value).otherwise(other) is the expression form of if/else. It evaluates the condition for every row at once and picks a value per row, and extra .when(...).then(...) branches handle more cases. direction_label uses it to label up, down and flat days without a Python if. price_view shows select, which returns only the columns you build, in the order you list them.

main.pyPython
# up / down / flat labels, counted by labellabelled = direction_label(df)print(labelled["direction"].value_counts().sort("direction").rows())
[('down', 16112), ('flat', 193), ('up', 17188)]
main.pyPython
# A trimmed view: symbol, date, px and the typical priceview = price_view(df)print(view.columns)print(view.head(3))
['symbol', 'date', 'px', 'typical']
shape: (3, 4)
┌────────┬────────────┬──────────┬──────────┐
│ symbol ┆ date       ┆ px       ┆ typical  │
│ ---    ┆ ---        ┆ ---      ┆ ---      │
│ str    ┆ date       ┆ f64      ┆ f64      │
╞════════╪════════════╪══════════╪══════════╡
│ AAPL   ┆ 2000-01-03 ┆ 0.83826  ┆ 0.814089 │
│ AAPL   ┆ 2000-01-04 ┆ 0.76771  ┆ 0.784849 │
│ AAPL   ┆ 2000-01-05 ┆ 0.778895 ┆ 0.792829 │
└────────┴────────────┴──────────┴──────────┘
If you reach for a loop, look for an expression

map_elements and iter_rows run Python once per row and give up the parallel, compiled path, often by a factor of a hundred. Almost every column calculation has an expression form: arithmetic, comparisons, when/then, string and date methods. Topic 10 covers the rare cases that do not, but start by assuming one exists.

04

What the tasks ask

  1. 1
    `with_range` and `price_view`df.with_columns(expr.alias(...), ...) adds; df.select(expr, ...) builds a new frame.
  2. 2
    `big_moves`df.filter((pl.col("close") / pl.col("open") - 1).abs() > threshold).
  3. 3
    `direction_label`pl.when(cond).then(pl.lit("up")).when(cond2).then(pl.lit("down")).otherwise(pl.lit("flat")), aliased direction.

Key takeaways

  • Describe, do not loop An expression is applied to the whole column in parallel.
  • Four contexts select, with_columns, filter and when/then cover most column work.
  • Name your results alias makes the column readable. Next: groups and windows.
Quick check
Why is df.with_columns(pl.col("close") / pl.col("open") - 1) better than looping over the rows in Python?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • Add columns: with_range25 pts
  • Keep the big days: big_moves25 pts
  • Choose per row: direction_label25 pts
  • Pick and rename: price_view25 pts
Explorer · lab-2-1
▾ lab-2-1
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-2-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

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