asf
This commit is contained in:
1 parent
3898609a52
commit
1cfbf11176
3003 files changed
+109
-6
No files matched your search
@@ -0,0 +1,6 @@
|
||||
pip install --user duckdb python3-zstd databento
|
||||
|
||||
#### pip3 install --user --break-system-packages databento
|
||||
|
||||
python csv_to_parquet.py "raw/*.gz" data
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Convert 1-minute futures bar CSVs (Databento-style continuous contracts) to Parquet.
|
||||
|
||||
Input columns : ts_et,open,high,low,close,volume,instrument_id
|
||||
ts_et like "2015-01-01 18:00:00-05:00" (bar OPEN time, US/Eastern with offset)
|
||||
Input files : e.g. NQ_1m_2015-2026_csv.gz, ES_1m_....csv (symbol = text before the first "_")
|
||||
|
||||
Output : <out>/symbol=NQ/year=2015/*.parquet (year = session year)
|
||||
|
||||
Columns written
|
||||
ts TIMESTAMPTZ bar open time (UTC internally; displays in your session TZ)
|
||||
ts_et TIMESTAMP same instant as naive US/Eastern wall-clock time
|
||||
session_date DATE CME trading date: the 18:00 ET Sunday bar belongs to Monday's session
|
||||
open/high/low/close/volume UNADJUSTED prices of the contract trading at that moment
|
||||
instrument_id BIGINT contract id; changes at each roll
|
||||
is_roll BOOLEAN first bar of a new contract -> the bar-to-bar return INTO this bar is
|
||||
a contract switch, not a market move. Exclude it from return calcs.
|
||||
roll_gap DOUBLE on roll bars: new open - old close (approx. calendar spread), else 0
|
||||
adj_add DOUBLE back-adjustment, additive: adj_price = price + adj_add
|
||||
adj_mult DOUBLE back-adjustment, multiplicative: adj_price = price * adj_mult
|
||||
(both = 0 / 1 on the latest contract; they change when you append data)
|
||||
|
||||
Usage
|
||||
pip install duckdb
|
||||
python csv_to_parquet.py "raw/*.gz" data
|
||||
python csv_to_parquet.py "raw/*.csv" data
|
||||
"""
|
||||
import argparse
|
||||
import time
|
||||
|
||||
import duckdb
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("inputs", help='glob of CSV / CSV.gz files, e.g. "raw/*_1m_*.gz"')
|
||||
ap.add_argument("out", help="output directory for partitioned Parquet")
|
||||
args = ap.parse_args()
|
||||
|
||||
t0 = time.time()
|
||||
con = duckdb.connect()
|
||||
con.sql("SET TimeZone = 'America/New_York'") # makes ts::TIMESTAMP = ET wall clock
|
||||
|
||||
con.sql(f"""
|
||||
CREATE TEMP TABLE bars AS
|
||||
SELECT
|
||||
split_part(parse_filename(filename), '_', 1) AS symbol,
|
||||
CAST(ts_et AS TIMESTAMPTZ) AS ts,
|
||||
open, high, low, close, volume, instrument_id
|
||||
FROM read_csv('{args.inputs}', header = true, filename = true,
|
||||
columns = {{'ts_et':'VARCHAR','open':'DOUBLE','high':'DOUBLE','low':'DOUBLE',
|
||||
'close':'DOUBLE','volume':'BIGINT','instrument_id':'BIGINT'}})
|
||||
""")
|
||||
|
||||
# Data checks that should never fail; stop rather than write bad data.
|
||||
dup = con.sql("SELECT count(*) FROM (SELECT 1 FROM bars GROUP BY symbol, ts HAVING count(*) > 1)").fetchall()[0][0]
|
||||
bad = con.sql("""SELECT count(*) FROM bars WHERE high < greatest(open, close) OR low > least(open, close)
|
||||
OR open <= 0 OR volume < 0""").fetchall()[0][0]
|
||||
if dup or bad:
|
||||
raise SystemExit(f"Data check failed: {dup} duplicate timestamps, {bad} invalid OHLC rows")
|
||||
|
||||
con.sql("""
|
||||
CREATE TEMP TABLE out AS
|
||||
WITH r AS (
|
||||
SELECT *,
|
||||
ts::TIMESTAMP AS ts_et,
|
||||
CAST(ts::TIMESTAMP + INTERVAL 6 HOUR AS DATE) AS session_date,
|
||||
coalesce(instrument_id <> lag(instrument_id) OVER w, false) AS is_roll,
|
||||
lag(close) OVER w AS prev_close
|
||||
FROM bars
|
||||
WINDOW w AS (PARTITION BY symbol ORDER BY ts)
|
||||
), g AS (
|
||||
SELECT *,
|
||||
CASE WHEN is_roll THEN open - prev_close ELSE 0 END AS roll_gap,
|
||||
CASE WHEN is_roll THEN ln(open / prev_close) ELSE 0 END AS roll_lr
|
||||
FROM r
|
||||
)
|
||||
SELECT symbol, ts, ts_et, session_date, year(session_date) AS year,
|
||||
open, high, low, close, volume, instrument_id, is_roll, roll_gap,
|
||||
coalesce(sum(roll_gap) OVER f, 0) AS adj_add,
|
||||
exp(coalesce(sum(roll_lr) OVER f, 0)) AS adj_mult
|
||||
FROM g
|
||||
WINDOW f AS (PARTITION BY symbol ORDER BY ts ROWS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING)
|
||||
ORDER BY symbol, ts
|
||||
""")
|
||||
|
||||
con.sql(f"""
|
||||
COPY out TO '{args.out}'
|
||||
(FORMAT parquet, PARTITION_BY (symbol, year), COMPRESSION zstd, OVERWRITE_OR_IGNORE)
|
||||
""")
|
||||
|
||||
print(con.sql("""
|
||||
SELECT symbol, count(*) AS bars, min(ts_et) AS first_bar_et, max(ts_et) AS last_bar_et,
|
||||
count(DISTINCT session_date) AS sessions, sum(is_roll::INT) AS rolls,
|
||||
round(arg_min(adj_mult, ts), 4) AS first_bar_adj_mult
|
||||
FROM out GROUP BY symbol ORDER BY symbol
|
||||
"""))
|
||||
print(f"done in {time.time() - t0:.1f}s -> {args.out}/")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,123 @@
|
||||
#!/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: <ROOT>_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).")
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
|
||||
export DATABENTO_API_KEY="$(cat api.key)"
|
||||
|
||||
Reference in new issue
Block a user