σμ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 2 · Joins, time and windows›Topic 2.2·~45 minIntermediate

Dates and dynamic grouping

Skill positionModule 2 of 3 · Topic 2 of 3
2.2 Dates and dynamic grouping
—Lab score— / 100Total XP—Streak—
Lecture0% read

3 min readCode examples: 4

  1. 01The idea in plain words
  2. 02Read the parts of a date
  3. 03Windows that follow the calendar
  4. 04Truncate, or cut dynamically
  5. 05What the tasks ask

Almost every question in finance carries a calendar inside it: the close of the month, the volume of the week, how many trading days a year has. Polars treats dates as a first-class type, so you read their parts with .dt and cut a sorted series into calendar windows with one call.

01

The idea in plain words

Where we are. Topic 4 joined two tables on time. Here we stay in one table and slice it by the calendar. First the .dt namespace: year, month, weekday. Then group_by_dynamic, which cuts the series into months or weeks. Last, the older route of truncating the date and using an ordinary group_by, and why you would pick one over the other.

DefinitionDynamic group-by

A group-by whose groups are time windows of fixed calendar length (a day, a week, a month) cut from a sorted date column. Each window is named by its start, and empty windows simply do not appear.

02

Read the parts of a date

A Date column has a .dt namespace. dt.year(), dt.month() and dt.weekday() return plain numbers, with Monday as 1 and Sunday as 7. They are expressions, so you add them with with_columns and then group, filter or sort on them like any column.

main.pyPython
# Add year, month and weekday, then count the bars of AAPL on each weekday (1 = Monday)dated = calendar_columns(bars)aapl = dated.filter(pl.col("symbol") == "AAPL")print(aapl.head(2).select("date", "year", "month", "weekday").rows())print(aapl.group_by("weekday").len().sort("weekday").rows())
[(datetime.date(2000, 1, 3), 2000, 1, 1), (datetime.date(2000, 1, 4), 2000, 1, 2)]
[(1, 1257), (2, 1375), (3, 1375), (4, 1349), (5, 1343)]
03

Windows that follow the calendar

group_by_dynamic("date", every="1mo") makes one group per calendar month, whatever the number of days in it. Add group_by="symbol" to do it for each stock, and aggregate inside: last() of the close is the month-end close. The result is labelled by each window's first day, and the frame must be sorted by the date column (by the group key first) or the windows come out wrong.

main.pyPython
# The last close of each month, for the first three months of AAPLmonthly = month_end_close(bars)print(monthly.filter(pl.col("symbol") == "AAPL").head(3).rows())print("month rows:", monthly.height, "| symbols:", monthly["symbol"].n_unique())
[('AAPL', datetime.date(2000, 1, 1), 0.777129), ('AAPL', datetime.date(2000, 2, 1), 0.858865), ('AAPL', datetime.date(2000, 3, 1), 1.01712)]
month rows: 1600 | symbols: 5
main.pyPython
# The same idea by week: the volume of KO in the first three weeks, each labelled by its Mondayweeks = weekly_volume(bars, "KO")print(weeks.head(3).rows())print("first week starts on weekday", weeks["week"][0].isoweekday(), "(1 = Monday)")
[(datetime.date(2000, 1, 3), 67237160), (datetime.date(2000, 1, 10), 58191080), (datetime.date(2000, 1, 17), 78416449)]
first week starts on weekday 1 (1 = Monday)
04

Truncate, or cut dynamically

There is a second route to the same windows. dt.truncate("1mo") rounds every date down to the first day of its month, and an ordinary group_by on that column then counts or sums. It needs no sorting and also works inside other expressions. group_by_dynamic is the better tool when the order matters, or when you want windows that overlap or start at an offset; truncate plus group_by is the simpler one for plain monthly totals.

main.pyPython
# Bars per month with truncate and group_by: a full month has about 20 to 23 trading dayscounts = bars_per_month(bars)print(counts.filter(pl.col("symbol") == "JPM").head(3).rows())print("fewest and most bars in a month:", counts["bars"].min(), counts["bars"].max())print("bars counted:", counts["bars"].sum(), "of", bars.height)
[('JPM', datetime.date(2000, 1, 1), 20), ('JPM', datetime.date(2000, 2, 1), 20), ('JPM', datetime.date(2000, 3, 1), 23)]
fewest and most bars in a month: 15 23
bars counted: 33493 of 33493
Sort before you cut

group_by_dynamic assumes the date column is sorted, and with group_by= it also wants the key sorted first. If it is not, Polars either raises an error or builds windows from the wrong neighbours. Call sort("symbol", "date") right before it; the cost is small and it removes a class of silent mistakes.

05

What the tasks ask

  1. 1
    `calendar_columns`with_columns with dt.year(), dt.month() and dt.weekday(), aliased year, month, weekday.
  2. 2
    `month_end_close` and `weekly_volume`Sort, then group_by_dynamic("date", every="1mo", group_by="symbol") with last(); every="1w" with sum(); rename date.
  3. 3
    `bars_per_month`dt.truncate("1mo") aliased month, an ordinary group_by with pl.len(), sorted.

Key takeaways

  • `.dt` reads the parts Year, month and weekday are expressions you add like any column.
  • Dynamic windows follow the calendar group_by_dynamic with every= on a sorted date; label is the window start.
  • Truncate for the simple case dt.truncate plus group_by needs no sorting. Next: rolling and cumulative expressions.
Quick check
You run group_by_dynamic on a frame that is not sorted by date, and the monthly numbers look wrong. What is the likely fix?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • Read the parts of a date: calendar_columns25 pts
  • The last close of each month: month_end_close25 pts
  • Volume per week: weekly_volume25 pts
  • Count the bars of a month: bars_per_month25 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