Querying Parquet Futures Data in Python with pandas, polars, and DuckDB
Select tick columns with pandas, polars, or DuckDB, keep timestamp filters in UTC, avoid accidental full-history scans, and compare resampled output with the published bars.
Start with three columns and one file
A Parquet reader can use the separate column layout and schema metadata to retrieve only requested fields. If the calculation concerns price changes, timestamp and price may be sufficient; reading every tick field spends memory on data you never use. Begin with a known file, examine its schema, and postpone any directory-wide scan.
The pandas reader accepts both a column projection and a filter:
import pandas as pd
file = "ES_2024_ticks.parquet"
ticks = pd.read_parquet(
file,
columns=["ts", "price", "volume"],
filters=[("ts", ">=", pd.Timestamp("2024-03-01", tz="UTC"))],
)
print(ticks.dtypes)
print(ticks.head())
The filename is illustrative. Selecting columns reduces memory use, while the filter can also reduce the rows read if predicate pushdown works with the chosen reader and file layout. Parquet cannot execute every Python expression internally; use simple pushdown predicates and leave complex expressions for post-read processing.
Pointing read_parquet at years of ticks before checking one representative file invites an expensive mistake. Inspect the row count, nulls, and timestamp range before launching the long query. Available derived datasets and field definitions are listed in the dataset documentation.
PyArrow can read the footer for a quick preflight, exposing row and column counts without materializing the data:
import pyarrow.parquet as pq
metadata = pq.ParquetFile(file).metadata
print(metadata.num_rows, metadata.num_columns)
Those counts can reveal an unexpected schema or wrong file before a costly scan, though they say nothing about the validity of individual values. You still have to inspect nulls, UTC boundaries, and actual sample rows.
A directory path can silently widen the query
Point a directory reader at a path and it may combine every matching Parquet file beneath it into one dataset. Restricting that path to one year can be handy; doing it at the root of a full market history can be painful. When two periods are all you need, pass their filenames:
files = [
"ticks/ES/year=2023/data.parquet",
"ticks/ES/year=2024/data.parquet",
]
ticks = pd.read_parquet(files, columns=["ts", "price", "volume"])
The example paths use year partitions, but your filenames should match the derived dataset you downloaded. A recursive glob followed by filtering in pandas does not save memory when the read has already loaded every row. The allocation has happened by then.
With DuckDB, the same files can be queried directly instead of first assembling a pandas DataFrame:
import duckdb
con = duckdb.connect()
result = con.execute('''
SELECT ts, price, volume
FROM read_parquet([
'ticks/ES/year=2023/data.parquet',
'ticks/ES/year=2024/data.parquet'
])
WHERE ts >= TIMESTAMPTZ '2024-03-01 00:00:00+00'
AND ts < TIMESTAMPTZ '2024-04-01 00:00:00+00'
''').df()
The interval contains March 1 and stops before April 1. Half-open bounds avoid duplicate rows at the edges and remove the need to guess a file’s final timestamp. Use the same construction for a single day or session.
Keep UTC for computation and Chicago for display
Derived per-contract ticks have a single UTC ts field. Between session definitions and daylight-saving transitions, the calendar is complicated enough without adding unintended timezone conversions. Keep filtering and sorting in UTC; convert only when presenting the result.
ticks["ts"] = pd.to_datetime(ticks["ts"], utc=True)
ticks = ticks.sort_values("ts")
chicago_time = ticks["ts"].dt.tz_convert("America/Chicago")
Converting to Chicago changes the displayed timezone, not the instants represented. Use tz_localize("UTC") only for naive timestamps and tz_convert for values that already carry a timezone. Confusing the two operations can shift timestamps or produce an exception.
Check the dtypes that come back. For per-contract ticks, price has type float64 and volume has type uint32. The bid_sz and ask_sz fields report executed volume at the bid and ask rather than resting book sizes; open interest is not included. Continuous ticks also contain price_raw and back_adjustment, where price = price_raw + back_adjustment.
A downcast trades information or schema fidelity for a smaller footprint: float32 prices have less precision, while converting volume to a signed type alters the schema. Keep the original files, measure what you actually save, and document each conversion in the analysis.
Bound a lazy polars query before collecting it
polars can build a lazy description of the query without executing it immediately. Specify the projection, date bounds, and sort in that description; collect comes after those limits are in place:
import polars as pl
query = (
pl.scan_parquet("ticks/ES/year=2024/data.parquet")
.filter(
(pl.col("ts") >= pl.datetime(2024, 3, 1, time_zone="UTC"))
& (pl.col("ts") < pl.datetime(2024, 4, 1, time_zone="UTC"))
)
.select("ts", "price", "volume")
.sort("ts")
)
march = query.collect(streaming=True)
The streaming API differs among polars releases, so check what your installed version accepts. Lazy execution alone does not cap memory. High-cardinality grouping or a large sort can still exhaust it, although the optimizer can push projections and filters down into the scan before materializing results.
Use explain to see whether those operations sit close to the scan in the plan. Then measure rows returned and process memory. The plan alone cannot tell you whether the query fits the machine.
Disk compression tells you little about RAM use
On-disk Parquet compression makes the download size a poor proxy for memory consumption. Start with selected rows multiplied by in-memory bytes per row, then budget for indexes, Python objects, expression intermediates, copies, and sorting. The resulting DataFrame can exceed the sum of its basic dtype sizes.
For a pandas result, ticks.memory_usage(deep=True).sum() estimates memory after the read. Sorting or aggregation may use a larger peak through temporary copies, and this call does not measure that peak. Measuring a successful short window gives you firmer evidence than estimating from a compressed file.
Reduce the input before tuning the engine
- Project only the columns the calculation needs; the others can stay on disk.
- Restrict file paths and timestamp ranges before collection.
- Process one year or session at a time if the algorithm allows it.
- Push aggregation into DuckDB or lazy polars before raw ticks enter Python.
- Leave memory available for the operating system and subsequent feature work.
Daily volume calls for daily aggregates, not millions of ticks pulled into a local group-by. A custom tick signal may instead require bounded periods of tick data. Persist intermediate outputs together with their settings; periods that fit individually need not fit after you join them all.
Partitioned folders still need explicit pruning
A year partition gives you a useful unit to query or rebuild without touching other years. It does not guarantee speed: behavior depends on the reader, and predicates on other columns still require relevant pages to be inspected. A selection of 20 year folders still scans 20 years.
Name the required year directories and retain timestamp predicates as well. The paths determine which files open; the predicates reduce rows inside those files. When a single partition contains the answer, scanning recursively from the root is wasted work.
Hive-style partition columns may be inferred from directory names by some readers. Inspect the inferred year dtype and compare it with ts. Because directory labels are metadata, check minimum and maximum timestamps for every file or partition and investigate any row filed outside its expected year.
Resampling needs a calendar, not just a frequency
The frequency string alone leaves a bar under-specified. Timezone, bucket origin, label side, closed side, and aggregation rule all matter. In a standard OHLCV aggregation, open is the first price, high is the maximum, low is the minimum, close is the last price, and volume is summed; in this dataset, trade_count is also summed from the input records. Sort on UTC timestamps first, and treat duplicate events so their order is not changed by accident.
The intraday derived bars in this dataset use epoch-aligned UTC buckets. Available intervals are 10s, 1m, 2m, 5m, 30m, 1h, 4h and 1D. Buckets with no observations are omitted; an absent row can therefore indicate no trades. Daily bars track Chicago’s 17:00 session across daylight-saving changes instead of grouping from midnight to midnight in UTC.
Because these bars originate in back-adjusted continuous ticks, independently resampled unadjusted per-contract ticks can differ throughout older adjusted segments, not only at rolls. If you resample continuous input, verify price = price_raw + back_adjustment before aggregation and retain the same adjustment convention. The guide to tick data and OHLCV bars discusses when existing bars are enough and when you need ticks.
Reproduce the small run before the long one
Record each input’s filename, row count, schema, minimum and maximum UTC timestamps, and null counts. Check after filtering that every returned timestamp falls within the requested bounds. Resampled output also needs invariants: high must be at least open, close, and low, while low must not exceed any of them. Apply sanity checks to volume and trade counts as well.
Pick a short window and reconcile it with the matching derived bars. Matching prices alone are insufficient because bucket edges, omitted empty buckets, and daily session rules can differ behind plausible-looking values. At a roll, verify the adjustment identity and point differences to keep a reference gap from appearing as a return.
Persist the query, file selection, parameters, package versions, and dataset manifest or checksums where available. Record the reader as well; pandas, polars, and DuckDB may read the same Parquet bytes yet differ in timestamp display, integer handling, and execution. In a fresh process, rerun a small golden example and compare its output.
Missing columns, unexpected dtypes, unsorted timestamps, or a surprise file count should halt the job. Put the golden example ahead of the long scan. Its comparison should come back exact and uneventful before you trust the next chart.