113 lines
7.5 KiB
Python
113 lines
7.5 KiB
Python
"""读取冻结本地快照,独立复算收益、持仓去重及全股票覆盖。禁止联网。"""
|
||
import datetime as dt
|
||
import numpy as np
|
||
import pandas as pd
|
||
from common import ROOT,BASE,read,dump,digest,protocol,install_offline,previous_sum
|
||
from absolute_core import conditions
|
||
|
||
def main():
|
||
install_offline();p=protocol();a=dict(np.load(ROOT/'cache/prices.npz'))
|
||
b=dict(np.load(ROOT/'cache/phase.npz'));c=dict(np.load(ROOT/'cache/chips.npz'))
|
||
coverage=dict(np.load(ROOT/'cache/coverage.npz'))
|
||
f=pd.read_csv(ROOT/'cache/observations.csv.gz');ledger=pd.read_csv(ROOT/'trades.csv.gz')
|
||
freeze=read(ROOT/'feature_freeze.json')
|
||
assert freeze['features_sha256']==digest(ROOT/'cache/features.csv.gz')
|
||
assert freeze['protocol_sha256']==digest(ROOT/'protocol.json')
|
||
assert freeze['coverage_rules_sha256']==digest(ROOT/'coverage_rules.json')
|
||
assert freeze['implementation_notes_sha256']==digest(ROOT/'implementation_notes.json')
|
||
masks=conditions(a,b,c);union=np.logical_or.reduce(list(masks.values()))&coverage['calculable']
|
||
ii,jj=np.where(union)
|
||
np.testing.assert_array_equal(ii,f.i);np.testing.assert_array_equal(jj,f.j)
|
||
assert not f.duplicated(['date','code']).any()
|
||
assert all(np.array_equal(mask[ii,jj],f[key]) for key,mask in masks.items())
|
||
assert not (coverage['verified']&coverage['incomplete']).any()
|
||
universe=pd.DataFrame({'code':a['codes'],'exchange':[x[-2:] for x in a['codes']],
|
||
'valid_price_days':np.isfinite(a['close']).sum(axis=0),
|
||
'verified_days':coverage['verified'].sum(axis=0),'incomplete_days':coverage['incomplete'].sum(axis=0),
|
||
'calculable_days':coverage['calculable'].sum(axis=0),'known_st_days':coverage['known_st'].sum(axis=0),
|
||
'complete_phase60_days':(b['valid']&np.isfinite(b['count60'])&coverage['calculable']).sum(axis=0),
|
||
'chip_seen_days':c['seen'].sum(axis=0),'chip_valid_days':c['chip_valid'].sum(axis=0),
|
||
'valley_evaluable_days':c['valley_evaluable'].sum(axis=0),'any_condition_signal_days':union.sum(axis=0)})
|
||
universe.to_csv(ROOT/'universe_audit.csv',index=False)
|
||
mature_last=a['dates'][-62]
|
||
source_checks=0
|
||
for name,h in read(ROOT/'chip_coverage.json')['source_sha256'].items():
|
||
assert digest(ROOT/'raw'/name)==h;source_checks+=1
|
||
for name,h in read(ROOT/'phase_coverage.json')['source_sha256'].items():
|
||
assert digest(BASE/'raw'/name)==h;source_checks+=1
|
||
for name,h in read(ROOT/'price_coverage.json')['source_sha256'].items():
|
||
assert digest(ROOT.parent/name)==h;source_checks+=1
|
||
assert not read(ROOT/'chip_coverage.json')['first_version_flag_differences']
|
||
# 独立从开盘价格和停牌涨跌停掩码复算,无调用outcome函数。
|
||
chosen=f.sample(min(1000,len(f)),random_state=p['seed']);completed_checks=0
|
||
for r in chosen.itertuples():
|
||
entry=r.i+1;due=entry+60
|
||
mature=due<len(a['dates']);filled=entry<len(a['dates']) and bool(a['can_buy'][entry,r.j])
|
||
assert r.calendar_matured==mature and r.entry_filled==filled
|
||
end=next((k for k in range(due,len(a['dates'])) if a['can_sell'][k,r.j]),None) if mature and filled else None
|
||
assert r.completed==(end is not None)
|
||
if end is not None:
|
||
net=a['open'][end,r.j]*(1-.003)/(a['open'][entry,r.j]*(1+.003))-1
|
||
assert np.isclose(net,r.net30,atol=1e-12) and r.exit_index==end;completed_checks+=1
|
||
if mature and filled:
|
||
path=a['close'][entry:due,r.j]/a['open'][entry,r.j]-1
|
||
assert r.path_complete==bool(np.isfinite(path).all())
|
||
if r.path_complete:
|
||
hits=[k for k,v in enumerate(path) if v>=.15];losses=[k for k,v in enumerate(path) if v<=-.1]
|
||
assert bool(r.hit15)==bool(hits)
|
||
assert bool(r.up_before_down)==bool(hits and (not losses or hits[0]<losses[0]))
|
||
# 以每天是否仍持仓的定义核对每一条入选交易,不根据未来盈亏挑选。
|
||
replay_groups=0
|
||
for (scope,key),actual in ledger.groupby(['analysis_scope','condition']):
|
||
candidates=f[f[key] if scope=='all_calculable' else (f[key]&(f.scope==scope))]
|
||
expected=[];prior=None;release=-1
|
||
rows=candidates[['code','date','i','entry_filled','completed','exit_index']].sort_values(['code','i'])
|
||
for code,day,i,filled,completed,end in rows.itertuples(index=False,name=None):
|
||
if code!=prior:prior=code;release=-1
|
||
if i<release:continue
|
||
expected.append((day,code))
|
||
if filled:release=end if completed else len(a['dates'])
|
||
assert set(expected)==set(zip(actual.date,actual.code))
|
||
assert len(expected)==len(actual);replay_groups+=1
|
||
# 股票没有代码取模采样;观察资格及输入覆盖按条件明确列出。
|
||
completephase=b['valid']&np.isfinite(b['count60']);trend=np.isfinite(a['ret60'])&np.isfinite(a['slope61'])
|
||
chip=c['chip_valid'];valley=chip&c['valley_evaluable'];avail={}
|
||
for key in masks:
|
||
use=np.ones(union.shape,bool)
|
||
if key.startswith('down'):use&=trend
|
||
if key in ['upper_gap','down_upper','down_upper_multi']:use&=chip
|
||
if 'valley' in key:use&=valley
|
||
if key in ['down_zero','down_one','down_multi','multi_all','down_upper_multi','down_valley_multi'] or key.startswith('down_duration'):use&=completephase
|
||
avail[key]={}
|
||
for scope in ['verified','incomplete','calculable']:
|
||
valid=use&coverage[scope];signals=valid&masks[key]
|
||
avail[key][scope]={'available_stock_days':int(valid.sum()),'available_stocks':int(valid.any(axis=0).sum()),
|
||
'available_dates':int(valid.any(axis=1).sum()),'signal_stock_days':int(signals.sum()),
|
||
'signal_stocks':int(signals.any(axis=0).sum())}
|
||
# 实际历史前缀检查:吸筹计数不含当日,延长时间轴不会改写前缀。
|
||
for cut in [180,240,300]:
|
||
np.testing.assert_allclose(previous_sum(b['events'][:cut],60),b['count60'][:cut],equal_nan=True)
|
||
np.testing.assert_allclose(previous_sum(b['clear'][:cut],60),b['days60'][:cut],equal_nan=True)
|
||
for i in [cut-1]:
|
||
expected=a['close'][i]/a['close'][i-60]-1
|
||
np.testing.assert_allclose(expected,a['ret60'][i],equal_nan=True)
|
||
counts=pd.read_csv(ROOT/'absolute_results.csv')
|
||
assert len(counts)==96
|
||
for r in counts.itertuples():
|
||
assert r.completed+r.unresolved_exit==r.filled_mature
|
||
assert r.wins+r.losses+r.zero_returns==r.completed
|
||
assert r.mature_signals+r.pending_60_days==r.observations
|
||
assert r.filled_mature+r.unfilled_mature==r.mature_signals
|
||
dump(ROOT/'feature_availability.json',avail)
|
||
dump(ROOT/'audit.json',{'audited_at':dt.datetime.now(dt.timezone(dt.timedelta(hours=8))).isoformat(),
|
||
'checks_passed':True,'full_union_stock_days':len(f),'outcome_independent_checks':len(chosen),
|
||
'completed_return_checks':completed_checks,'position_replay_groups':replay_groups,'source_hash_checks':source_checks,
|
||
'real_history_prefix_cuts':[180,240,300],'latest_60_day_mature_signal':str(mature_last),
|
||
'latest_60_day_mature_entry':str(a['dates'][-61]),
|
||
'chip_backfilled_stock_days':int((c['seen']&c['created_later']).sum()),'chip_seen_stock_days':int(c['seen'].sum()),
|
||
'unit_tests':'17项专项测试,经scripts/unit_test_guard.py隔离配置并禁止联网;另附测试回执。',
|
||
'calendar_limit':'旧版三个指数核对至10月23日;最后四个市场日按全市场行情扩展。trade_cal仍为空。'})
|
||
print('全量覆盖、1000笔收益与所有条件持仓回放核验通过',flush=True)
|
||
|
||
if __name__=='__main__':main()
|