211 lines
12 KiB
Python
211 lines
12 KiB
Python
|
|
"""四维网格事件研究及现金约束账户。离线运行,不导入线上策略服务。"""
|
||
|
|
import csv
|
||
|
|
import datetime as dt
|
||
|
|
import gzip
|
||
|
|
import itertools
|
||
|
|
import json
|
||
|
|
import sys
|
||
|
|
from pathlib import Path
|
||
|
|
|
||
|
|
import numpy as np
|
||
|
|
|
||
|
|
from prepare import ROOT, digest, dump, offline, read
|
||
|
|
|
||
|
|
def parameter_key(heat,lower,upper,hold):return f'{heat:g}/{lower:g}/{upper:g}/{hold}'
|
||
|
|
|
||
|
|
def stock_mask(panel, field, heat, lower, upper, signal_end):
|
||
|
|
out=panel['eligible']&np.isfinite(panel[field])&(panel[field]>=heat)&(panel['pct']>=lower)&(panel['pct']<upper)
|
||
|
|
out[signal_end+1:]=False
|
||
|
|
return out
|
||
|
|
|
||
|
|
def future_exits(panel,hold):
|
||
|
|
t,n=panel['open'].shape
|
||
|
|
nxt=np.full((t+1,n),-1,dtype=np.int16)
|
||
|
|
for i in range(t-1,-1,-1):nxt[i]=np.where(panel['can_sell'][i],i,nxt[i+1])
|
||
|
|
exits=np.full((t,n),-1,dtype=np.int16)
|
||
|
|
gross=np.full((t,n),np.nan)
|
||
|
|
for s in range(t-hold-1):
|
||
|
|
e=nxt[s+hold+1];j=np.arange(n)
|
||
|
|
exits[s]=e
|
||
|
|
ok=(e>=0)&panel['can_buy'][s+1]
|
||
|
|
gross[s,ok]=panel['open'][e[ok],j[ok]]/panel['open'][s+1,ok]
|
||
|
|
return exits,gross
|
||
|
|
|
||
|
|
def daily_means(mask,values):
|
||
|
|
valid=mask&np.isfinite(values)
|
||
|
|
n=valid.sum(axis=1)
|
||
|
|
total=np.where(valid,values,0).sum(axis=1)
|
||
|
|
return np.divide(total,n,out=np.full(len(n),np.nan),where=n>0)
|
||
|
|
|
||
|
|
def mean(v):
|
||
|
|
v=np.asarray(v);v=v[np.isfinite(v)]
|
||
|
|
return float(v.mean()) if len(v) else None
|
||
|
|
|
||
|
|
def event_grid(panel,p,field,out):
|
||
|
|
dates=panel['dates'];t=len(dates);end=t-12
|
||
|
|
pairs=[(l,u) for l in p['return_lower_pct'] for u in p['return_upper_pct'] if l<u]
|
||
|
|
buy=np.vstack([panel['can_buy'][1:],np.zeros_like(panel['can_buy'][0])])
|
||
|
|
result=[];daily={}
|
||
|
|
train_days=dates<='2026-08-31';test_days=dates>='2026-09-15'
|
||
|
|
split=int(np.searchsorted(dates,'2026-09-15'))
|
||
|
|
for h in p['hold_sessions']:
|
||
|
|
exits,gross=future_exits(panel,h)
|
||
|
|
net=gross*(1-.003)/(1+.003)-1
|
||
|
|
base={}
|
||
|
|
for l,u in pairs:
|
||
|
|
m=stock_mask(panel,field,0,l,u,end)&buy
|
||
|
|
base[l,u]=daily_means(m,net)
|
||
|
|
for heat,l,u in itertools.product(p['heat_thresholds'],p['return_lower_pct'],p['return_upper_pct']):
|
||
|
|
if l>=u:continue
|
||
|
|
select=stock_mask(panel,field,heat,l,u,end);filled=select&buy
|
||
|
|
complete=filled&np.isfinite(net);means=daily_means(complete,net)
|
||
|
|
excess=means-base[l,u]
|
||
|
|
train=complete&(exits<split)&train_days[:,None]
|
||
|
|
tr_mean=daily_means(train,net)
|
||
|
|
# 对照也只使用分割日前已经完成的交易,避免训练标签偷看验证期。
|
||
|
|
bm=stock_mask(panel,field,0,l,u,end)&buy&(exits<split)&train_days[:,None]
|
||
|
|
tr_excess=tr_mean-daily_means(bm,net)
|
||
|
|
v=net[complete];key=parameter_key(heat,l,u,h)
|
||
|
|
r={'key':key,'view':field,'heat':heat,'lower':l,'upper':u,'hold':h,
|
||
|
|
'signals':int(select.sum()),'signal_days':int(np.any(select,axis=1).sum()),
|
||
|
|
'filled':int(filled.sum()),'completed':len(v),'unresolved':int(filled.sum()-len(v)),
|
||
|
|
'skipped_buy':int(select.sum()-filled.sum()),'stocks':int(np.any(filled,axis=0).sum()),
|
||
|
|
'mean_daily_net30':mean(means),'mean_daily_excess30':mean(excess),
|
||
|
|
'mean_daily_net60':mean((means+1)*((1-.006)/(1+.006))/((1-.003)/(1+.003))-1),
|
||
|
|
'pooled_mean30':mean(v),'pooled_median30':float(np.median(v)) if len(v) else None,
|
||
|
|
'win_rate30':float((v>0).mean()) if len(v) else None,
|
||
|
|
'p10_net30':float(np.quantile(v,.1)) if len(v) else None,
|
||
|
|
'worst_net30':float(v.min()) if len(v) else None,
|
||
|
|
'delayed_exits':int(np.sum(complete&(exits>np.arange(t)[:,None]+h+1))),
|
||
|
|
'train_days':int(np.isfinite(tr_mean).sum()),'train_completed':int(train.sum()),
|
||
|
|
'train_net30':mean(tr_mean),'train_excess_per_day':mean(tr_excess/h),
|
||
|
|
'test_days':int(np.sum(np.isfinite(means)&test_days)),
|
||
|
|
'test_net30':mean(means[test_days]),'test_excess30':mean(excess[test_days])}
|
||
|
|
for month in sorted(set(d[:7] for d in dates)):
|
||
|
|
r[month+'_net30']=mean(means[np.char.startswith(dates,month)])
|
||
|
|
result.append(r)
|
||
|
|
daily[key]={'net30':[None if not np.isfinite(x) else float(x) for x in means],
|
||
|
|
'excess30':[None if not np.isfinite(x) else float(x) for x in excess]}
|
||
|
|
print(field,'持有',h,'日,网格完成',flush=True)
|
||
|
|
with (out/f'grid_{field}.csv').open('w',newline='') as f:
|
||
|
|
w=csv.DictWriter(f,fieldnames=list(result[0]),lineterminator='\n');w.writeheader();w.writerows(result)
|
||
|
|
with gzip.open(out/f'daily_{field}.json.gz','wt') as f:json.dump(daily,f,separators=(',',':'))
|
||
|
|
return result
|
||
|
|
|
||
|
|
def select_train(rows,p):
|
||
|
|
axes=[p['heat_thresholds'],p['return_lower_pct'],p['return_upper_pct'],p['hold_sessions']]
|
||
|
|
def eligible(r):return r['train_days']>=10 and r['train_completed']>=100 and r['train_excess_per_day'] is not None and r['heat']>0
|
||
|
|
lookup={r['key']:r for r in rows};scored=[]
|
||
|
|
for r in rows:
|
||
|
|
if not eligible(r):continue
|
||
|
|
vals=[r[k] for k in ['heat','lower','upper','hold']];near=[r['train_excess_per_day']]
|
||
|
|
for a in range(4):
|
||
|
|
at=axes[a].index(vals[a])
|
||
|
|
for k in [at-1,at+1]:
|
||
|
|
if 0<=k<len(axes[a]):
|
||
|
|
z=vals.copy();z[a]=axes[a][k];rr=lookup.get(parameter_key(*z))
|
||
|
|
if rr and eligible(rr):near.append(rr['train_excess_per_day'])
|
||
|
|
scored.append({**r,'neighbor_score':float(np.median(near)),'neighbors':len(near)})
|
||
|
|
scored.sort(key=lambda r:(-r['neighbor_score'],-r['hold'],r['heat'],-(r['upper']-r['lower']),r['key']))
|
||
|
|
return scored[0] if scored else None,scored[:20]
|
||
|
|
|
||
|
|
def account(panel,mask,hold,cost,stop=None,detail=False):
|
||
|
|
"""每批次独立到期;卖出失败保留原任务。预算采用前收资产,禁止重复使用现金。"""
|
||
|
|
t,n=mask.shape;stop=t if stop is None else stop
|
||
|
|
cash=1.;prev=1.;lots=[];records=[];journal=[];fees=0.;skipped=0;delays=0
|
||
|
|
max_weight=0.;max_positions=0;max_stale_value=0.;buy_count=sell_count=0
|
||
|
|
for i in range(stop):
|
||
|
|
fee_today=0.;turnover=0.;sell_cash=0.;buy_cash=0.
|
||
|
|
survivors=[]
|
||
|
|
for lot in lots:
|
||
|
|
ix,q,due,sig=lot
|
||
|
|
if i>=due:
|
||
|
|
sell=panel['can_sell'][i,ix]
|
||
|
|
if i==due:delays+=int((~sell).sum())
|
||
|
|
if sell.any():
|
||
|
|
v=q[sell]*panel['open'][i,ix[sell]];fee=float(v.sum()*cost)
|
||
|
|
cash+=float(v.sum())-fee;fee_today+=fee;turnover+=float(v.sum());sell_cash+=float(v.sum())-fee
|
||
|
|
sell_count+=int(sell.sum())
|
||
|
|
if detail:
|
||
|
|
journal.extend({'day':i,'side':'sell','stock':int(j),'qty':float(qty),'price':float(price),'signal':sig}
|
||
|
|
for j,qty,price in zip(ix[sell],q[sell],panel['open'][i,ix[sell]]))
|
||
|
|
ix,q=ix[~sell],q[~sell]
|
||
|
|
if len(ix):survivors.append((ix,q,due,sig))
|
||
|
|
lots=survivors
|
||
|
|
if i>0:
|
||
|
|
chosen=np.flatnonzero(mask[i-1]);count=len(chosen)
|
||
|
|
if count:
|
||
|
|
available=panel['can_buy'][i,chosen];skipped+=int((~available).sum());ix=chosen[available]
|
||
|
|
budget=min(max(cash,0),prev/hold)
|
||
|
|
if len(ix) and budget>0:
|
||
|
|
each=budget/count/(1+cost);q=each/panel['open'][i,ix]
|
||
|
|
value=each*len(ix);fee=value*cost
|
||
|
|
cash-=value+fee;fee_today+=fee;turnover+=value;buy_cash=value+fee
|
||
|
|
lots.append((ix,q,i+hold,i-1));buy_count+=len(ix)
|
||
|
|
if detail:
|
||
|
|
journal.extend({'day':i,'side':'buy','stock':int(j),'qty':float(qty),'price':float(price),'signal':i-1}
|
||
|
|
for j,qty,price in zip(ix,q,panel['open'][i,ix]))
|
||
|
|
values=np.zeros(n)
|
||
|
|
for ix,q,_,_ in lots:np.add.at(values,ix,q*panel['mark'][i,ix])
|
||
|
|
value=float(values.sum());nav=cash+value;assert cash>=-1e-12 and nav>=0
|
||
|
|
max_weight=max(max_weight,float(values.max()/nav) if nav else 0)
|
||
|
|
max_positions=max(max_positions,int(np.count_nonzero(values)))
|
||
|
|
max_stale_value=max(max_stale_value,float(values[~np.isfinite(panel['close'][i])].sum()))
|
||
|
|
fees+=fee_today
|
||
|
|
records.append({'date':str(panel['dates'][i]),'cash':cash,'stock_value':value,'nav':nav,'fee':fee_today,
|
||
|
|
'turnover':turnover,'sell_cash':sell_cash,'buy_cash':buy_cash,'positions':int(np.count_nonzero(values))})
|
||
|
|
prev=nav
|
||
|
|
nav=np.array([1.]+[r['nav'] for r in records]);draw=nav/np.maximum.accumulate(nav)-1
|
||
|
|
summary={'return':float(nav[-1]-1),'max_drawdown':float(draw.min()),'fees_initial_capital':fees,
|
||
|
|
'buy_count':buy_count,'sell_count':sell_count,'skipped_buy':skipped,'delayed_lots':delays,
|
||
|
|
'ending_cash':cash,'ending_stock_value':records[-1]['stock_value'],'open_lots':sum(len(x[0]) for x in lots),
|
||
|
|
'max_stock_weight':max_weight,'max_positions':max_positions,'max_stale_valuation':max_stale_value,
|
||
|
|
'mean_exposure':float(np.mean([r['stock_value']/r['nav'] for r in records if r['buy_cash'] or r['stock_value']])) if buy_count else 0}
|
||
|
|
return {'summary':summary,'daily':records,'journal':journal}
|
||
|
|
|
||
|
|
def main():
|
||
|
|
sys.addaudithook(offline)
|
||
|
|
p=read(ROOT/'protocol.json');assert digest(ROOT/'protocol.json')==(ROOT/'protocol.sha256').read_text().split()[0]
|
||
|
|
assert digest(ROOT/'cache/panel.npz')==read(ROOT/'coverage.json')['panel_sha256']
|
||
|
|
panel=dict(np.load(ROOT/'cache/panel.npz'));out=ROOT/'results';out.mkdir(exist_ok=True)
|
||
|
|
allrows={field:event_grid(panel,p,field,out) for field in ['asof','heat']}
|
||
|
|
winner,top=select_train(allrows['asof'],p)
|
||
|
|
b=p['baseline'];baseline=parameter_key(b['heat'],b['lower'],b['upper'],b['hold'])
|
||
|
|
eligible=[r for r in allrows['asof'] if r['heat']>0 and r['signal_days']>=20 and r['completed']>=100]
|
||
|
|
best=max(eligible,key=lambda r:r['mean_daily_excess30']/r['hold']) if eligible else None
|
||
|
|
lookup={r['key']:r for r in allrows['asof']}
|
||
|
|
candidates=[baseline]+([winner['key']] if winner else [])+([best['key']] if best else [])
|
||
|
|
# 固定基线的四条参数轴,用同一账户规则补充现金、回撤和费用含义。
|
||
|
|
for r in allrows['asof']:
|
||
|
|
if sum([r['heat']!=b['heat'],r['lower']!=b['lower'],r['upper']!=b['upper'],r['hold']!=b['hold']])<=1:candidates.append(r['key'])
|
||
|
|
for k in list(candidates):
|
||
|
|
r=lookup[k];candidates.append(parameter_key(0,r['lower'],r['upper'],r['hold']))
|
||
|
|
accounts={};account_rows=[]
|
||
|
|
for key in sorted(set(candidates)):
|
||
|
|
r=lookup[key];mask=stock_mask(panel,'asof',r['heat'],r['lower'],r['upper'],len(panel['dates'])-12)
|
||
|
|
for fee in p['cost_bps_each_side']:
|
||
|
|
v=account(panel,mask,r['hold'],fee/10000,detail=key in [baseline,winner['key'] if winner else ''])
|
||
|
|
accounts[f'{key}@{fee}']=v
|
||
|
|
account_rows.append({'key':key,'cost_bps':fee,**v['summary']})
|
||
|
|
with (out/'accounts.csv').open('w',newline='') as f:
|
||
|
|
w=csv.DictWriter(f,fieldnames=list(account_rows[0]),lineterminator='\n');w.writeheader();w.writerows(account_rows)
|
||
|
|
with gzip.open(out/'accounts.json.gz','wt') as f:json.dump(accounts,f,separators=(',',':'))
|
||
|
|
# 对入库时区及执行晚一天做固定基线诊断,不参与挑选网格。
|
||
|
|
sensitivities={}
|
||
|
|
for field in ['asof','asof_raw','heat']:
|
||
|
|
m=stock_mask(panel,field,b['heat'],b['lower'],b['upper'],len(panel['dates'])-12)
|
||
|
|
sensitivities[field]=account(panel,m,b['hold'],.003)['summary']
|
||
|
|
delayed=stock_mask(panel,'asof',b['heat'],b['lower'],b['upper'],len(panel['dates'])-12)
|
||
|
|
delayed=np.vstack([np.zeros_like(delayed[:1]),delayed[:-1]])
|
||
|
|
sensitivities['one_more_day_delay']=account(panel,delayed,b['hold'],.003)['summary']
|
||
|
|
dump(out/'selection.json',{'baseline':baseline,'training_winner':winner,'training_top20':top,'full_sample_best_excess_per_day':best,
|
||
|
|
'sensitivity':sensitivities,'grid_rows_per_view':len(allrows['asof']),
|
||
|
|
'account_cases':len(accounts),'common_last_signal':str(panel['dates'][-12])})
|
||
|
|
dump(out/'manifest.json',{'completed_at_beijing':dt.datetime.now(dt.timezone(dt.timedelta(hours=8))).isoformat(),
|
||
|
|
'protocol_sha256':digest(ROOT/'protocol.json'),'coverage_sha256':digest(ROOT/'coverage.json'),
|
||
|
|
'code_sha256':{f.name:digest(f) for f in ROOT.glob('*.py')},
|
||
|
|
'result_sha256':{f.name:digest(f) for f in out.iterdir() if f.name!='manifest.json'}})
|
||
|
|
print('标定计算完成',len(allrows['asof']),'组/视图;账户',len(accounts),flush=True)
|
||
|
|
|
||
|
|
if __name__=='__main__':main()
|