tradingSystem/research/score_recurrence_20261029/audit.py

70 lines
6.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""真实快照的独立计数、基线、指数区间及逐笔现金核查;断网执行。"""
import sys
from collections import defaultdict
import numpy as np
import pandas as pd
from common import *
from engine import future_exits,account
def main():
sys.addaudithook(offline);p,panel,f,cov=load();dates=panel['dates'];t,n=panel['open'].shape;cfg=configuration();rng=np.random.default_rng(20261029)
frequency_checks=0
for group,key in enumerate(f['group_keys']):
field,q=key.split(':');q=float(q)
for _ in range(100):
day=int(rng.integers(20,t));stock=int(rng.integers(n));actual=int(np.sum(panel[field][day-20:day,stock]>=q));assert actual==f['counts'][group,day,stock];frequency_checks+=1
stop=int(np.searchsorted(dates,'2026-01-01'))
for group,key in enumerate(f['group_keys']):
field,q=key.split(':');short=previous_counts(panel[field][:stop]>=float(q));assert np.array_equal(short,f['counts'][group,:stop])
# 验证旧单因子基线:恢复旧信号窗口后应精确得到上轮结果。
old=pd.read_csv(PREVIOUS/'grid.csv');oldwindow=(dates>='2025-01-02')&(dates<='2026-09-30');oldchecks=[];indexchecks=[]
for h in [1,5,10]:
ex,gr=future_exits(panel,h);d=np.load(ROOT/f'cache/daily_{h:02}.npz')
for field in ['total','smart']:
mask=panel['eligible']&oldwindow[:,None]&(panel[field]>=.8)&np.isfinite(gr)
daily=divide(np.where(mask,gr*.997/1.003-1,0).sum(1),mask.sum(1));observed=float(mean(daily))
row=old[(old.total==(.8 if field=='total' else 0))&(old.smart==(.8 if field=='smart' else 0))&(old.hold==h)&(old.period=='full')&(old.regime==99)&(old.regime_index=='regime300')&(old.fee_bps==30)].iloc[0]
assert abs(observed-row.mean_net)<1e-12;assert mask.sum()==row.completed;oldchecks.append({'score':field,'hold':h,'error':abs(observed-row.mean_net)})
for c in [c for c in cfg if c['score']=='smart' and c['threshold']==.8 and (c['mode']=='current' or c['k']==5)]:
mask=mask_for(panel,f,c)&np.isfinite(gr)
for name,op in zip(f['index_names'],f['index_opens']):
# 按实际退出日逐只取指数,不使用计划退出日替代被阻止的卖出。
values=np.full((t,n),np.nan)
for day in np.flatnonzero(mask.any(1)):
stocks=np.flatnonzero(mask[day]);values[day,stocks]=gr[day,stocks]-op[ex[day,stocks]]/op[day+1]
direct=divide(np.nansum(values,axis=1),mask.sum(1));saved=d['excess_'+str(name)][:,c['config']]
err=float(np.nanmax(np.abs(direct-saved)));assert err<1e-12;indexchecks.append({'hold':h,'mode':c['mode'],'index':str(name),'error':err})
# 真正截断日期,保留截至截断日已经退出的同一批次,核验收益标签。
short={key:values[:stop] if key!='codes' else values for key,values in panel.items()};sx,sg=future_exits(short,h)
valid=np.isfinite(gr[:stop])&(ex[:stop]<stop)
assert np.array_equal(np.isfinite(sg),valid);assert np.allclose(sg[valid],gr[:stop][valid])
ledgerchecks=[];eventchecks=[]
for c in [c for c in cfg if c['score']=='smart' and c['threshold']==.8 and (c['mode']=='current' or c['k']==5)]:
mask=mask_for(panel,f,c)&(dates>='2026-01-01')[:,None];aa=account(panel,mask,5,.003,detail=True)
byday=defaultdict(list);legs=defaultdict(dict)
for tr in aa['journal']:byday[tr['day']].append(tr);legs[tr['signal'],tr['stock']][tr['side']]=tr
cash=1.;quantities=np.zeros(n);err=0.
for i,row in enumerate(aa['daily']):
for tr in byday[i]:
j=tr['stock'];value=tr['qty']*tr['price'];assert tr['price']==panel['open'][i,j]
if tr['side']=='buy':assert i==tr['signal']+1 and panel['can_buy'][i,j];cash-=value*1.003;quantities[j]+=tr['qty']
else:assert i>=tr['signal']+6 and panel['can_sell'][i,j];cash+=value*.997;quantities[j]-=tr['qty']
assert cash>=-1e-10 and quantities[j]>=-1e-10
value=float(quantities@panel['mark'][i]);err=max(err,abs(cash-row['cash']),abs(value-row['stock_value']),abs(cash+value-row['nav']))
assert err<1e-10;ledgerchecks.append({'mode':c['mode'],'trades':len(aa['journal']),'error':err})
batches=defaultdict(list)
for (sig,j),tr in legs.items():
if 'sell' in tr:batches[sig].append(tr['sell']['price']/tr['buy']['price']*.997/1.003-1)
dd=np.load(ROOT/'cache/daily_05.npz');expected=mean((dd['gross'][:,c['config']][dates>='2026-01-01']+1)*.997/1.003-1)
observed=np.mean([np.mean(v) for v in batches.values()]);assert abs(expected-observed)<1e-12
eventchecks.append({'mode':c['mode'],'completed':sum(map(len,batches.values())),'mean_net30':float(observed)})
print(c['mode'],'独立逐笔重建完成',flush=True)
# 一个事先指定日期的窗口明细,按股票代码顺序展示3只,而非按收益选例。
day=int(np.where(dates=='2026-08-31')[0][0]);group=list(f['group_keys']).index('smart:0.8');chosen=np.flatnonzero(f['base'][day]&(f['counts'][group,day]>=5))[:3];trace=[]
for stock in chosen:
for j in range(day-20,day):trace.append({'signal_date':str(dates[day]),'stock':str(panel['codes'][stock]),'historical_date':str(dates[j]),'smart_score':float(panel['smart'][j,stock]),'hit_ge_0_8':bool(panel['smart'][j,stock]>=.8),'prior20_hits':int(f['counts'][group,day,stock]),'signal_day_score':float(panel['smart'][day,stock])})
pd.DataFrame(trace).to_csv(ROOT/'window_examples.csv',index=False,lineterminator='\n')
dump(ROOT/'audit.json',{'environment':'开发机,经unit_test_guard隔离配置、断网运行','memory_tests':9,'raw_window_checks':frequency_checks,'all_threshold_count_prefix_exact':True,'prior_baseline_checks':oldchecks,'index_actual_exit_checks':indexchecks,'event_exit_truncation_holds':[1,5,10],'ledger_rebuilds':ledgerchecks,'event_rebuilds':eventchecks,'window_example_signal_date':'2026-08-31','window_example_stocks':len(chosen)})
print('全部审计通过',frequency_checks,'次直接20日计数;',len(indexchecks),'项指数区间检查')
if __name__=='__main__':main()