tradingSystem/research/signal_independence_20261111/weights.py

103 lines
6.1 KiB
Python
Raw Permalink Normal View History

2026-11-11 15:10:55 +08:00
"""v2分组、日期净化与原公式重算;仅离线运行。"""
from __future__ import annotations
import datetime as dt
import gzip
import hashlib
import itertools
import json
from pathlib import Path
import sys
import numpy as np
import pandas as pd
import analyze as a
SOURCE_ROOT=Path('/Users/baobao/Documents/work/project/intraday_timing/src')
sys.path.insert(0,str(SOURCE_ROOT))
from intraday_timing.state.daily_qrs_computer import DailyQRSComputer
GROUPS=['qrs','fund','mtf']
def dependence_weights(panel):
rs=[];R=np.eye(len(GROUPS))
for i,j in itertools.combinations(range(len(GROUPS)),2):
q=panel[[GROUPS[i],GROUPS[j]]].dropna()
r=a.corr(q.iloc[:,0],q.iloc[:,1])
if r is None:return None
R[i,j]=R[j,i]=abs(r)
rs.append({'a':GROUPS[i],'b':GROUPS[j],'n':len(q),'corr':r})
u=1/R.sum(axis=1);weights=u/u.sum()
return {'weights':dict(zip(GROUPS,map(float,weights))), 'pairs':rs}
def grouped_panel(f,how='last'):
z=f.copy();z['source']=z.source.replace({'intensity':'fund','distribution':'fund'})
return a.panels(z,how)
def bootstrap_weights(panel,key='day',n=1000):
q=panel.reset_index();rng=np.random.default_rng(20261111);blocks=[v.drop(columns=key) for _,v in q.groupby(key)]
estimates=[]
for _ in range(n):
sample=pd.concat([blocks[i] for i in rng.integers(len(blocks),size=len(blocks))],ignore_index=True)
r=dependence_weights(sample)
if r:estimates.append([r['weights'][g] for g in GROUPS])
return {g:np.quantile(np.array(estimates)[:,i],[.025,.5,.975]).tolist() for i,g in enumerate(GROUPS)}
def main():
f=pd.read_csv(a.DATA/'normalized.csv.gz');f['t']=pd.to_datetime(f.t)
bars=pd.DataFrame([json.loads(x) for x in gzip.open(a.DATA/'daily.jsonl.gz','rt')])
bars['trade_date']=pd.to_datetime(bars.timestamp).dt.date
bars['code']=bars.symbol.map(a.code)
assert not bars.duplicated(['code','trade_date']).any()
for col in ['high','low','close']:bars[col]=pd.to_numeric(bars[col])
cal=sorted(bars[bars.symbol=='SH600519'].trade_date.unique())
prev={d:max(x for x in cal if x<dt.date.fromisoformat(d)) for d in f.day.unique()}
q=f[f.source=='qrs'].copy()
q['fresh']=q.apply(lambda r:r.evidence_date==prev[r.day].isoformat(),axis=1)
q['age']=(pd.to_datetime(q.day)-pd.to_datetime(q.evidence_date)).dt.days
calc=DailyQRSComputer(None,n_regression=18,m_lookback=60,threshold=.7)
bycode={c:g for c,g in bars.groupby('code')};recon=[];reproduced=[];errors=[]
for row in q.itertuples():
try:
b=bycode[row.code];result=calc._compute_from_dataframe(row.code,b,prev[row.day])
if result.trade_date!=prev[row.day]:raise ValueError('missing prior-day bar')
recon.append({'day':row.day,'code':row.code,'value':result.qrs_value,'direction':float(np.sign(result.qrs_value)),
'old_value':row.value,'old_direction':row.direction,'fresh':row.fresh,'evidence_date':prev[row.day].isoformat()})
try:
old=calc._compute_from_dataframe(row.code,b,dt.date.fromisoformat(row.evidence_date))
reproduced.append(abs(old.qrs_value-row.value))
except Exception as e:errors.append({'code':row.code,'day':row.day,'phase':'old_reproduction','error':type(e).__name__})
except Exception as e:errors.append({'code':row.code,'day':row.day,'phase':'fresh_reconstruction','error':type(e).__name__})
rr=pd.DataFrame(recon)
clean=f[(f.source!='qrs') | f.index.isin(q[q.fresh].index)].copy()
counter=f.copy().set_index(['day','code','source'])
for row in rr.itertuples():
key=(row.day,row.code,'qrs');counter.loc[key,'direction']=row.direction;counter.loc[key,'value']=row.value
counter=counter.reset_index().sort_values(['t','source','code'])
# 未成功重算的QRS不得保留旧值。
success=set(zip(rr.day,rr.code))
counter=counter[(counter.source!='qrs') | counter.apply(lambda r:(r.day,r.code) in success,axis=1)]
a.SOURCES=['qrs','fund','mtf','bionic']
raw_panel=grouped_panel(f);clean_panel=grouped_panel(clean);recon_panel=grouped_panel(counter)
result={'qrs_quality':{'events':len(q),'fresh':int(q.fresh.sum()),'stale':int((~q.fresh).sum()),'age_median':float(q.age.median()),
'same_evidence_repeated':int(q.duplicated(['code','evidence_date','direction']).sum())},
'reconstruction':{'rows':len(rr),'changed_sign':int((rr.old_direction!=rr.direction).sum()),
'old_value_reproduced':len(reproduced),'old_value_max_abs_error':max(reproduced) if reproduced else None,'errors':errors},
'clean_pairs':a.pair_stats(clean_panel,False),'grouped_raw_pairs':a.pair_stats(raw_panel,False),
'reconstructed_pairs':a.pair_stats(recon_panel),
'raw_weights':dependence_weights(raw_panel),'clean_weights_for_diagnostics_only':dependence_weights(clean_panel),
'reconstructed_weights':dependence_weights(recon_panel),
'day_bootstrap':bootstrap_weights(recon_panel),'stock_bootstrap':bootstrap_weights(recon_panel,'code',500),
'sensitivity':{},'triple_complete_rows':len(recon_panel[GROUPS].dropna()),
'data_sha256':hashlib.sha256((a.DATA/'daily.jsonl.gz').read_bytes()).hexdigest()}
for how in ['first','mean']:
result['sensitivity'][how]=dependence_weights(grouped_panel(counter,how))
days=sorted(counter.day.unique());mid=days[len(days)//2]
for name,g in [('first_half',counter[counter.day<mid]),('second_half',counter[counter.day>=mid])]:
result['sensitivity'][name]=dependence_weights(grouped_panel(g))
# 资金组用更稳定全窗的资金分布作唯一代表,查看强度缺发是否改变结论。
result['sensitivity']['fund_distribution_only']=dependence_weights(grouped_panel(counter[counter.source!='intensity']))
a.OUT.joinpath('weights.json').write_text(json.dumps(result,ensure_ascii=False,indent=2))
rr.to_csv(a.DATA/'qrs_reconstruction.csv.gz',index=False,compression='gzip')
print(json.dumps(result,ensure_ascii=False,indent=2))
if __name__=='__main__':main()