This commit is contained in:
wvr committed 2026-11-26 08:32:04 -06:00
1 parent 3898609a52
commit 1cfbf11176
3003 files changed
+109 -6

No files matched your search

+1
View File
@@ -0,0 +1 @@
npx dukascopy-node -i usatechidxusd -from 2020-01-01 -to now -t m1 -f csv -v -vu units -r 3 -fn nq_proxy_1m
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env python3
"""Price check (free, downloads nothing): CME options-on-futures data needed to estimate dealer gamma.
Two schemas per product: 'statistics' (daily open interest + settlement prices) and 'definition'
(strike, expiry, call/put of every option). Same API key setup as get_futures_1m.py.
export DATABENTO_API_KEY=db-xxxxxxxxxxxxxxxx
python3 options_cost.py # NQ, ES, gold, crude options, 2016 -> latest
python3 options_cost.py --parents NQ.OPT --start 2020-01-01
"""
import argparse, os, sys
import databento as db
import pandas as pd
DATASET = "GLBX.MDP3"
# CME option product codes: NQ / ES equity index options, OG = gold (COMEX), LO = crude (NYMEX)
DEFAULT = ["NQ.OPT", "ES.OPT", "OG.OPT", "LO.OPT"]
p = argparse.ArgumentParser()
p.add_argument("--parents", nargs="+", default=DEFAULT)
p.add_argument("--schemas", nargs="+", default=["statistics", "definition"])
p.add_argument("--start", default="2016-01-01")
p.add_argument("--end", default=None)
a = p.parse_args()
key = os.environ.get("DATABENTO_API_KEY")
if not key:
sys.exit("Set DATABENTO_API_KEY first.")
client = db.Historical(key)
end = a.end
if end is None:
rng = client.metadata.get_dataset_range(dataset=DATASET)
end = rng["end"]
end = pd.Timestamp(end); end = end.tz_localize("UTC") if end.tzinfo is None else end.tz_convert("UTC")
start = pd.Timestamp(a.start, tz="UTC")
print(f"Range {start.date()} -> {end.date()} (cost estimates only, nothing is downloaded or billed)\n")
grand = 0.0
for par in a.parents:
for sch in a.schemas:
params = dict(dataset=DATASET, schema=sch, stype_in="parent", symbols=[par], start=start.isoformat(), end=end.isoformat())
try:
cost = client.metadata.get_cost(**params)
size = client.metadata.get_billable_size(**params)
n = client.metadata.get_record_count(**params)
grand += cost
print(f"{par:8s} {sch:11s} ${cost:9.2f} {size / 1e9:7.2f} GB {n:,} records")
except Exception as e:
print(f"{par:8s} {sch:11s} error: {e}")
print(f"\nTotal estimate: ${grand:,.2f}")
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
"""Free cost estimate (downloads nothing) for opening-window trade data (aggressor side) on CME futures.
Samples ~30 trading days across the range, prices each day's window, and extrapolates to all trading days.
export DATABENTO_API_KEY=db-xxxxxxxx
python3 orderflow_cost.py # NQ, 9:29-9:34 ET, trades + tbbo, 2010-06 -> now
python3 orderflow_cost.py --symbols NQ GC CL --window 09:29 09:34
python3 orderflow_cost.py --symbols GC --window 08:19 08:24
"""
import argparse, os, sys
import databento as db
import pandas as pd
p = argparse.ArgumentParser()
p.add_argument("--symbols", nargs="+", default=["NQ"])
p.add_argument("--window", nargs=2, default=["09:29", "09:34"], help="ET start/end, e.g. 09:29 09:34")
p.add_argument("--schemas", nargs="+", default=["trades", "tbbo"])
p.add_argument("--start", default="2010-06-07")
p.add_argument("--end", default=None)
p.add_argument("--samples", type=int, default=30)
a = p.parse_args()
key = os.environ.get("DATABENTO_API_KEY") or sys.exit("Set DATABENTO_API_KEY first.")
c = db.Historical(key)
end = a.end or str(pd.Timestamp(c.metadata.get_dataset_range(dataset="GLBX.MDP3")["end"]).date())
days = pd.bdate_range(a.start, end) # weekdays (holidays make this a slight overestimate)
idx = [int(i) for i in pd.Series(range(len(days))).quantile([k / (a.samples - 1) for k in range(a.samples)]).round()]
sample = days[idx]
print(f"{len(days):,} weekdays {days[0].date()} -> {days[-1].date()}, window {a.window[0]}-{a.window[1]} ET, {len(sample)} sampled days\n")
total = 0.0
for sym in a.symbols:
for sch in a.schemas:
costs = []
for d in sample:
s = pd.Timestamp(f"{d.date()} {a.window[0]}", tz="America/New_York").tz_convert("UTC")
e = pd.Timestamp(f"{d.date()} {a.window[1]}", tz="America/New_York").tz_convert("UTC")
try:
costs.append(c.metadata.get_cost(dataset="GLBX.MDP3", schema=sch, stype_in="continuous",
symbols=[f"{sym}.v.0"], start=s.isoformat(), end=e.isoformat()))
except Exception as ex:
print(f" {sym} {sch} {d.date()}: {ex}"); continue
if not costs: continue
early, late = sum(costs[: len(costs) // 2]) / max(1, len(costs) // 2), sum(costs[len(costs) // 2:]) / max(1, len(costs) - len(costs) // 2)
est = sum(costs) / len(costs) * len(days); total += est
print(f"{sym:3s} {sch:7s} ~${est:8.2f} for all days (avg ${sum(costs)/len(costs):.4f}/day; earlier years ${early:.4f}, later ${late:.4f})")
print(f"\nEstimated total: ~${total:,.2f} (one request per day when downloading; front month = volume-based continuous contract)")
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env python3
"""Download NQ front-month trades (aggressor side) for a short window each weekday. One request per day,
saved under raw_of/ and skipped on re-run (safe to restart after a timeout). Then builds one CSV.
export DATABENTO_API_KEY=db-xxxxxxxx
python3 orderflow_get.py # NQ, 09:29-09:32 ET, 2010-06-07 -> 2015-01-01 (~$13)
python3 orderflow_get.py --start 2016-01-01 --end 2026-11-21 # later, only if the test passes
"""
import argparse, glob, os, sys, time
import databento as db
import pandas as pd
p = argparse.ArgumentParser()
p.add_argument("--symbol", default="NQ"); p.add_argument("--window", nargs=2, default=["09:29", "09:32"])
p.add_argument("--start", default="2010-06-07"); p.add_argument("--end", default="2015-01-01")
p.add_argument("--yes", action="store_true", help="skip the confirmation prompt")
a = p.parse_args()
key = os.environ.get("DATABENTO_API_KEY") or sys.exit("Set DATABENTO_API_KEY first.")
c = db.Historical(key); os.makedirs("raw_of", exist_ok=True)
days = [d for d in pd.bdate_range(a.start, a.end) if d < pd.Timestamp(a.end)]
todo = [d for d in days if not os.path.exists(f"raw_of/{a.symbol}_{d.date()}.dbn.zst")]
print(f"{len(days)} weekdays, {len(todo)} still to download, window {a.window[0]}-{a.window[1]} ET")
if todo and not a.yes and input("Download (billed by Databento)? [y/N] ").strip().lower() != "y": sys.exit("cancelled")
for k, d in enumerate(todo, 1):
s = pd.Timestamp(f"{d.date()} {a.window[0]}", tz="America/New_York").tz_convert("UTC")
e = pd.Timestamp(f"{d.date()} {a.window[1]}", tz="America/New_York").tz_convert("UTC")
out, tmp = f"raw_of/{a.symbol}_{d.date()}.dbn.zst", f"raw_of/{a.symbol}_{d.date()}.part"
for attempt in range(4):
try:
c.timeseries.get_range(dataset="GLBX.MDP3", schema="trades", stype_in="continuous", symbols=[f"{a.symbol}.v.0"],
start=s.isoformat(), end=e.isoformat(), path=tmp)
os.replace(tmp, out); break
except Exception as ex:
if os.path.exists(tmp): os.remove(tmp)
if attempt == 3: sys.exit(f"stopped at {d.date()} ({ex}); just run the command again to resume")
time.sleep(5 * (attempt + 1))
if k % 50 == 0 or k == len(todo): print(f" {k}/{len(todo)} done", flush=True)
frames = []
for f in sorted(glob.glob(f"raw_of/{a.symbol}_*.dbn.zst")):
if not (a.start <= f.split("_")[-1][:10] < a.end): continue
df = db.DBNStore.from_file(f).to_df()
if len(df): frames.append(df.reset_index()[["ts_event", "price", "size", "side", "instrument_id"]])
X = pd.concat(frames); X["ts_et"] = pd.to_datetime(X.pop("ts_event"), utc=True).dt.tz_convert("America/New_York")
name = f"{a.symbol}_trades_{a.window[0].replace(':','')}-{a.window[1].replace(':','')}_{a.start[:4]}-{str(int(a.end[:4]) - (1 if a.end[5:] == '01-01' else 0))}.csv.gz"
X.to_csv(name, index=False); print(f"wrote {name}: {len(X):,} trades, {X.ts_et.dt.date.nunique()} days")