Our five stocks fit in memory with room to spare, but the habits you build now decide what happens on fifty years of tick data. The question to ask of every step is how much of the file it has to hold at once. Polars lets you answer: a chunk, not the file.
The idea in plain words
Where we are. Topic 8 introduced the lazy API. This topic uses it on data that is bigger than you want in memory. Three tools: sink_parquet writes a lazy query to disk as it runs, scan_parquet reads only the columns and row groups the query needs, and slice lets you walk through a result in fixed-size chunks when a step really must be done piece by piece.
Data too big to hold in RAM at once. It can still be processed by reading it in pieces and keeping only a small running result, so the memory used depends on the size of a piece, not on the size of the data.
Write while you read
Collecting a query puts its whole result in memory. sink_parquet(path) is the lazy alternative: Polars runs the query and writes the result straight to the file in batches, so a result bigger than RAM is fine. It also converts: here five CSV files become a single Parquet file, which is smaller and much faster to read back.
# Five CSV files into one Parquet file, written by sink_parquet without collecting anythingshutil.rmtree("lake", ignore_errors=True)os.makedirs("lake")rows = bars_to_parquet("data", SYMBOLS, "lake/bars.parquet")csv_mb = sum(os.path.getsize(f"data/{s}.csv") for s in SYMBOLS) / 1e6print(rows, "rows | CSV", round(csv_mb, 1), "MB -> Parquet", round(os.path.getsize("lake/bars.parquet") / 1e6, 1), "MB")
33493 rows | CSV 1.7 MB -> Parquet 0.7 MB
Read only what the query needs
scan_parquet keeps the file lazy and Parquet stores each column separately, so a query that touches three columns out of seven reads only those three. The yearly volume below never loads open, high, low or close. Combined with a filter on a sorted column, whole row groups are skipped as well, which is why Parquet beats CSV on big data.
# Yearly volume from the Parquet file: only symbol, date and volume are readyearly = yearly_volume("lake/bars.parquet")print(yearly.filter(pl.col("symbol") == "KO").head(3).rows())print("rows in the answer:", yearly.height, "from", rows, "rows in the file")
[('KO', 2000, 3620485497), ('KO', 2001, 3269679676), ('KO', 2002, 3921594525)]
rows in the answer: 135 from 33493 rows in the fileWhen a step must go piece by piece
Not everything can be written as one lazy query: you may call a library that wants a real DataFrame, or train on batches. lazy.slice(offset, length).collect() gives you rows offset to offset + length, one chunk at a time, and you keep only a small running total. The loop below counts rows per symbol while holding at most chunk_rows rows. split_by_symbol goes the other way and cuts one file into many with a lazy filter and sink_parquet for each piece.
# Count rows per symbol in chunks of 10,000, then split the file into one file per symbolprint(symbol_counts_chunked("lake/bars.parquet", 10_000))written = split_by_symbol("lake/bars.parquet", "lake/by_symbol")print(written, "->", sorted(os.listdir("lake/by_symbol"))[:2], "...")
{'AAPL': 6699, 'JNJ': 6699, 'JPM': 6698, 'KO': 6699, 'XOM': 6698}
['AAPL', 'JNJ', 'JPM', 'KO', 'XOM'] -> ['AAPL.parquet', 'JNJ.parquet'] ...A tiny chunk makes the loop slow, because every piece pays a fixed cost to start. A huge one defeats the purpose. Pick the largest chunk that comfortably fits in memory, and prefer one lazy query or a sink_ to a hand-written loop whenever the work can be written that way.
What the tasks ask
- 1`bars_to_parquet` and `yearly_volume`Scans with
pl.lit(s),pl.concat,sink_parquet, then count withscan_parquet;scan_parquet,select,group_byon symbol anddt.year(),sum, sort,collect(). - 2`symbol_counts_chunked` and `split_by_symbol`Row count, then
range(0, total, chunk_rows)withslice(offset, chunk_rows).collect()and a running dict; unique symbols, then a lazyfilterandsink_parquetfor each.
Lab · what's graded
4 tasks · 100 pts- Write while you read:
bars_to_parquet25 pts - Read only what you need:
yearly_volume25 pts - Walk through it in chunks:
symbol_counts_chunked25 pts - Split a big file:
split_by_symbol25 pts