This commit is contained in:
wvr committed 2026-11-21 20:00:22 -06:00
1 parent 421050292d
commit ce36cba8e9
2978 files changed
+35317 -85

No files matched your search

+113
View File
@@ -0,0 +1,113 @@
"""Step 1: for every market x period x entry clock, one row per day with features known at the entry bar's close and the bracket
P&L for long and short (eval / funded bracket, realistic / harsh fills). Output: out/frames/{period}_{market}_{clock}.pkl"""
import os, sys, time, numpy as np, pandas as pd
import multiprocessing as mp
import engine as EN
S = {}; VF = None; CAL = None; TD = None
def load_all():
global VF, CAL, TD
for per, ms in EN.MARKETS.items():
for m in ms: S[(per, m)] = EN.Sessions(m, per)
aux = os.path.join(EN.DATA, "aux")
def rd(f, col):
x = pd.read_csv(os.path.join(aux, f)); x.columns = [c.strip().upper() for c in x.columns]
x["D"] = pd.to_datetime(x["DATE"], errors="coerce"); return x.dropna(subset=["D"]).set_index("D")[col].astype(float).sort_index()
V = pd.DataFrame(dict(vix=rd("VIX.csv", "CLOSE"), vix9d=rd("VIX9D.csv", "CLOSE"), vix3m=rd("VIX3M.csv", "CLOSE"), gvz=rd("GVZ.csv", "GVZ"), ovx=rd("OVX.csv", "OVX")))
x = pd.read_csv(os.path.join(aux, "DIX.csv"), parse_dates=["date"]).set_index("date").sort_index(); V = V.join(x[["dix", "gex"]], how="outer").sort_index()
F = pd.DataFrame(index=V.index)
F["vix"] = V.vix; F["vix_d1"] = np.log(V.vix).diff(); F["vix_d5"] = np.log(V.vix).diff(5); F["vix_ts"] = V.vix / V.vix3m; F["vix9_ratio"] = V.vix9d / V.vix
F["gvz"] = V.gvz; F["gvz_d1"] = np.log(V.gvz).diff(); F["ovx"] = V.ovx; F["ovx_d1"] = np.log(V.ovx).diff()
F["dix"] = V.dix; F["dix_d1"] = V.dix.diff(); F["gex_z"] = (V.gex - V.gex.rolling(250, min_periods=60).mean()) / V.gex.rolling(250, min_periods=60).std()
VF = F.ffill(limit=3)
CAL = pd.read_csv(os.path.join(aux, "calendar.csv"), parse_dates=["d"]); CAL["d"] = CAL.d.values.astype("datetime64[D]"); CAL = CAL.set_index("d")
TD = CAL.index.values
def per_day_stats(s):
"""Session-level arrays used for prior-session features."""
n = len(s.dates); R = np.full(n, np.nan); HI = np.full(n, np.nan); LO = np.full(n, np.nan); CL = np.full(n, np.nan)
VW = np.full(n, np.nan); TH = np.full(n, np.nan); TL = np.full(n, np.nan)
for i in range(n):
sl = s.day(i); o, h, l, c, v, t = s.o[sl], s.h[sl], s.l[sl], s.c[sl], s.v[sl], s.t[sl]
R[i] = np.log(c[-1] / o[0]); HI[i], LO[i], CL[i] = h.max(), l.min(), c[-1]
typ = (h + l + c) / 3; VW[i] = (typ * v).sum() / max(v.sum(), 1); TH[i] = t[np.argmax(h)] / 1440; TL[i] = t[np.argmin(l)] / 1440
return dict(R=R, HI=HI, LO=LO, CL=CL, VW=VW, TH=TH, TL=TL)
def price_at(s, i, k):
"""Close of the last bar at or before minute k (since 18:00) in session i; None if no bar within 5 minutes."""
sl = s.day(i); t = s.t[sl]; j = np.searchsorted(t, k, side="right") - 1
if j < 0 or t[j] < k - 5: return None, None
return s.c[sl][j], j
def build(task):
per, m, clock = task
out_f = os.path.join(EN.OUT, "frames", f"{per}_{m}_{clock.replace(':', '')}.pkl")
if os.path.exists(out_f): return out_f, -1
s = S[(per, m)]; k = EN.mins(clock); P = per_day_stats(s); n = len(s.dates)
others = [x for x in EN.MARKETS[per] if x != m]
vol30 = np.full(n, np.nan); volS = np.full(n, np.nan); rows = []
for i in range(n):
sl = s.day(i); t = s.t[sl]; o, h, l, c, v = s.o[sl], s.h[sl], s.l[sl], s.c[sl], s.v[sl]
j = np.searchsorted(t, k, side="right") - 1
if j < 0 or t[j] != k: continue # the clock bar itself must exist (entry at its close)
vol30[i] = v[(t > k - 30) & (t <= k)].sum(); volS[i] = v[:j + 1].sum()
if j >= len(t) - 2: continue
d = s.dates[i]; A = s.atr[i]; p = c[j]
f = dict(d=d, i=i)
for br, (st, tg) in EN.BRACKETS.items():
for hz, harsh in (("", False), ("_h", True)):
for side, nm in ((1, "up"), (-1, "dn")):
f[f"{br}{hz}_{nm}"] = EN.trade(m, o[j + 1:], h[j + 1:], l[j + 1:], c[j + 1:], p, A, side, st, tg, harsh)
f["r_on"] = np.log(p / o[0])
hh, ll = h[:j + 1].max(), l[:j + 1].min(); f["on_rng_atr"] = (hh - ll) / A; f["on_loc"] = (p - ll) / (hh - ll) if hh > ll else 0.5
f["dist_on_high"] = (p - hh) / A; f["dist_on_low"] = (p - ll) / A
for K in (5, 15, 30, 60, 120):
jj = np.searchsorted(t, k - K, side="right") - 1; f[f"r_last{K}"] = np.log(p / c[jj]) if jj >= 0 else np.nan
rg = h[j] - l[j]; f["bar_body"] = (c[j] - o[j]) / rg if rg > 0 else 0.0; f["bar_loc"] = (c[j] - l[j]) / rg if rg > 0 else 0.5; f["bar_rng_atr"] = rg / A
if i > 0 and (d - s.dates[i - 1]).astype(int) <= 4:
q = i - 1; f["r_gap"] = np.log(p / P["CL"][q]); f["prev_rng_atr"] = (P["HI"][q] - P["LO"][q]) / A
f["prev_loc"] = (P["CL"][q] - P["LO"][q]) / max(P["HI"][q] - P["LO"][q], 1e-12)
f["dist_prev_high"] = (p - P["HI"][q]) / A; f["dist_prev_low"] = (p - P["LO"][q]) / A; f["dist_prev_vwap"] = (p - P["VW"][q]) / A
f["prev_t_high"], f["prev_t_low"] = P["TH"][q], P["TL"][q]
pq, _ = price_at(s, q, k); f["prev_post_clock"] = np.log(P["CL"][q] / pq) if pq else np.nan
for K in (1, 2, 3, 4, 5): f[f"r_prev{K}"] = P["R"][i - K] if i - K >= 0 else np.nan
sd = np.nanstd(P["R"][max(0, i - 20):i]) if i >= 15 else np.nan
for K in (2, 3, 5, 10, 20): f[f"z_sum{K}"] = np.nansum(P["R"][max(0, i - K):i]) / (sd * np.sqrt(K)) if i >= K and sd > 0 else np.nan
if i >= 30: f["atr_regime"] = A / np.mean(s.atr[max(0, i - 60):i])
if i >= 5: f["dist_wk_high"] = (p - np.max(P["HI"][i - 5:i])) / A; f["dist_wk_low"] = (p - np.min(P["LO"][i - 5:i])) / A
f["dow"] = int((d.astype("datetime64[D]").view("int64") - 4) % 7)
dd = pd.Timestamp(d); f["month"] = dd.month; f["opex"] = int(dd.weekday() == 4 and 15 <= dd.day <= 21)
if d in CAL.index:
f["TOM"], f["PH"], f["FOMC"] = (int(CAL.at[d, x]) for x in ("TOM", "PH", "FOMC"))
a = np.searchsorted(TD, d); mo = dd.month; e = a
while e + 1 < len(TD) and pd.Timestamp(TD[e + 1]).month == mo: e += 1
f["days_to_month_end"] = e - a
kk = VF.index.searchsorted(dd) - 1
if kk >= 0: f.update(VF.iloc[kk].to_dict())
for x in others:
so = S[(per, x)]; io = so.idx.get(d)
if io is None: continue
px, _ = price_at(so, io, k)
if px is None: continue
f[f"x_{x}_on"] = np.log(px / so.o[so.day(io)][0])
if io > 0: f[f"x_{x}_gap"] = np.log(px / so.c[so.day(io - 1)][-1]); f[f"x_{x}_prev"] = np.log(so.c[so.day(io - 1)][-1] / so.o[so.day(io - 1)][0])
rows.append(f)
X = pd.DataFrame(rows)
if len(X):
med30 = pd.Series(vol30).shift(1).rolling(20, min_periods=10).median(); medS = pd.Series(volS).shift(1).rolling(20, min_periods=10).median()
X["vol30_rel"] = vol30[X.i.values] / med30.values[X.i.values]; X["volS_rel"] = volS[X.i.values] / medS.values[X.i.values]
os.makedirs(os.path.dirname(out_f), exist_ok=True); X.to_pickle(out_f + ".tmp"); os.replace(out_f + ".tmp", out_f)
return out_f, len(X)
if __name__ == "__main__":
quick = "--quick" in sys.argv
load_all()
tasks = [(per, m, ck) for per, ms in EN.MARKETS.items() for m in ms for ck in EN.CLOCKS]
if quick: tasks = [t for t in tasks if t[1] in ("NQ", "GC") and t[2] in ("08:30", "09:30", "02:00")]
workers = int(os.environ.get("WORKERS", os.cpu_count()))
print(f"step 1: {len(tasks)} market/period/clock frames on {workers} workers"); t0 = time.time()
with mp.get_context("fork").Pool(workers) as pool:
for k, (f, nrows) in enumerate(pool.imap_unordered(build, tasks), 1):
if k % 20 == 0 or k == len(tasks) or quick: print(f" {k}/{len(tasks)} {os.path.basename(f)} rows {nrows if nrows >= 0 else 'cached'} ({time.time() - t0:.0f}s)", flush=True)
print("step 1 done")