σμ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.3·~50 minIntermediate

Group by and window expressions

Skill positionModule 1 of 3 · Topic 3 of 3
1.3 Group by and window expressions
—Lab score— / 100Total XP—Streak—
Lecture0% read

3 min readCode examples: 4

  1. 01The idea in plain words
  2. 02Collapse each group to a row
  3. 03Keep every row with .over()
  4. 04What the tasks ask

Almost every question about prices is a question about groups: total volume per symbol, the best day of each stock, how today compares with that stock's own history. Polars has two tools for them, and the difference is one the tool names hide. Aggregation turns each group into one row. A window expression computes inside the group but keeps every row, so the result lines up with the original table and can be added as a column.

01

The idea in plain words

Where we are. Topic 2 gave the vocabulary of expressions. This topic adds the second axis: computing per group. The SQL skill covered the same two ideas as GROUP BY and window functions with OVER; here the names are group_by().agg() and .over(). Joins, time and rolling windows build on it.

DefinitionWindow expression

An expression followed by .over("key"), computed separately inside each group but returned for every row, in the original order. It is how a value is compared with its own group, such as a share of the group total or a rank within it.

02

Collapse each group to a row

group_by("symbol").agg(...) takes any number of expressions and runs each over every group, in parallel. pl.len() counts the rows of the group. The groups come out in no promised order, so a final sort makes the table reproducible. For first and last values, remember that they mean by position: first_last_close sorts by date before grouping so that "first" means earliest.

main.pyPython
# One row per symbol: total volume, mean close, number of daysprint(volume_by_symbol(df))
shape: (5, 4)
┌────────┬───────────────┬────────────┬──────┐
│ symbol ┆ total_volume  ┆ mean_close ┆ days │
│ ---    ┆ ---           ┆ ---        ┆ ---  │
│ str    ┆ i64           ┆ f64        ┆ u32  │
╞════════╪═══════════════╪════════════╪══════╡
│ AAPL   ┆ 2863818765894 ┆ 53.962251  ┆ 6699 │
│ JNJ    ┆ 76321726041   ┆ 87.439377  ┆ 6699 │
│ JPM    ┆ 163036003862  ┆ 76.857367  ┆ 6698 │
│ KO     ┆ 127779316463  ┆ 33.39018   ┆ 6699 │
│ XOM    ┆ 167184796142  ┆ 57.659943  ┆ 6698 │
└────────┴───────────────┴────────────┴──────┘
main.pyPython
# The first and last close of each stock by datefor symbol, first, last in first_last_close(df).rows():    print(f"{symbol:5} {first:>8.2f} -> {last:>8.2f}")
AAPL      0.84 ->   309.35
JNJ      32.12 ->   270.24
JPM      33.93 ->   351.58
KO       19.45 ->    91.10
XOM      23.59 ->   165.11
03

Keep every row with .over()

.over("symbol") after an expression says: compute it per symbol, but give me a value on every row. rank_in_symbol ranks each day's volume against the other days of the same stock. share_of_symbol divides each day's volume by that stock's total, so the shares of each stock add up to 1. Neither needs a join back to a summary table, which is the pandas habit that .over() replaces.

main.pyPython
# The busiest day of each stock: rank 1 within its own symbolranked = rank_in_symbol(df)top = ranked.filter(pl.col("volume_rank") == 1).sort("symbol")for symbol, day, volume in top.select("symbol", "date", "volume").rows():    print(symbol, day, f"{volume:,}")
AAPL 2000-09-29 8,846,193,721
JNJ 2023-08-21 151,319,484
JPM 2012-05-11 291,205,984
KO 2009-09-18 179,920,213
XOM 2010-06-25 189,442,014
main.pyPython
# Each day as a share of its stock's total volume; the shares of one stock add up to 1shared = share_of_symbol(df)print(shared.select("symbol", "date", pl.col("volume_share").round(6)).head(2).rows())print(shared.group_by("symbol").agg(pl.col("volume_share").sum().round(6)).sort("symbol").rows())
[('AAPL', datetime.date(2000, 1, 3), 0.000223), ('AAPL', datetime.date(2000, 1, 4), 0.000213)]
[('AAPL', 1.0), ('JNJ', 1.0), ('JPM', 1.0), ('KO', 1.0), ('XOM', 1.0)]
group_by has no promised order

The groups can come back in a different order on every run, because Polars processes them in parallel. A test or a report that depends on that order will fail at random. Sort the result by the key, or pass maintain_order=True when you need the groups in order of first appearance. .over() is different: it always returns the rows in their original order.

04

What the tasks ask

  1. 1
    `volume_by_symbol` and `first_last_close`df.group_by("symbol").agg(expr.alias(...), ...) then .sort("symbol"); sort by date first for first/last.
  2. 2
    `rank_in_symbol` and `share_of_symbol`df.with_columns(expr.over("symbol").alias(...)); rank(method="min", descending=True) and sum() as the window expressions.

Key takeaways

  • agg collapses, over keeps One row per group, or every row with a group-aware value.
  • Sort after group_by Group order is not promised, so make it explicit.
  • No join back needed A window expression replaces summarise-then-merge. Next: joins.
Quick check
You want each day's volume as a fraction of its own stock's total volume, keeping every row. Which tool?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • One row per group: volume_by_symbol25 pts
  • First and last by date: first_last_close25 pts
  • Rank inside the group: rank_in_symbol25 pts
  • A share of the group total: share_of_symbol25 pts
Explorer · lab-3-1
▾ lab-3-1
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-3-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

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