价格告诉你发生了什么,基本面告诉你它可能为何重要。把两者放进一张表需要连接,而量化工作中最常出错的就是按时间连接。3 月 3 日的价格应带上市场在 3 月 3 日已知的营收,而不是 3 月 20 日才公布的营收。as-of 连接就是为按日期做这种匹配而存在的,用对它才能避免回测偷看未来。
用通俗的话说这个想法
我们在哪里。 主题 3 在一张表内部做汇总。这里是两张表的相遇。前半部分是普通的键连接:附加一列、找出没有匹配的项。后半部分是时间连接。季度基本面数据与 SQL 技能用的是同一个数据集,那里以可移植的形式讲过 as-of 思想;join_asof 是 Polars 中对应的算子。
把左表的每一行匹配到右表中时间不晚于它的最近一行,而不是完全相等的键。它要求两张表都按时间排序,还可以设置容差来拒绝过旧的匹配。
附加一列,并找出没有匹配的项
左连接保留左表的每一行,未匹配处用空值填充新列,所以表不会悄悄变小。内连接则会一声不响地丢掉这些行。反连接直接回答审计问题:我的价格里哪些代码没有行业?每次连接之后都运行它,看看你丢了什么,或者本来就没有什么。
# Left join: KO has no sector in the lookup, so its sector is null; the anti join names the gapjoined = join_sector(bars, sectors)print(joined.group_by("symbol").agg(pl.col("sector").first()).sort("symbol").rows())print("rows kept:", joined.height, "of", bars.height)print("no sector for:", symbols_without_sector(bars, sectors))
[('AAPL', 'Tech'), ('JNJ', 'Health'), ('JPM', 'Banks'), ('KO', None), ('XOM', 'Energy')]
rows kept: 33493 of 33493
no sector for: ['KO']匹配到最近一条更早的记录
每份财报在其 filed 日期才可见,而不是在季度末。latest_filing 先把两个数据框按时间排序,然后 join_asof 一起扫描:对每个价格,取同一代码在当天或更早的最新财报,by="symbol" 把各代码分开。某代码首次财报之前,营收为空,这是正确的,因为当时还一无所知。
# KO around its first filing in the data (24 April 2019): null before, then the report that was publicko = latest_filing(bars, filings).filter((pl.col("symbol") == "KO") & (pl.col("date") >= pl.date(2019, 4, 22)) & (pl.col("date") <= pl.date(2019, 4, 26)))for row in ko.rows(): print(row)
('KO', datetime.date(2019, 4, 22), 42.1946, datetime.date(2019, 2, 21), 7058000000)
('KO', datetime.date(2019, 4, 23), 42.915, datetime.date(2019, 2, 21), 7058000000)
('KO', datetime.date(2019, 4, 24), 42.7105, datetime.date(2019, 2, 21), 7058000000)
('KO', datetime.date(2019, 4, 25), 42.5862, datetime.date(2019, 4, 25), 8020000000)
('KO', datetime.date(2019, 4, 26), 42.96, datetime.date(2019, 4, 25), 8020000000)对过期匹配设置容差
最近一份财报可能已是一年前的。设置 tolerance=timedelta(days=max_days) 后,连接会拒绝比这更旧的匹配并留下空值。recent_filing 把这个选择明确化:三个季度前的营收数字不应被当作当前数字。出现的空值个数本身,也是关于基本面数据是否完整的信息。
# How many price rows have no filing at all, and how many have none within 100 daysanywhere = latest_filing(bars, filings)["revenue"].null_count()recent = recent_filing(bars, filings, 100)["revenue"].null_count()print("no filing yet:", anywhere, "| none in the last 100 days:", recent, "| of", bars.height, "rows")
no filing yet: 21903 | none in the last 100 days: 25684 | of 33493 rows
季度在某一天结束,而财报要几周后才发布。按期末日期连接,会把当时没人知道的营收交给模型,使所有回测都显得更漂亮。基本面一定要按发布日期连接。验证方法是看某次发布前后的两行:数字必须在发布当天才变化,而不是更早。
任务要求
- 1`join_sector` 与 `symbols_without_sector`
bars.join(sectors, on="symbol", how="left");how="anti",再取去重后排序的代码。 - 2`latest_filing` 与 `recent_filing`两个数据框先按时间排序,再
join_asof(right, left_on="date", right_on="filed", by="symbol", strategy="backward");加上tolerance=timedelta(days=max_days);最后按代码和日期排序。
实验:评分内容
4 个任务 · 100 分- 附加一列:
join_sector25 分 - 谁没有匹配:
symbols_without_sector25 分 - 匹配到最近一条更早的记录:
latest_filing25 分 - 仅当足够新:
recent_filing25 分