How should I organise many days of data on disk?

Save a month of trades as one Parquet folder per day, read one week by filtering on the folder names, and add a new day without rewriting the old ones.

After this lesson, you can read one week of trades from a month of data and add a new day by writing a single folder.

How do I save a month as one folder per day?

trades.to_parquet(by_day, partition_cols=["day"]) writes one folder per trading day, such as day=2024-04-01, each with a Parquet file of that day’s trades, and this way of dividing a table is called partitioning. The 2,200,000 made-up trades of April 2024 fill 22 daily folders of 100,000 trades each.

The trades have a day, a ticker from AAA to EEE, a size in shares and a price in dollars per share, as in the lesson on Parquet files. The file inside a folder holds the other columns, and the reader takes the day from the folder’s name. existing_data_behavior="delete_matching" replaces a day’s folder when that day is written again, so a repeated write of a complete day does not count its trades twice, and a day is written only when its data are complete.

Code: the made-up trades
import shutil
from pathlib import Path

import numpy as np
import pandas as pd

demo = Path("partitions_demo")
shutil.rmtree(demo, ignore_errors=True)
demo.mkdir()
rng = np.random.default_rng(12)
price_level = {"AAA": 170.0, "BBB": 180.0, "CCC": 410.0, "DDD": 880.0, "EEE": 170.0}
day_texts = pd.bdate_range("2024-04-01", "2024-04-30").strftime("%Y-%m-%d")
n = 100_000 * len(day_texts)
trades = pd.DataFrame({"day": np.repeat(day_texts, 100_000), "ticker": rng.choice(list(price_level), n), "size": rng.integers(1, 1_000, n)})
trades["price"] = (trades["ticker"].map(price_level) * rng.normal(1, 0.01, n)).round(2)

The following box writes the daily folders and checks that every day holds 100,000 trades.

by_day = demo / "by_day"
trades.to_parquet(by_day, partition_cols=["day"], index=False, existing_data_behavior="delete_matching")
day_folders = sorted(path.name for path in by_day.iterdir())
print(len(day_folders), day_folders[:2])
print(pd.read_parquet(by_day, columns=["day"]).groupby("day", observed=True).size().eq(100_000).all())
22 ['day=2024-04-01', 'day=2024-04-02']
True

How do I read only one week?

pd.read_parquet(by_day, filters=week) with week = [("day", ">=", "2024-04-08"), ("day", "<=", "2024-04-12")] reads only the folders of 8 to 12 April, 500,000 trades, and skips the other 17 days by their names. The day comes back as a category, which pd.to_datetime turns into dates.

The two conditions must both hold, and dates written as year-month-day sort in calendar order, so the comparisons work on the text. A partition should still hold many rows, because opening a file costs time. A folder per day, ticker and minute would give 22 × 5 × 390 = 42,900 folders of about 51 trades, and the same week would open 9,750 files.

The following box reads the week.

week = [("day", ">=", "2024-04-08"), ("day", "<=", "2024-04-12")]
one_week = pd.read_parquet(by_day, filters=week)
print(len(one_week), one_week["day"].dtype, one_week["day"].unique().tolist())
500000 category ['2024-04-08', '2024-04-09', '2024-04-10', '2024-04-11', '2024-04-12']

Your turn

Add 100,000 made-up trades of 1 May 2024 to by_day, then print the number of daily folders and the number of rows read for 1 May. You should see 23 and 100,000.

Only the new day’s folder is written.

may = pd.DataFrame({"day": "2024-05-01", "ticker": rng.choice(list(price_level), 100_000), "size": rng.integers(1, 1_000, 100_000)})
may["price"] = (may["ticker"].map(price_level) * rng.normal(1, 0.01, 100_000)).round(2)
may.to_parquet(by_day, partition_cols=["day"], index=False, existing_data_behavior="delete_matching")
print(len(list(by_day.iterdir())), len(pd.read_parquet(by_day, columns=["day"], filters=[("day", "==", "2024-05-01")])))
23 100000