#!/usr/bin/env python3 """Download CME futures 1-minute bars (continuous front month) from Databento, one gzipped CSV per market. Setup (one time): 1. Sign up at https://databento.com (new accounts get free historical data credits) 2. Copy your API key from the portal (API Keys page) 3. pip install -U databento pandas Check first (recommended): python3 get_futures_1m.py --cost-only # estimated cost, free, downloads nothing python3 get_futures_1m.py --test # tiny live download (~3 days of NQ, pennies) to prove it works Run (best from your Linux home folder, e.g. ~/trading, not /mnt/c - writing to the Windows drive is slow): export DATABENTO_API_KEY=db-xxxxxxxxxxxxxxxx python3 get_futures_1m.py # NQ ES GC SI, 2015-01-01 -> latest python3 get_futures_1m.py --symbols NQ GC --start 2018-01-01 Downloads in one-year chunks, streamed straight to disk under ./raw/ with a progress line per chunk. Chunks already on disk are skipped, so if it's interrupted, just run it again - finished years are not re-downloaded (and not re-billed). Shows the estimated cost of the remaining chunks before downloading. Output: _1m.csv.gz with columns ts_et (US/Eastern, bar open time), open, high, low, close, volume, instrument_id. instrument_id changes on roll days. Full Globex session kept (overnight included). """ import argparse import os import sys import time import databento as db import pandas as pd DATASET = "GLBX.MDP3" # CME Globex (CME, CBOT, NYMEX, COMEX) SCHEMA = "ohlcv-1m" p = argparse.ArgumentParser() p.add_argument("--symbols", nargs="+", default=["NQ", "ES", "GC", "SI"], help="contract roots (front month rolled by volume), e.g. NQ ES GC SI MNQ") p.add_argument("--start", default="2015-01-01") p.add_argument("--end", default=None, help="exclusive end date; default = latest available") p.add_argument("-y", "--yes", action="store_true", help="skip the cost confirmation") p.add_argument("--cost-only", action="store_true", help="print the estimated cost and exit (free)") p.add_argument("--test", action="store_true", help="live smoke test: download ~3 days of NQ (costs pennies), print it, change nothing else") a = p.parse_args() key = os.environ.get("DATABENTO_API_KEY") if not key: sys.exit("Set DATABENTO_API_KEY first (see the top of this file).") client = db.Historical(key) print(f"databento {db.__version__}; contacting Databento (step 1/3: dataset range)...", flush=True) end = a.end if end is None: rng = client.metadata.get_dataset_range(dataset=DATASET) end = (rng.get("schema", {}).get(SCHEMA, {}) or {}).get("end") or rng["end"] end_ts = pd.Timestamp(end) end_ts = end_ts.tz_localize("UTC") if end_ts.tzinfo is None else end_ts.tz_convert("UTC") if a.test: params = dict(dataset=DATASET, schema=SCHEMA, stype_in="continuous", symbols=["NQ.v.0"], start=(end_ts - pd.Timedelta(days=3)).isoformat(), end=end_ts.isoformat()) print("step 2/3: cost estimate...", flush=True) print(f"Smoke test: NQ, last 3 days, estimated ${client.metadata.get_cost(**params):.4f}", flush=True) print("step 3/3: downloading...", flush=True) path = "smoke_test.dbn.zst" if os.path.exists(path): os.remove(path) df = client.timeseries.get_range(**params, path=path).to_df(tz="America/New_York") print(df[["open", "high", "low", "close", "volume", "instrument_id"]].tail(5).to_string()) print(f"OK: {len(df):,} bars received. The full download should work - run without --test.") sys.exit(0) # one-year chunks edges = [pd.Timestamp(f"{y}-01-01", tz="UTC") for y in range(pd.Timestamp(a.start).year, end_ts.year + 1)] edges[0] = max(edges[0], pd.Timestamp(a.start, tz="UTC")) edges.append(end_ts) os.makedirs("raw", exist_ok=True) print("step 2/3: cost estimates...", flush=True) chunks, total = [], 0.0 for root in a.symbols: root = root.upper() for s, e in zip(edges[:-1], edges[1:]): if s >= e: continue path = os.path.join("raw", f"{root}_{s.year}.dbn.zst") if os.path.exists(path) and os.path.getsize(path) > 0: continue params = dict(dataset=DATASET, schema=SCHEMA, stype_in="continuous", symbols=[f"{root}.v.0"], start=s.isoformat(), end=e.isoformat()) total += client.metadata.get_cost(**params) chunks.append((root, s.year, path, params)) print(f"{len(chunks)} chunks to download, estimated ${total:.2f} (already-downloaded years are skipped)") if a.cost_only: sys.exit(0) if chunks and not a.yes and input("Download? [y/N] ").strip().lower() != "y": sys.exit("Cancelled.") for root, year, path, params in chunks: t0 = time.time() print(f" {root} {year} ... ", end="", flush=True) tmp = path + ".part" if os.path.exists(tmp): # leftover from an interrupted run: the client refuses to os.remove(tmp) # overwrite, which would fail AFTER the (billed) request client.timeseries.get_range(**params, path=tmp) os.replace(tmp, path) # only complete chunks get the final name print(f"{os.path.getsize(path) / 1e6:.1f} MB in {time.time() - t0:.0f}s", flush=True) for root in [s.upper() for s in a.symbols]: files = sorted(f for f in os.listdir("raw") if f.startswith(root + "_") and f.endswith(".dbn.zst")) if not files: continue print(f"Building {root}_1m.csv.gz from {len(files)} chunks...", flush=True) df = pd.concat([db.DBNStore.from_file(os.path.join("raw", f)).to_df(tz="America/New_York") for f in files]) df = df[~df.index.duplicated()].sort_index()[["open", "high", "low", "close", "volume", "instrument_id"]] df.index.name = "ts_et" out = f"{root}_1m.csv.gz" df.to_csv(out, float_format="%.10g") rolls = int((df["instrument_id"].diff().fillna(0) != 0).sum()) print(f" wrote {out}: {len(df):,} bars, {df.index.normalize().nunique()} days, " f"{df.index[0]} -> {df.index[-1]}, {rolls} rolls") print("\nDone. Attach the .csv.gz files in the chat (NQ first if you can only send one at a time).")