2009 年底,五只大型股的最大方向承载了它们 80.4% 的方差,协方差矩阵的条件数为 45.7;到 2026 年 8 月,同一方向只占 30.3%,条件数为 3.7。把这个测量在 6,447 个滚动窗口上重复一遍,布局得当只需 0.043 秒,布局不当要 11.6 秒。这样的任务该怎样搭建,又该怎样核算成本?
用通俗的话说这个想法
我们在哪里。 这是最后一个主题,它用到前面所有主题。这项任务的各阶段就是整个技能的各阶段:BLAS 的三个层级决定每一步的成本(主题 1),协方差是一次分块的 dgemm(2),作用在我们如实声明了排布的数据上(3),再做特征值分解(4),按生产代码的方式调用(5),并用条件数评判答案(6),整件事分摊到各个核上(7),所用的库来自一张表的选择(8),并且可以从 C 调用(9)。
- 阶段用到技能中的什么
- load_returns_matrix从价格到收益率对齐日期,纯 Python
- covariance_matrix第 3 层乘积主题 1、2
- eigen_report特征值与条件数主题 4、5、6
- pipeline_report多核上的成本主题 7、8
输入真实价格,输出对齐的收益率
data 文件夹里有 AAPL、JPM、XOM、JNJ、KO 的日线。它们的起始日期各不相同,所以第一项工作是只保留五只都有的日期,并把收盘价转成简单收益率。PATHS 是这五个文件的列表。
# Five price files in, one table of aligned daily returns outdates, rows = load_returns_matrix(PATHS)print(len(rows), "days of returns from", dates[0], "to", dates[-1], "|", len(rows[0]), "stocks")1print("last day:", [f"{r * 100:+.2f}%" for r in rows[-1]])
6696 days of returns from 2000-01-04 to 2026-08-21 | 5 stocks last day: ['-0.63%', '+0.01%', '-0.63%', '+1.07%', '+0.66%']
- 16,696 天:五个文件从 2000 年 1 月 4 日起重叠,每一行对每只股票有一个收益率。
协方差及其形状
# The covariance of the last 250 days: one dgemm, charged to the counterblas = Blas()cov = covariance_matrix(blas, rows[-250:])print("flops", blas.flops, "words", blas.words, "| flops per word", round(blas.intensity(), 2))1report = eigen_report(blas, cov)print("share of the variance, smallest to largest direction (%):", [round(s * 100, 1) for s in report["share"]])print("condition number:", round(report["condition"], 2), "| after the eigen step: flops", blas.flops)2print("largest direction (AAPL, JPM, XOM, JNJ, KO):", [round(v, 2) for v in report["top_vector"]])
flops 12500 words 2525 | flops per word 4.95 share of the variance, smallest to largest direction (%): [8.2, 16.3, 19.7, 25.5, 30.3] condition number: 3.67 | after the eigen step: flops 12666 largest direction (AAPL, JPM, XOM, JNJ, KO): [0.64, 0.33, -0.68, -0.07, -0.08]
- 1与第一个主题相同:2,525 个字上 12,500 次 flop,乘积很便宜,强度约为 5。
- 2条件数小于 4:矩阵病态程度很低,其分解大约可信到 15 位。
形状如何随年份变化
我们在选定年份最后一个交易日结束的 250 天上重复这个测量。当市场一起下跌时,一个方向(所有股票随大盘一起动)吞掉了方差,矩阵也更难处理。
# The largest direction's share of the variance, and the condition number, at the end of selected yearslast_day = {}for position, date in enumerate(dates): last_day[date[:4]] = positionfor year in ("2004", "2008", "2009", "2013", "2017", "2020", "2024"): end = last_day[year] window = covariance_matrix(Blas(), rows[end - 249:end + 1]) result = eigen_report(Blas(), window) print(year, f"largest direction {result['share'][-1] * 100:5.1f}% condition {result['condition']:5.1f}")1
2004 largest direction 62.5% condition 10.6 2008 largest direction 64.7% condition 39.5 2009 largest direction 80.4% condition 45.7 2013 largest direction 46.9% condition 10.2 2017 largest direction 39.2% condition 5.0 2020 largest direction 70.8% condition 27.7 2024 largest direction 35.7% condition 6.4
- 12009 和 2020 最突出:崩盘时股票一起下跌,一个方向承担 71% 到 80% 的风险,条件数是 2017 这类平静年份的 5 到 9 倍。
核算滚动任务的成本
一个窗口只有 12,666 次 flop,微不足道,而任务有 6,447 个窗口。主题 7 已经告诉我们对大量小而独立的任务该怎么办:每个核一个单线程的工作进程。pipeline_report 运行布局搜索,并与朴素选择(8 个进程各要 8 个线程)作比较。
# What the rolling job costs on an 8-core machine (4 billion flops per second per core, 50 microseconds per thread)windows = len(rows) - 249report = pipeline_report(windows, 5, 250, 8, 4e9, 5e-5)print("flops per window:", report["flops_per_window"], "| total:", f"{report['flops_per_window'] * windows:.3g}")print("best layout (workers, threads):", report["layout"], "->", round(report["seconds"], 4), "s")print("8 workers x 8 threads:", round(report["naive_seconds"], 2), "s |", round(report["speedup"]), "times slower")1print("one thread, one worker:", round(batch_time(windows, report["flops_per_window"], 1, 1, 8, 4e9, 5e-5), 3), "s")
flops per window: 12666 | total: 8.17e+07 best layout (workers, threads): (8, 1) -> 0.0429 s 8 workers x 8 threads: 11.62 s | 271 times slower one thread, one worker: 0.343 s
- 1最佳配置是 8 个单线程进程。朴素地把 64 个线程压在 8 个核上,要多花 271 倍时间,正如主题 7 所预测的。
成本模型告诉你该看哪里,而不是秒表会显示什么。在真机上,用 NumPy 对几个窗口跑协方差和特征值步骤,把 OMP_NUM_THREADS 分别设为 1 和核数,分别用一个和多个工作进程,保留最快的配置。答案的形状(大量小任务适合许多单线程进程)是稳健的,具体数字则不是。
任务要求
- 1`load_returns_matrix`用
csv.DictReader按列名读文件,保留共同日期,返回日期和简单收益率表。 - 2`covariance_matrix` 与 `eigen_report`去均值并除以 T − 1 后用一次
dgemm得到协方差,再基于eigh生成报告:特征值、方差占比、最大特征向量和条件数。 - 3`pipeline_report`用线程模型核算滚动任务:每窗口 flop 数、最佳配置、所需秒数,以及朴素配置的代价。
实验:评分内容
4 个任务 · 100 分- 用
load_returns_matrix载入对齐的收益率25 分 - 用
covariance_matrix构造协方差25 分 - 用
eigen_report描述它25 分 - 用
pipeline_report核算任务成本25 分