How do I query many files without loading them all?

Describe a query over a folder of Parquet files with Polars scan_parquet, let Polars read only the columns the query needs and filter the rows before the aggregation, and collect a small result.

After this lesson, you can query 22 daily trade files and return one row per day with CCC’s number of trades, shares and volume-weighted average price, VWAP.

How do I describe the query before it runs?

pl.scan_parquet(files) starts a lazy query over all 22 files, a plan that records each step without reading the trades, and .filter, .group_by and .agg add the steps for CCC’s daily summary. The result is a LazyFrame, which runs only when .collect() asks for it.

\[ \text{VWAP} = \frac{\sum_i p_i\, q_i}{\sum_i q_i} \]

Here \(p_i\) is the price of CCC’s trade \(i\) in dollars per share and \(q_i\) its size in shares. The made-up files hold 100,000 trades per weekday of April 2024, each with a time, a ticker from AAA to EEE, a price, a size and an exchange. pl.col("size") stands for a column in the plan, .dt.date().alias("date") takes each trade’s calendar date, and the names in .agg label the output columns. Polars installs with python -m pip install polars.

Code: the 22 made-up daily files
import shutil
from pathlib import Path

import numpy as np
import pandas as pd
import polars as pl

folder = Path("polars_ticks")
shutil.rmtree(folder, ignore_errors=True)
folder.mkdir()
rng = np.random.default_rng(10)
price_level = {"AAA": 170.0, "BBB": 180.0, "CCC": 410.0, "DDD": 880.0, "EEE": 170.0}
n = 100_000
for day in pd.bdate_range("2024-04-01", "2024-04-30"):
    tickers = rng.choice(list(price_level), n)
    times = day + pd.Timedelta("09:30:00") + pd.to_timedelta(np.sort(rng.integers(0, 23_400_000, n)), unit="ms")
    prices = (pd.Series(tickers).map(price_level) * rng.normal(1, 0.01, n)).round(2)
    pd.DataFrame({"time": times, "ticker": tickers, "price": prices, "size": rng.integers(1, 1_000, n), "exchange": rng.choice(["NASDAQ", "NYSE Arca", "Cboe BZX", "IEX"], n)}).to_parquet(folder / f"trades_{day.date()}.parquet", index=False)
files = sorted(folder.glob("trades_*.parquet"))

The following box describes CCC’s daily summary.

size = pl.col("size")
query = (
    pl.scan_parquet(files)
    .filter(pl.col("ticker") == "CCC")
    .group_by(pl.col("time").dt.date().alias("date"))
    .agg(trades=pl.len(), shares=size.sum(), vwap=(pl.col("price") * size).sum() / size.sum())
    .sort("date")
)
print(len(files), type(query).__name__)
22 LazyFrame

What will Polars read?

query.explain() shows the plan Polars will run, and its scan requests four of the five columns, because the filter needs the ticker, the date needs the time and the totals need the price and the size, and it applies the CCC filter while reading. The exchange column is never read.

In Polars 2.2.0, the line starting with PROJECT counts the requested columns and the line starting with SELECTION shows the filter, and the wording can change between versions. Each file’s row groups contain all five tickers, so the reader still checks every group for CCC rows.

The following box prints the two lines of the plan.

for line in query.explain().splitlines():
    if line.strip().startswith(("PROJECT ", "SELECTION")):
        print(line.strip())
PROJECT 4/5 COLUMNS
SELECTION: [(col("ticker")) == ("CCC")]

How do I collect the daily rows?

query.collect(engine="streaming") runs the plan in batches and returns 22 rows, one per day, and on 1 April CCC had 19,701 trades of 9,859,842 shares at a VWAP of 410.07 dollars. A pandas read of all 2,200,000 trades gives the same daily shares.

The streaming engine updates each day’s count and sums batch by batch, so it never holds all trades at once, and only the 22-row result must fit in memory. .round(2) rounds the VWAP for display.

The following box collects the result and checks the shares with pandas.

daily = query.collect(engine="streaming")
print(daily.shape)
print(daily.head(3).with_columns(pl.col("vwap").round(2)))
everything = pd.concat([pd.read_parquet(path) for path in files])
ccc = everything[everything["ticker"] == "CCC"]
print(np.array_equal(ccc.groupby(ccc["time"].dt.date)["size"].sum().to_numpy(), daily["shares"].to_numpy()))
(22, 4)
shape: (3, 4)
┌────────────┬────────┬──────────┬────────┐
│ date       ┆ trades ┆ shares   ┆ vwap   │
│ ---        ┆ ---    ┆ ---      ┆ ---    │
│ date       ┆ u32    ┆ i64      ┆ f64    │
╞════════════╪════════╪══════════╪════════╡
│ 2024-04-01 ┆ 19701  ┆ 9859842  ┆ 410.07 │
│ 2024-04-02 ┆ 20015  ┆ 10014404 ┆ 409.95 │
│ 2024-04-03 ┆ 19994  ┆ 9963103  ┆ 410.03 │
└────────────┴────────┴──────────┴────────┘
True

Your turn

Make one row per date and ticker with the number of trades and the shares, and print the five rows of 1 April. You should see CCC with 19,701 trades and 9,859,842 shares.

Grouping by two keys gives one row per date and ticker.

per_ticker = pl.scan_parquet(files).group_by(pl.col("time").dt.date().alias("date"), "ticker").agg(trades=pl.len(), shares=size.sum()).sort("date", "ticker").collect(engine="streaming")
print(per_ticker.head(5))
shape: (5, 4)
┌────────────┬────────┬────────┬──────────┐
│ date       ┆ ticker ┆ trades ┆ shares   │
│ ---        ┆ ---    ┆ ---    ┆ ---      │
│ date       ┆ str    ┆ u32    ┆ i64      │
╞════════════╪════════╪════════╪══════════╡
│ 2024-04-01 ┆ AAA    ┆ 20321  ┆ 10177534 │
│ 2024-04-01 ┆ BBB    ┆ 20035  ┆ 10016836 │
│ 2024-04-01 ┆ CCC    ┆ 19701  ┆ 9859842  │
│ 2024-04-01 ┆ DDD    ┆ 19939  ┆ 9975466  │
│ 2024-04-01 ┆ EEE    ┆ 20004  ┆ 10023230 │
└────────────┴────────┴────────┴──────────┘