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.
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.
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.
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.
# 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)]
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.
# 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# 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)
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.
# 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 33493group_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.
What the tasks ask
- 1`calendar_columns`
with_columnswithdt.year(),dt.month()anddt.weekday(), aliasedyear,month,weekday. - 2`month_end_close` and `weekly_volume`Sort, then
group_by_dynamic("date", every="1mo", group_by="symbol")withlast();every="1w"withsum(); renamedate. - 3`bars_per_month`
dt.truncate("1mo")aliasedmonth, an ordinarygroup_bywithpl.len(), sorted.
group_by_dynamic on a frame that is not sorted by date, and the monthly numbers look wrong. What is the likely fix?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