几乎每个金融问题里都藏着一个日历:月末收盘价、一周的成交量、一年有多少个交易日。Polars 把日期当作一等类型:用 .dt 读取它的各个部分,再用一次调用把有序序列切成日历窗口。
用通俗的话说这个想法
我们在哪里。 主题 4 按时间连接了两张表。这里我们留在一张表内,按日历来切分。先是 .dt 命名空间:年、月、星期。然后是把序列切成月或周的 group_by_dynamic。最后是把日期截断后用普通 group_by 的做法,以及如何在两者之间取舍。
按固定日历长度(一天、一周、一个月)的时间窗口来分组的聚合,窗口取自一列已排序的日期。每个窗口以其起点命名,空窗口不会出现。
读取日期的各部分
Date 列有 .dt 命名空间。dt.year()、dt.month()、dt.weekday() 返回普通数字,星期一为 1,星期日为 7。它们是表达式,用 with_columns 添加后,就能像普通列一样用来分组、过滤或排序。
# 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)]
跟随日历的窗口
group_by_dynamic("date", every="1mo") 为每个日历月建立一个分组,不管这个月有几天。加上 group_by="symbol" 就按股票分别做,并在其中聚合:收盘价的 last() 就是月末收盘价。结果以每个窗口的第一天作标签,并且数据框必须按日期列排序(先按分组键),否则窗口会出错。
# 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)
截断,还是动态切分
同样的窗口还有第二条路。dt.truncate("1mo") 把每个日期向下取整到所在月的第一天,再对这一列做普通 group_by 计数或求和。它不需要排序,也能用在其他表达式里。顺序重要、或窗口重叠、带偏移时,group_by_dynamic 更合适;单纯的月度汇总,截断加 group_by 更简单。
# 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 假定日期列已排序,带 group_by= 时还要求分组键先排序。否则 Polars 要么报错,要么用错误的相邻行建窗口。在它之前调用 sort("symbol", "date");代价很小,却能避免一类悄无声息的错误。
任务要求
- 1`calendar_columns`用
with_columns加入dt.year()、dt.month()、dt.weekday(),命名为year、month、weekday。 - 2`month_end_close` 与 `weekly_volume`先排序,再用
group_by_dynamic("date", every="1mo", group_by="symbol")配合last();every="1w"配合sum();重命名date。 - 3`bars_per_month`
dt.truncate("1mo")命名为month,用普通group_by加pl.len(),再排序。
group_by_dynamic,月度数字看起来不对。最可能的修复是什么?实验:评分内容
4 个任务 · 100 分- 读取日期的各部分:
calendar_columns25 分 - 每月最后一个收盘价:
month_end_close25 分 - 每周成交量:
weekly_volume25 分 - 统计每月的K线数:
bars_per_month25 分