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.
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.
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.
TipShow answer
Each chunk adds its BBB dollars and shares to two running totals.