日线是原材料,研究面板才是你真正研究的对象。把前者变成后者,是每条量化流水线的第一项工作,用到了本技能的全部内容:日历窗口、按代码的滚动表达式、一次连接,以及跨代码的统计。这个结业项目把它们组装成一条可复现的链。
用通俗的话说这个想法
我们在哪里。 本技能的最后一个主题。这里没有新工具,只有使用工具的顺序。四个步骤:用 group_by_dynamic 把日线变成月线;用 .over("symbol") 在每个代码内部加入收益、动量和波动率;用左连接附上月度因子;最后用 .over("month") 在每个月内比较各只股票。每一步接收一个数据框并返回一个数据框,因此可以单独测试。
每个“个体 × 时间”组合各占一行的表,这里就是每只股票和每个月。沿一列向下读是某只股票的历史,横跨一个月读则是各只股票之间的比较。
第 1 步:月线
月线是由当月日线算出的五个数:第一天的开盘价、最高的最高价、最低的最低价、最后一天的收盘价和总成交量。group_by_dynamic 按代码把有序日期切成日历月,agg 取 first、max、min、last 和 sum。两个检查能说明这一步正确:成交量没有丢失,最高价从不低于最低价。
# 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第 2 步:每个代码内部的特征
三列都用 .over("symbol") 计算,避免一只股票渗入下一只:月收益率(pct_change())、12 个月动量(pct_change(12),即自一年前以来的收益)和 12 个月波动率(月收益率的滚动标准差)。每只股票的前十二行为空,因为历史太短,这是对的:空值是诚实的,猜测则不然。
# 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)
第 3 步:附上因子
Fama-French 因子每月一行,所以按 month 左连接后,每个“股票×月份”都带上了市场收益、规模、价值和无风险利率。左连接即使某月没有因子也保留该行,所以面板不会悄悄变小。减去无风险利率得到超额收益,这正是因子回归所用的数。
# 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第 4 步:在每个月内比较各只股票
到目前为止,窗口都是沿时间方向运行。横截面统计则是跨代码运行:.over("month") 取该月动量的均值和标准差,z 分数说明此刻每只股票比同伴高出或低于多少。这是把原始信号变成可逐月比较的排名的标准做法,主题 6 里 .over 的思想在这里以第二种形式得到回报。
# 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由四个函数组成的流水线就是四个小测试。当最终的 z 分数看起来奇怪时,先检查下一层:连接是否保留了所有行,特征是否在该为空的地方为空,月线是否保留了全部成交量?返回数据框的小步骤,能让你在几分钟而不是几小时内找出错误。
任务要求
- 1`monthly_bars` 与 `add_features`排序,
group_by_dynamic("date", every="1mo", group_by="symbol")配合first、max、min、last、sum,重命名date;pct_change()、pct_change(12)、rolling_std(12),各自.over("symbol")。 - 2`join_factors` 与 `zscore_panel`
join(factors, on="month", how="left"),再把ret - rf作为excess;drop_nulls("mom12"),(x - x.mean().over("month")) / x.std().over("month"),按月和代码排序。
.over("symbol") 而不是 .over("month") 计算。结果表示什么?实验:评分内容
4 个任务 · 100 分- 从日线到月线:
monthly_bars25 分 - 收益、动量、波动率:
add_features25 分 - 附上因子:
join_factors25 分 - 在每个月内排名:
zscore_panel25 分