tradingSystem/research/heat_recurrence_20261029/calibrate.py

94 lines
7.5 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
import numpy as np
import pandas as pd
from common import *
from engine import future_exits,account
def slices(dates,features):
out=[]
for period in ['full','2026-08','2026-09','2026-10']:
period_mask=features['window'] if period=='full' else features['window']&np.char.startswith(dates,period)
out.append((period,'all',99,period_mask))
for ix,index in enumerate(features['index_names']):
for stage in [-1,0,1]:out.append((period,str(index),stage,period_mask&(features['stages'][ix]==stage)))
return out
def main():
sys.addaudithook(offline);p,panel,f,cov=load();dates=panel['dates'];t,n=panel['open'].shape;configs=configuration();nc=len(configs);n_groups=len(f['group_keys'])
ids=[];selected=[];filled=[];can_buy=np.vstack([panel['can_buy'][1:],np.zeros((1,n),bool)])
for group,key in enumerate(f['group_keys']):
field,q=key.split(':');q=float(q);hit=panel[field]>=q;base=f['base_'+field]
bucket=np.arange(t,dtype=np.int32)[:,None]*42+hit.astype(np.int32)*21+np.maximum(f['counts'][group],0)
ids.append(bucket);selected.append(aggregate(bucket,base,None,t));filled.append(aggregate(bucket,base&can_buy,None,t))
selected=np.concatenate(selected,axis=1);filled=np.concatenate(filled,axis=1)
cfg=pd.DataFrame(configs);sl=slices(dates,f);all_rows=[];checks=[];daily_dir=ROOT/'cache'
control=np.array([c['config']//43*43+(1 if c['mode']=='frequency' else 0) for c in configs])
current=np.array([c['config']//43*43 for c in configs]);universe=np.array([c['config']//43*43+1 for c in configs])
for h in p['holds']:
exits,gross=future_exits(panel,h);gr=gross-1
fields={'completed':[],'gross':[],'wins30':[],'delayed':[]}
for index in f['index_names']:fields['excess_'+str(index)]=[]
ix_excess=[]
# 比较各股票实际持有区间的指数开盘收益,卖出延期不偷偷截回计划日。
for op in f['index_opens']:
benchmark=op[np.maximum(exits,0)]/np.r_[op[1:],np.nan][:,None]-1
ix_excess.append(gr-benchmark)
for group,bucket in enumerate(ids):
field=str(f['group_keys'][group]).split(':')[0];ok=f['base_'+field]&np.isfinite(gross)
cc=aggregate(bucket,ok,None,t);fields['completed'].append(cc)
fields['gross'].append(divide(aggregate(bucket,ok,gr,t),cc))
fields['wins30'].append(aggregate(bucket,ok,gross*.997/1.003>1,t))
fields['delayed'].append(aggregate(bucket,ok&(exits>np.arange(t)[:,None]+h+1),None,t))
for index,values in zip(f['index_names'],ix_excess):fields['excess_'+str(index)].append(divide(aggregate(bucket,ok,values,t),cc))
d={k:np.concatenate(values,axis=1) for k,values in fields.items()};d['selected']=selected;d['filled']=filled
np.savez_compressed(daily_dir/f'daily_{h:02}.npz',**d)
for period,index,stage,dd in sl:
v=d['gross'][dd];cc=d['completed'][dd];ntr=cc.sum(0)
z=cfg.copy();z['hold']=h;z['period']=period;z['phase_index']=index;z['stage']=stage;z['phase_days']=int(dd.sum())
z['active_days']=np.sum(cc>0,axis=0);z['selected']=selected[dd].sum(0).astype(int);z['mean_selected']=divide(selected[dd].sum(0),np.full(nc,dd.sum()))
z['filled']=filled[dd].sum(0).astype(int);z['completed']=ntr.astype(int);z['unresolved']=(filled[dd].sum(0)-ntr).astype(int);z['delayed']=d['delayed'][dd].sum(0).astype(int)
z['mean_gross']=mean(v);z['mean_net30']=(z['mean_gross']+1)*.997/1.003-1;z['mean_net60']=(z['mean_gross']+1)*.994/1.006-1
z['win30']=divide(d['wins30'][dd].sum(0),ntr)
z['delta_k0_net30']=mean(v-v[:,control])*.997/1.003;z['delta_current_net30']=mean(v-v[:,current])*.997/1.003;z['delta_universe_net30']=mean(v-v[:,universe])*.997/1.003
z['paired_days']=np.sum(np.isfinite(v-v[:,control]),axis=0)
for key in ['csi300','csi500','csi1000','csi2000']:z['excess_'+key]=mean(d['excess_'+key][dd])
z['supported']=(z.active_days>=20)&(z.completed>=100)
all_rows.append(z)
# K=0条件是本实验的恒等式,覆盖每一分数阈值与持有期。
for group in range(n_groups):
off=group*43;assert np.array_equal(d['completed'][:,off],d['completed'][:,off+22]);assert np.allclose(d['gross'][:,off],d['gross'][:,off+22],equal_nan=True,atol=1e-14)
basis_start=(group//len(p['thresholds']))*len(p['thresholds'])*43
assert np.array_equal(d['completed'][:,basis_start+1],d['completed'][:,off+1])
# 对K=5直接逐股筛选,再独立等权计算,核对分桶累计没有错位。
config=configs[off+6];mask=mask_for(panel,f,config)&np.isfinite(gross)
direct=divide(np.where(mask,gr,0).sum(1),mask.sum(1))
assert np.allclose(direct,d['gross'][:,off+6],equal_nan=True,atol=1e-12)
delta=np.abs(direct-d['gross'][:,off+6]);error=float(np.nanmax(delta)) if np.isfinite(delta).any() else 0.
assert error<1e-12;checks.append({'hold':h,'group':str(f['group_keys'][group]),'max_error':error})
print('持有',h,'日:',nc,'组条件、',len(sl),'种时间阶段分组完成',flush=True)
grid=pd.concat(all_rows,ignore_index=True);grid.to_csv(ROOT/'grid.csv.gz',index=False,compression={'method':'gzip','mtime':0},lineterminator='\n')
focus=grid[(grid.threshold==.8)&grid.k.isin([0,1,3,5,8,10,15,20])];focus.to_csv(ROOT/'focus_grid.csv',index=False,lineterminator='\n')
accounts=[];curves=[];cashchecks=[]
account_configs=[c for c in configs if c['threshold']==.8 and (c['mode']=='current' or c['k']==5)]
# 无分数/频次门槛对照,其完整历史观察池与所有条件一致。
account_configs.extend(configs[i*len(p['thresholds'])*43+1] for i in range(len(p['scores'])));test=f['window']
for c in account_configs:
mask=mask_for(panel,f,c)&test[:,None]
for h in [1,5,10]:
for fee in [30,60]:
aa=account(panel,mask,h,fee/10000);cash=1.;err=0.
for row in aa['daily']:
err=max(err,abs(row['cash']-(cash+row['sell_cash']-row['buy_cash'])),abs(row['nav']-row['cash']-row['stock_value']));cash=row['cash'];assert cash>=-1e-12
assert err<1e-10
name=c['score']+('_universe' if c['mode']=='frequency' and c['k']==0 else '_'+c['mode'])
accounts.append({'name':name,**c,'hold':h,'fee_bps':fee,**aa['summary']})
curves.extend({'name':name,'hold':h,'fee_bps':fee,**row} for row in aa['daily'])
cashchecks.append({'name':name,'hold':h,'fee_bps':fee,'error':err})
if fee==30:assert account(panel,mask,h,.003,stop=t//2)['daily']==aa['daily'][:t//2]
print('预设账户',c['score'],c['mode'],c['k'],'完成',flush=True)
pd.DataFrame(accounts).to_csv(ROOT/'accounts.csv',index=False,lineterminator='\n');pd.DataFrame(curves).to_csv(ROOT/'account_daily.csv.gz',index=False,compression={'method':'gzip','mtime':0},lineterminator='\n')
dump(ROOT/'calculation_checks.json',{'grid_rows':len(grid),'combinations':nc*10,'k0_identities':'全部24组阈值、10个持有期通过;无门槛历史池一致,both K0=current','direct_mask_checks':checks,'account_checks':cashchecks,'account_prefix_check':'全部36条30bp预设账户前半段与截断计算逐日一致'})
print('计算完成',len(grid),'行分组结果,',len(accounts),'账户')
if __name__=='__main__':main()