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.
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.
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.