How do I total a CSV that is too big to load at once?

Read a large CSV in chunks with read_csv(chunksize=…), keep running totals by ticker, and combine them into the answer for the whole file, with a running sum and count for every mean.

After this lesson, you can total shares, compute mean prices and find volume-weighted prices by ticker when a trade file is too large to read at once.

How do I total shares one chunk at a time?

pd.read_csv(path, chunksize=200_000) returns a reader that hands over the file 200,000 rows at a time, and adding each chunk’s totals by ticker to a running total, total_shares.add(part, fill_value=0), gives the totals of the whole file. AAA’s trades add up to 150,138,189 shares, the same as a full read.

The made-up file holds a million trades of AAA, BBB, CCC, DDD and EEE, with prices in dollars per share and sizes in shares, small enough for a full read to check the chunks. usecols reads only the needed columns, and dtype={"size": "Int64"} keeps the shares as whole numbers that can be missing, so the totals stay exact integers when alignment creates gaps. fill_value=0 counts a ticker missing from one side as zero. The loop holds one or two chunks and five totals in memory, never the whole file.

Code: the made-up trade file
import shutil
from pathlib import Path

import numpy as np
import pandas as pd

demo = Path("csv_chunks_demo")
shutil.rmtree(demo, ignore_errors=True)
demo.mkdir()
trades_file = demo / "trades_million.csv"
rng = np.random.default_rng(8)
price_level = {"AAA": 170.0, "BBB": 180.0, "CCC": 410.0, "DDD": 880.0, "EEE": 170.0}
n = 1_000_000
trades = pd.DataFrame({"ticker": rng.choice(list(price_level), n, p=[0.3, 0.2, 0.2, 0.2, 0.1])})
trades["price"] = (trades["ticker"].map(price_level) * rng.normal(1, 0.01, n)).round(2)
trades["size"] = rng.integers(1, 1_000, n)
trades.to_csv(trades_file, index=False)
del trades

The following box totals the shares in chunks and compares them with a full read.

total_shares = pd.Series(dtype="Int64")
for chunk in pd.read_csv(trades_file, usecols=["ticker", "size"], dtype={"size": "Int64"}, chunksize=200_000):
    total_shares = total_shares.add(chunk.groupby("ticker")["size"].sum(), fill_value=0)
whole = pd.read_csv(trades_file).groupby("ticker")["size"].sum()
print(pd.DataFrame({"chunked": total_shares, "whole": whole}))
print((total_shares.astype("int64") == whole).all())
          chunked      whole
ticker                      
AAA     150138189  150138189
BBB      99850301   99850301
CCC     100123006  100123006
DDD      99852510   99852510
EEE      50244824   50244824
True

Why do means need sums and counts?

A mean across chunks is the sum of all prices divided by their count, so the loop keeps a running sum and a running count per ticker and divides once at the end. DDD’s mean price is 879.9992 dollars, while the mean of the four chunk means gives 879.9847, because the last chunk of 100,000 rows gets the same weight as the full chunks of 300,000.

\[ \bar p = \frac{\sum_c S_c}{\sum_c n_c} \]

Here \(S_c\) is the sum of a ticker’s prices in chunk \(c\) and \(n_c\) their count. .count() counts the prices that are present, and pd.concat(chunk_means, axis=1).mean(axis=1) averages the chunk means for comparison. In a file sorted by date, where prices drift, the gap can be much larger than the 1.46 cents here.

The following box computes the means both ways and compares them with a full read.

price_sums = pd.Series(dtype="float64")
price_counts = pd.Series(dtype="int64")
chunk_means = []
for chunk in pd.read_csv(trades_file, usecols=["ticker", "price"], chunksize=300_000):
    prices = chunk.groupby("ticker")["price"]
    price_sums = price_sums.add(prices.sum(), fill_value=0)
    price_counts = price_counts.add(prices.count(), fill_value=0)
    chunk_means.append(prices.mean())
mean_prices = pd.DataFrame({
    "sum_over_count": price_sums / price_counts,
    "mean_of_chunk_means": pd.concat(chunk_means, axis=1).mean(axis=1),
    "whole": pd.read_csv(trades_file).groupby("ticker")["price"].mean(),
})
print(mean_prices.round(4))
print(f"{(mean_prices['mean_of_chunk_means'] - mean_prices['whole']).abs().max():.4f}")
        sum_over_count  mean_of_chunk_means     whole
ticker                                               
AAA           169.9945             169.9949  169.9945
BBB           180.0007             180.0004  180.0007
CCC           409.9831             409.9815  409.9831
DDD           879.9992             879.9847  879.9992
EEE           169.9921             169.9914  169.9921
0.0146

Your turn

Read the file in chunks of 250,000 rows and print BBB’s volume-weighted average price, its traded dollars divided by its shares. You should see BBB 180.00.

Each chunk adds its BBB dollars and shares to two running totals.

dollars, shares = 0.0, 0
for chunk in pd.read_csv(trades_file, usecols=["ticker", "price", "size"], chunksize=250_000):
    bbb = chunk[(chunk["ticker"] == "BBB") & chunk["price"].notna()]
    dollars += (bbb["price"] * bbb["size"]).sum()
    shares += bbb["size"].sum()
print(f"BBB {dollars / shares:.2f}")
BBB 180.00