σμ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.5·~1 hr 30 minAdvanced

Capstone: a monthly bar builder and factor panel

Skill positionModule 3 of 3 · Topic 5 of 5
3.5 Capstone: a monthly bar builder and factor panel
—Lab score— / 100Total XP—Streak—
Lecture0% read

4 min readCode examples: 4

  1. 01The idea in plain words
  2. 02Step 1: monthly bars
  3. 03Step 2: features inside each symbol
  4. 04Step 3: attach the factors
  5. 05Step 4: compare the stocks within each month
  6. 06What the tasks ask

Daily bars are the raw material; a research panel is what you actually study. Turning one into the other is the job every quant pipeline starts with, and it uses everything in this skill: calendar windows, per-symbol rolling expressions, a join, and statistics across symbols. This capstone assembles them into one reproducible chain.

01

The idea in plain words

Where we are. The last topic of the skill. There is no new tool here, only the order in which the tools are used. Four steps: turn daily bars into monthly bars with group_by_dynamic; add return, momentum and volatility inside each symbol with .over("symbol"); attach the monthly factors with a left join; and finally compare the stocks to each other within each month with .over("month"). Each step takes a frame and returns a frame, so it can be tested alone.

DefinitionPanel data

A table with one row for every combination of an entity and a time, here every stock and every month. It can be read down a column for one stock's history, or across a month to compare the stocks.

02

Step 1: monthly bars

A monthly bar is five numbers computed from the daily bars of the month: the open of the first day, the highest high, the lowest low, the close of the last day and the total volume. group_by_dynamic cuts the sorted dates into calendar months for each symbol, and agg takes first, max, min, last and sum. Two checks tell you the step is right: no volume is lost, and the high is never below the low.

main.pyPython
# Daily to monthly: the first month of KO, and two checks that the step is rightprint(monthly.height, "monthly bars from", bars.height, "daily bars")print(monthly.filter(pl.col("symbol") == "KO").head(1).rows())print("volume kept:", monthly["volume"].sum() == bars["volume"].sum(), "| high >= low everywhere:", bool((monthly["high"] >= monthly["low"]).all()))
1600 monthly bars from 33493 daily bars
[('KO', datetime.date(2000, 1, 1), 19.7756, 23.0787, 19.0671, 19.8226, 325484697)]
volume kept: True | high >= low everywhere: True
03

Step 2: features inside each symbol

Three columns, all computed with .over("symbol") so one stock never leaks into the next: the monthly return (pct_change()), the 12-month momentum (pct_change(12), the return since a year ago) and the 12-month volatility (a rolling standard deviation of the monthly return). The first twelve rows of each stock are null because the history is too short, and that is correct: a null here is honest, a guess would not be.

main.pyPython
# KO in the last months of the data: return, 12-month momentum and 12-month volatilitylast = features.filter(pl.col("symbol") == "KO").tail(2).select("month", pl.col("ret", "mom12", "vol12").round(3))print(last.rows())print("nulls per column:", features.select(pl.col("ret", "mom12", "vol12").null_count()).row(0))
[(datetime.date(2026, 7, 1), 0.078, 0.29, 0.051), (datetime.date(2026, 8, 1), 0.04, 0.32, 0.051)]
nulls per column: (5, 60, 60)
04

Step 3: attach the factors

The Fama-French factors are one row per month, so a left join on month gives every stock-month the market return, size, value and risk-free rate. A left join keeps rows even when a month has no factors, so the panel never shrinks silently. Subtracting the risk-free rate gives the excess return, the number that factor regressions use.

main.pyPython
# Excess return against the market: how closely does each stock follow it?valid = panel.drop_nulls(["excess", "mkt_rf"])print(valid.group_by("symbol").agg(pl.corr("excess", "mkt_rf").round(2).alias("corr_with_market")).sort("symbol").rows())print("rows kept by the left join:", panel.height, "of", features.height)
[('AAPL', 0.55), ('JNJ', 0.36), ('JPM', 0.69), ('KO', 0.37), ('XOM', 0.42)]
rows kept by the left join: 1600 of 1600
05

Step 4: compare the stocks within each month

Until now the windows ran down time. A cross-sectional statistic runs across symbols instead: .over("month") takes the mean and standard deviation of that month's momentum, and the z-score says how far each stock is above or below its peers right then. It is the standard way to turn a raw signal into a rank that can be compared month to month, and it is where the .over idea of topic 6 pays off in its second form.

main.pyPython
# The most recent month: the five stocks ranked by 12-month momentum, as a z-score among themselvesranked = zscore_panel(panel)latest = ranked.filter(pl.col("month") == ranked["month"].max()).sort("mom_z")print(latest["month"][0], [(s, round(z, 2)) for s, z in latest.select("symbol", "mom_z").rows()])print("each month sums to about zero:", bool((ranked.group_by("month").agg(pl.col("mom_z").sum().abs()).get_column("mom_z") < 1e-9).all()))
2026-08-01 [('JPM', -1.41), ('KO', -0.28), ('AAPL', -0.17), ('XOM', 0.63), ('JNJ', 1.23)]
each month sums to about zero: True
Test each step on its own

A pipeline that is four functions is four small tests. When the final z-scores look odd, check the layer below first: is the join keeping every row, are the features null where they should be, do the monthly bars keep all the volume? Small steps that return frames are what let you find a mistake in minutes, not hours.

06

What the tasks ask

  1. 1
    `monthly_bars` and `add_features`Sort, group_by_dynamic("date", every="1mo", group_by="symbol") with first, max, min, last, sum, rename date; pct_change(), pct_change(12) and rolling_std(12), each .over("symbol").
  2. 2
    `join_factors` and `zscore_panel`join(factors, on="month", how="left"), then ret - rf as excess; drop_nulls("mom12"), (x - x.mean().over("month")) / x.std().over("month"), sort by month and symbol.

Key takeaways

  • Calendar windows build the panel group_by_dynamic turns daily bars into monthly bars in one step.
  • `over` has two directions .over("symbol") runs along time, .over("month") runs across stocks.
  • Small steps, frames in and out Each step is testable alone. That completes Polars: the next data-stack skill is data pipelines.
Quick check
In the panel, a z-score is computed with .over("symbol") instead of .over("month"). What does the result show?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • Daily into monthly: monthly_bars25 pts
  • Return, momentum, volatility: add_features25 pts
  • Attach the factors: join_factors25 pts
  • Rank within each month: zscore_panel25 pts
Explorer · lab-11-1
▾ lab-11-1
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-11-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

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