192 lines
12 KiB
Python
192 lines
12 KiB
Python
|
|
"""冻结协议后的离线独立性分析;不读取收益,不连接任何外部服务。"""
|
|||
|
|
from __future__ import annotations
|
|||
|
|
import collections
|
|||
|
|
import datetime as dt
|
|||
|
|
import gzip
|
|||
|
|
import hashlib
|
|||
|
|
import itertools
|
|||
|
|
import json
|
|||
|
|
import math
|
|||
|
|
from pathlib import Path
|
|||
|
|
import re
|
|||
|
|
|
|||
|
|
import numpy as np
|
|||
|
|
import pandas as pd
|
|||
|
|
|
|||
|
|
ROOT = Path(__file__).resolve().parent
|
|||
|
|
DATA = ROOT / 'data'
|
|||
|
|
OUT = ROOT
|
|||
|
|
TZ = dt.timezone(dt.timedelta(hours=8))
|
|||
|
|
START, END = '2026-10-08', '2026-11-10'
|
|||
|
|
SOURCES = ['qrs', 'intensity', 'distribution', 'mtf', 'bionic']
|
|||
|
|
LABELS = {'qrs':'逐股QRS','intensity':'资金流强度','distribution':'资金分布','mtf':'资金异动','bionic':'决策系统'}
|
|||
|
|
HS = re.compile(r'(?:(?:60|68)\d{4}\.SH|(?:00|30)\d{4}\.SZ)$')
|
|||
|
|
|
|||
|
|
def code(s):
|
|||
|
|
s = str(s)
|
|||
|
|
if s[:2] in ('SH','SZ'): s=s[2:]+'.'+s[:2]
|
|||
|
|
if not HS.fullmatch(s): raise ValueError('non-HS row')
|
|||
|
|
return s
|
|||
|
|
|
|||
|
|
def load():
|
|||
|
|
rows=[]; raw=[]; broadcasts=[]; provenance=collections.Counter(); all_judgements=[]
|
|||
|
|
manifest={}
|
|||
|
|
for p in [DATA/name for name in ['itd.jsonl.gz','bionic.jsonl.gz','streams.jsonl.gz']]:
|
|||
|
|
manifest[p.name]={'sha256':hashlib.sha256(p.read_bytes()).hexdigest(),'bytes':p.stat().st_size}
|
|||
|
|
records=[json.loads(x) for x in gzip.open(p,'rt')]
|
|||
|
|
manifest[p.name]['rows']=len(records)
|
|||
|
|
for r in records:
|
|||
|
|
if r['kind']=='itd':
|
|||
|
|
c=code(r['ts_code']);day=r['trade_date'];t=dt.datetime.fromtimestamp(int(r['trigger_time'])/1000,TZ)
|
|||
|
|
meta=r.get('metadata') or {};name=r['source'];parts=meta.get('contributing_sources',[]) if name=='multi_source' else [name]
|
|||
|
|
raw.append({'day':day,'source':name,'code':c})
|
|||
|
|
for part in parts:
|
|||
|
|
if part.startswith('daily_qrs_symmetric'):s='qrs';direction=-1 if part.endswith('down') else 1
|
|||
|
|
elif part.startswith('money_flow_'):s='intensity';direction=-1 if '_out_' in part else 1
|
|||
|
|
elif part.startswith('capital_'):s='distribution';direction=-1 if part.endswith('distribution') else 1
|
|||
|
|
elif part=='intraday_buy_emitted':continue
|
|||
|
|
else:raise ValueError('unknown alert source '+part)
|
|||
|
|
value=(meta.get('contributing_values') or {}).get(part,r.get('value'))
|
|||
|
|
rows.append({'day':day,'source':s,'code':c,'t':t,'direction':direction,'value':float(value),'id':r['alert_id']+':'+part,
|
|||
|
|
'parent_source':name,'evidence_date':str(meta.get('trade_date') or '')[:10], 'level':r['level']})
|
|||
|
|
elif r['kind']=='mtf':
|
|||
|
|
c=code(r['ts_code']);received=dt.datetime.fromtimestamp(int(r['stream_id'].split('-')[0])/1000,TZ)
|
|||
|
|
day=received.date().isoformat();t=dt.datetime.fromisoformat(day+'T'+r['calc_time']).replace(tzinfo=TZ)
|
|||
|
|
rows.append({'day':day,'source':'mtf','code':c,'t':t,'direction':1 if r['direction']=='inflow' else -1,
|
|||
|
|
'value':float(r['z_dd']),'id':r['stream_id'],'parent_source':'mtf','evidence_date':day,'level':r.get('mode')})
|
|||
|
|
elif r['kind']=='bionic_audit':
|
|||
|
|
c=code(r['stock_code']);day=dt.datetime.strptime(str(r['audit_date']),'%Y%m%d').date().isoformat()
|
|||
|
|
# 审计库存UTC naive时间;随后用同股同结论广播独立核对偏移。
|
|||
|
|
t=dt.datetime.fromisoformat(r['created_at']).replace(tzinfo=dt.timezone.utc).astimezone(TZ)
|
|||
|
|
if t.date().isoformat()!=day: raise ValueError('audit timezone/date mismatch')
|
|||
|
|
trigger=r['reason'].split('源:',1)[-1].split(' | 判定:',1)[0]
|
|||
|
|
prefix=re.match(r'【盘中([^】]+)】',r['reason']).group(1)
|
|||
|
|
provenance[(prefix,trigger.split('(')[0].strip())]+=1
|
|||
|
|
all_judgements.append({'day':day,'code':c,'t':t,'verdict':r['verdict'],'prefix':prefix,'trigger':trigger})
|
|||
|
|
direction={'REVERSAL_BUY':1,'REVERSAL_SELL':-1,'TAKE_PROFIT':-1}.get(r['verdict'])
|
|||
|
|
if direction is None:continue # 维持不是中性票,不从旧计划反推方向。
|
|||
|
|
rows.append({'day':day,'source':'bionic','code':c,'t':t,'direction':direction,'value':direction,
|
|||
|
|
'id':f'{c}:{t.isoformat()}:{r["verdict"]}','parent_source':prefix,'verdict':r['verdict'],'trigger':trigger,'evidence_date':'','level':''})
|
|||
|
|
elif r['kind']=='bionic_broadcast':
|
|||
|
|
r['code']=code(r['ts_code']);broadcasts.append(r)
|
|||
|
|
df=pd.DataFrame(rows).drop_duplicates(['source','code','id']).sort_values(['t','source','code'])
|
|||
|
|
# 合成告警拆为原成分,同一时刻同股票同成分只保留一条。
|
|||
|
|
df=df.drop_duplicates(['source','code','t','direction'],keep='last')
|
|||
|
|
OUT.joinpath('manifest.json').write_text(json.dumps({'input':manifest,'scope':'沪深','protocol_sha256':hashlib.sha256((ROOT/'protocol.json').read_bytes()).hexdigest()},indent=2,ensure_ascii=False))
|
|||
|
|
return df,pd.DataFrame(raw),broadcasts,pd.DataFrame(all_judgements),provenance
|
|||
|
|
|
|||
|
|
def eligible(x,y,days):
|
|||
|
|
return len(x)>=50 and len(set(days))>=10 and min(sum(x>0),sum(x<0),sum(y>0),sum(y<0))>=10
|
|||
|
|
|
|||
|
|
def corr(x,y):
|
|||
|
|
x=np.asarray(x,dtype=float);y=np.asarray(y,dtype=float)
|
|||
|
|
if len(x)<2 or np.std(x)<1e-12 or np.std(y)<1e-12:return None
|
|||
|
|
return float(np.corrcoef(x,y)[0,1])
|
|||
|
|
|
|||
|
|
def bootstrap_pairs(frame,group,seed=20261111,n=1000):
|
|||
|
|
rng=np.random.default_rng(seed);blocks=[g[['x','y']].to_numpy() for _,g in frame.groupby(group)]
|
|||
|
|
estimates=[]
|
|||
|
|
for _ in range(n):
|
|||
|
|
v=np.concatenate([blocks[i] for i in rng.integers(len(blocks),size=len(blocks))]);r=corr(v[:,0],v[:,1])
|
|||
|
|
if r is not None:estimates.append(r)
|
|||
|
|
return [float(x) for x in np.quantile(estimates,[.025,.5,.975])] if estimates else None
|
|||
|
|
|
|||
|
|
def pair_stats(panel,bootstrap=True):
|
|||
|
|
results=[]
|
|||
|
|
for a,b in itertools.combinations(SOURCES,2):
|
|||
|
|
if a not in panel or b not in panel:continue
|
|||
|
|
p=panel[[a,b]].dropna().reset_index().rename(columns={a:'x',b:'y'})
|
|||
|
|
if p.empty:continue
|
|||
|
|
x,y=p.x.to_numpy(),p.y.to_numpy();r=corr(x,y)
|
|||
|
|
item={'a':a,'b':b,'n':len(p),'dates':p.day.nunique(),'stocks':p.code.nunique(),'corr':r,
|
|||
|
|
'agreement':float(np.mean(np.sign(x)==np.sign(y))),
|
|||
|
|
'a_positive':int(sum(x>0)),'a_negative':int(sum(x<0)), 'b_positive':int(sum(y>0)),'b_negative':int(sum(y<0)),
|
|||
|
|
'eligible':bool(eligible(x,y,p.day))}
|
|||
|
|
if bootstrap and r is not None and len(p)>20:
|
|||
|
|
item['day_ci']=bootstrap_pairs(p,'day');item['stock_ci']=bootstrap_pairs(p,'code',n=500)
|
|||
|
|
results.append(item)
|
|||
|
|
return results
|
|||
|
|
|
|||
|
|
def panels(df,how='last'):
|
|||
|
|
group=df.groupby(['day','code','source'])
|
|||
|
|
if how=='last':return group.direction.last().unstack('source')
|
|||
|
|
if how=='first':return group.direction.first().unstack('source')
|
|||
|
|
if how=='mean':return group.direction.mean().unstack('source')
|
|||
|
|
raise ValueError(how)
|
|||
|
|
|
|||
|
|
def trade_minute(t):
|
|||
|
|
minute=t.hour*60+t.minute+t.second/60
|
|||
|
|
if 570<=minute<=690:return minute-570
|
|||
|
|
if 780<=minute<=900:return minute-660
|
|||
|
|
return None
|
|||
|
|
|
|||
|
|
def event_matching(df):
|
|||
|
|
result=[]
|
|||
|
|
# QRS是日状态;盘中匹配只比较真正按分钟更新的来源。
|
|||
|
|
for a,b in itertools.combinations(['intensity','distribution','mtf','bionic'],2):
|
|||
|
|
for window in [15,30,60]:
|
|||
|
|
matches=[]
|
|||
|
|
by_b={k:g for k,g in df[df.source==b].groupby(['day','code'])}
|
|||
|
|
count=0
|
|||
|
|
for key,g in df[df.source==a].groupby(['day','code']):
|
|||
|
|
q=by_b.get(key)
|
|||
|
|
if q is None:continue
|
|||
|
|
qt=[(trade_minute(r.t),r) for r in q.itertuples()]
|
|||
|
|
qt=[x for x in qt if x[0] is not None]
|
|||
|
|
if not qt:continue
|
|||
|
|
for row in g.itertuples():
|
|||
|
|
now=trade_minute(row.t)
|
|||
|
|
if now is None:continue
|
|||
|
|
count+=1
|
|||
|
|
lag,other=min(((z-now,r) for z,r in qt),key=lambda x:abs(x[0]))
|
|||
|
|
if abs(lag)<=window:matches.append({'day':key[0],'code':key[1],'x':row.direction,'y':other.direction,'lag':lag})
|
|||
|
|
p=pd.DataFrame(matches)
|
|||
|
|
result.append({'a':a,'b':b,'window':window,'eligible_a_events':count,'matched':len(p),
|
|||
|
|
'agreement':float((p.x==p.y).mean()) if len(p) else None,
|
|||
|
|
'corr':corr(p.x,p.y) if len(p) else None,
|
|||
|
|
'median_lag_b_minus_a':float(p.lag.median()) if len(p) else None})
|
|||
|
|
return result
|
|||
|
|
|
|||
|
|
def timezone_check(df,broadcasts):
|
|||
|
|
b=df[df.source=='bionic'];diff=[];clock=[]
|
|||
|
|
for r in broadcasts:
|
|||
|
|
t=dt.datetime.fromtimestamp(int(r['trigger_time'])/1000,TZ)
|
|||
|
|
p=b[(b.code==r['code']) & (b.day==r['trade_date']) & (b.verdict==r['verdict'])]
|
|||
|
|
if len(p):diff.append(float(min(abs((x-t).total_seconds()) for x in p.t)))
|
|||
|
|
rec=dt.datetime.fromtimestamp(int(r['stream_id'].split('-')[0])/1000,TZ)
|
|||
|
|
clock.append((rec-t).total_seconds())
|
|||
|
|
return {'broadcasts':len(broadcasts),'matched_audits':len(diff),
|
|||
|
|
'audit_broadcast_abs_sec_quantiles':np.quantile(diff,[0,.5,.95,1]).tolist() if diff else [],
|
|||
|
|
'redis_minus_publisher_sec_quantiles':np.quantile(clock,[0,.5,.95,1]).tolist() if clock else []}
|
|||
|
|
|
|||
|
|
def main():
|
|||
|
|
df,raw,broadcasts,judgements,provenance=load();primary=df[(df.day>=START)&(df.day<=END)].copy()
|
|||
|
|
summaries=[]
|
|||
|
|
for s,g in primary.groupby('source'):
|
|||
|
|
groups=g.groupby(['day','code']);daily=g.groupby('day').size()
|
|||
|
|
summaries.append({'source':s,'events':len(g),'stocks':g.code.nunique(),'days':g.day.nunique(),'stock_days':len(groups),
|
|||
|
|
'positive_events':int(sum(g.direction>0)),'negative_events':int(sum(g.direction<0)),
|
|||
|
|
'daily_events_mean':float(daily.mean()),'daily_events_median':float(daily.median()),
|
|||
|
|
'direction_changing_stock_days':int((groups.direction.nunique()>1).sum()),
|
|||
|
|
'duplicate_fixed_qrs':len(g)-len(groups) if s=='qrs' else None})
|
|||
|
|
panel=panels(primary)
|
|||
|
|
result={'window':[START,END],'source_summary':summaries,'pairs':pair_stats(panel),
|
|||
|
|
'first_pairs':pair_stats(panels(primary,'first'),False),'mean_pairs':pair_stats(panels(primary,'mean'),False),
|
|||
|
|
'halves':{},'secondary':pair_stats(panels(df[df.source!='bionic']),False),
|
|||
|
|
'event_matches':event_matching(primary),'timezone':timezone_check(primary,broadcasts),
|
|||
|
|
'bionic_trigger_directions':judgements.prefix.value_counts().to_dict(),
|
|||
|
|
'bionic_verdicts':judgements.verdict.value_counts().to_dict(),
|
|||
|
|
'bionic_directional_triggers':primary[primary.source=='bionic'].parent_source.value_counts().to_dict(),
|
|||
|
|
'bionic_trigger_examples': [{'type':k[0],'trigger':k[1],'n':n} for k,n in provenance.most_common(15)]}
|
|||
|
|
days=sorted(primary.day.unique());mid=days[len(days)//2]
|
|||
|
|
for name,d in [('first',primary[primary.day<mid]),('second',primary[primary.day>=mid])]:result['halves'][name]={'start':d.day.min(),'end':d.day.max(),'pairs':pair_stats(panels(d),False)}
|
|||
|
|
# 审计是否在本窗口所有日期均有,不将没有发信号的股票日补0。
|
|||
|
|
result['presence_dates']={s:sorted(g.day.unique().tolist()) for s,g in primary.groupby('source')}
|
|||
|
|
OUT.joinpath('results.json').write_text(json.dumps(result,ensure_ascii=False,indent=2))
|
|||
|
|
# 归一化事件与原始沪深研究输入一并留存,避免上游TTL到期后无法复现。
|
|||
|
|
primary.to_csv(DATA/'normalized.csv.gz',index=False,compression='gzip')
|
|||
|
|
panel.to_csv(DATA/'paired_daily.csv.gz',compression='gzip')
|
|||
|
|
print(json.dumps({'summary':summaries,'pairs':result['pairs'],'timezone':result['timezone'],'bionic':result['bionic_directional_triggers']},ensure_ascii=False,indent=2))
|
|||
|
|
|
|||
|
|
if __name__=='__main__':main()
|