流水线是前面各个主题发挥价值的地方。tick 以行的形式到来;你想在收盘时得到各代码的名义金额,而不必加载整天的数据。用 Arrow,这只是对记录批的五个小步骤:构建批、对整列计算、写出流、逐批读回、累加汇总。内存里同时最多只有一个批,数据从头到尾保持列式布局。
用通俗的话说这个想法
我们在哪里。 Arrow 技能的最后一个主题。它用到了批(主题 2)、内核(主题 3)、IPC 流(主题 6),并再次用到主题 2 的流式读取模式;时间戳(主题 7)出现在模式里。同样结构的流水线,把流换成 Parquet 文件、把累加换成 DuckDB 或 Polars,就是数据流水线技能的主题。
由多个阶段串成的链,每个阶段以上一阶段的输出为输入,这里是一次一个批。由于同时在途的只有一小块,无论经过多少数据,内存都保持平稳,而且可以在不动其他阶段的情况下改进某个慢的阶段。
行进,批出,计算一列
rows_to_batches 是从 Python 进入 Arrow 的入口:每个批由至多 batch_rows 行逐列构建,使用共享的 TICK_SCHEMA,因此后续各阶段都可以信赖其类型。add_notional 是对整个批的一次内核调用:价格乘数量,任何一边为空结果就为空,无需另写特殊情况。
# The ticks as rows, then as record batches of 5,000 rows, then one batch with its notional columnprint(len(rows), "rows; first:", rows[0])batches = rows_to_batches(rows, 5000)print(len(batches), "batches:", [b.num_rows for b in batches])enriched = add_notional(batches[0])print(enriched.schema.names)print("first notional:", f"{enriched.column('notional')[0].as_py():,.0f}", "= price", rows[0][2], "x size", f"{rows[0][3]:,}")
33493 rows; first: ('AAPL', datetime.datetime(2000, 1, 3, 0, 0, tzinfo=datetime.timezone.utc), 0.83826, 638640787)
7 batches: [5000, 5000, 5000, 5000, 5000, 5000, 3493]
['symbol', 'ts', 'price', 'size', 'notional']
first notional: 535,347,026 = price 0.83826 x size 638,640,787写出流,再逐批汇总
write_ticks 为每个批加上名义金额,并在就绪后立刻写入 IPC 流文件,所以文件在增长,而内存里始终只有一个批。notional_by_symbol 以同样的方式读取该文件:一个批,一次小规模分组,累加到运行中的字典,再处理下一批。结果与一次性全部求和相同,但整天的数据从未同时在内存里。无论文件里是一天还是十年,代码都一样。
# Write the stream, then total the notional per symbol while reading it back one batch at a timeimport oswritten = write_ticks(batches, "ticks.stream")print(written, "rows written;", os.path.getsize("ticks.stream"), "bytes on disk")for symbol, total in notional_by_symbol("ticks.stream").items(): print(f"{symbol:5} {total:>22,.0f}")
33493 rows written; 1309120 bytes on disk AAPL 40,972,234,013,659 JNJ 5,791,663,141,548 JPM 8,498,489,347,331 KO 3,955,468,216,505 XOM 9,008,363,956,774
# Check against adding everything up in plain Python, which needs the whole list at oncecheck = {}for symbol, ts, price, size in rows: check[symbol] = check.get(symbol, 0.0) + price * sizetotals = notional_by_symbol("ticks.stream")print("same symbols:", sorted(check) == list(totals))print("largest relative difference:", f"{max(abs(totals[k] - check[k]) / check[k] for k in check):.1e}")
same symbols: True largest relative difference: 2.5e-15
可以更换任何一个阶段而不动其他阶段。数据需要长期保存时写 Parquet 而不是流(Parquet 技能);做更重的查询时把批交给 DuckDB 或 Polars(DuckDB 技能,像主题 5 那样零拷贝);或者用 Flight 发送这些批(主题 8)。批是阶段之间的契约,这就是 Arrow 适合流水线的原因。
任务要求
- 1`rows_to_batches`对每个
batch_rows行的切片,用zip(*chunk)转置,对TICK_SCHEMA的每个字段用pa.array(column, type=field.type),再pa.RecordBatch.from_arrays(arrays, schema=TICK_SCHEMA)。 - 2`add_notional`
pc.multiply(price, pc.cast(size, pa.float64())),再pa.RecordBatch.from_arrays(batch.columns + [notional], names=...)。 - 3`write_ticks` 与 `notional_by_symbol`用第一个批打开
ipc.new_stream(sink, enriched.schema)并对每个批write_batch;用ipc.open_stream(source)读取,对每个批分组并累加进运行中的字典。
notional_by_symbol 逐批读取流,而不是用 read_all() 加载?实验:评分内容
4 个任务 · 100 分- 把行变成批:
rows_to_batches25 分 - 一个内核算名义金额:
add_notional25 分 - 写出流:
write_ticks25 分 - 逐批汇总:
notional_by_symbol25 分