"""Descriptive first-touch timing; no trading execution or profit assumed.""" import argparse import hashlib import json from pathlib import Path import zipfile import numpy as np import pandas as pd CUTS=[1,2,5,10,15,30,60,120,240,360,600,930,1380] BINS=[0,1,5,15,30,60,120,360,930,1380] def fingerprint(path): h=hashlib.sha256() with path.open('rb') as f: for chunk in iter(lambda:f.read(1048576),b''):h.update(chunk) return h.hexdigest() def first_touch(g,target,gap): hits=g.low.le(target) if gap>0 else g.high.ge(target) return int(np.flatnonzero(hits.to_numpy())[0]) if hits.any() else None def summarize(rows): n=len(rows);times=[r['minute'] for r in rows];on=sum(t is not None and t<930 for t in times) return {'events':n,'overnight_touches':on, 'cumulative':[{'before_minute':m,'touches':sum(t is not None and t=m for t in times), 'later_overnight_touches':sum(t is not None and m<=t<930 for t in times), 'pct_remaining':100*sum(t is not None and m<=t<930 for t in times)/sum(t is None or t>=m for t in times) if any(t is None or t>=m for t in times) else None} for m in [1,5,15,30,60,120,360]]} def calculate(source): cols=['timestamp_utc','session_date','open','high','low','close','underlying_contract','data_condition','is_complete','roll_transition'] with zipfile.ZipFile(source) as z: names=[n for n in z.namelist() if n.lower().endswith('.csv')] if len(names)!=1:raise ValueError('Expected one CSV.') raw=pd.read_csv(z.open(names[0]),usecols=cols,parse_dates=['timestamp_utc']) assert raw.timestamp_utc.is_monotonic_increasing and not raw.timestamp_utc.duplicated().any() assert raw.is_complete.eq(True).all() assert np.isfinite(raw[['open','high','low','close']].to_numpy()).all() assert raw[['open','high','low','close']].gt(0).all().all() assert (raw.low.le(raw[['open','close','high']].min(axis=1)) & raw.high.ge(raw[['open','close','low']].max(axis=1))).all() local=raw.timestamp_utc.dt.tz_convert('America/New_York') raw['date']=local.dt.strftime('%Y-%m-%d');raw['clock']=local.dt.hour*60+local.dt.minute raw['session_date']=raw.session_date.astype(str) raw['bad']=raw.data_condition.eq('degraded') | raw.roll_transition.astype(str).str.lower().eq('true') closes=raw.loc[raw.clock.eq(1019)].set_index('date');assert not closes.index.duplicated().any() groups={day:g for day,g in raw.groupby('session_date',sort=True)} previous={day:prev for prev,day in zip(groups,list(groups)[1:])} main=[];old=[];overnight=[];prior_degraded={} exclusions={k:0 for k in ['missing_required_close','target_contract_change','missing_or_misaligned_full_day','flagged_or_mixed_contract_full_day','zero_gap']} candidates=0 for day,g in groups.items(): entries=g.loc[g.clock.eq(1080)] if not len(entries):continue assert len(entries)==1;candidates+=1;a=entries.iloc[0] start=a.timestamp_utc;et=start.tz_convert('America/New_York') assert et.weekday() in [0,1,2,3,6] assert (et+pd.DateOffset(days=1)).strftime('%Y-%m-%d')==day path=g.loc[(g.timestamp_utc>=start)&(g.timestamp_utc=10]), ('first_year',[r for r in rows if r['date']<'2025-08-29']), ('second_year',[r for r in rows if r['date']>='2025-08-29'])]}, 'overlap':{'main_shared_with_400_overnight':len(set(r['date'] for r in rows)&set(r['date'] for r in on)), 'main_shared_with_original':len(set(r['date'] for r in rows)&set(r['date'] for r in old))}, 'timing':'Minute start offset; t < cutoff. First-minute touch lies in [18:00,18:01); no exact seconds or execution inferred.', 'limitations':['Retrospective complete full-day selection uses later coverage and quality, not a live eligibility signal.', 'No trading P&L, fees, spread, slippage, queue or stop-order execution modeled.', 'Same previously explored minute archive; groups and periods are descriptive, not independent validation.', 'Coarser historical candles cannot establish minute-level first-touch timing.']} # Remove misleading daytime cutoff from the overnight-only comparator. result['overnight_only_comparator']['cumulative']=[r for r in result['overnight_only_comparator']['cumulative'] if r['before_minute']<=930] assert fingerprint(a.input)==before a.output.mkdir(parents=True,exist_ok=True) (a.output/'summary.json').write_text(json.dumps(result,indent=2,allow_nan=False)+'\n',encoding='utf-8') pd.DataFrame(result['main']['cumulative']).to_csv(a.output/'cumulative.csv',index=False) print(json.dumps({k:result[k] for k in ['checks','main','overlap']},indent=2)) if __name__=='__main__':main_cli()