76 lines
4.8 KiB
Python
76 lines
4.8 KiB
Python
|
|
"""纯离线收益、配对与不确定性计算。"""
|
|||
|
|
import numpy as np
|
|||
|
|
|
|||
|
|
def outcome(a,i,j,hold=60):
|
|||
|
|
t=len(a['dates']);entry=i+1;due=entry+hold
|
|||
|
|
r={'entry_index':entry,'due_index':due,'calendar_matured':bool(due<t),
|
|||
|
|
'entry_filled':False,'completed':False,'entry_date':None,'exit_date':None,
|
|||
|
|
'exit_delay':None,'gross':np.nan,'net30':np.nan,'net60':np.nan,
|
|||
|
|
'path_complete':False,'hit15':np.nan,'up_before_down':np.nan,
|
|||
|
|
'max_close_gain':np.nan,'max_close_loss':np.nan}
|
|||
|
|
if entry>=t:return r
|
|||
|
|
r['entry_date']=str(a['dates'][entry])
|
|||
|
|
if not a['can_buy'][entry,j]:return r
|
|||
|
|
r['entry_filled']=True;price=a['open'][entry,j]
|
|||
|
|
if due>=t:return r
|
|||
|
|
path=a['close'][entry:due,j]/price-1
|
|||
|
|
r['path_complete']=bool(np.isfinite(path).all())
|
|||
|
|
if r['path_complete']:
|
|||
|
|
hi=np.flatnonzero(path>=.15);lo=np.flatnonzero(path<=-.10)
|
|||
|
|
r.update(hit15=float(len(hi)>0),up_before_down=float(len(hi)>0 and (not len(lo) or hi[0]<lo[0])),
|
|||
|
|
max_close_gain=float(path.max()),max_close_loss=float(min(0,path.min())))
|
|||
|
|
exits=np.flatnonzero(a['can_sell'][due:,j])
|
|||
|
|
if not len(exits):return r
|
|||
|
|
end=due+int(exits[0]);gross=a['open'][end,j]/price
|
|||
|
|
r.update(completed=True,exit_date=str(a['dates'][end]),exit_delay=end-due,gross=float(gross),
|
|||
|
|
net30=float(gross*.997/1.003-1),net60=float(gross*.994/1.006-1))
|
|||
|
|
return r
|
|||
|
|
|
|||
|
|
def match_pairs(frame,treatment,extra_pressure=False,day_count_caliper=None):
|
|||
|
|
"""先只用信号日特征匹配。不会读取收益、成交或未来日期字段。"""
|
|||
|
|
rows=[];unmatched=0;treated=0
|
|||
|
|
fields=['ret60','log_cap','log_vol','log_turn','position60']
|
|||
|
|
cal=np.array([.05,np.log(2),np.log(2),np.log(2),.20])
|
|||
|
|
if extra_pressure:fields+=['overhead'];cal=np.r_[cal,.10]
|
|||
|
|
if day_count_caliper is not None:fields+=['clear_days60'];cal=np.r_[cal,day_count_caliper]
|
|||
|
|
f=frame.copy();f['treatment']=treatment
|
|||
|
|
f=f[np.isfinite(f[fields]).all(axis=1)&f.industry.notna()&(f.industry!='')]
|
|||
|
|
for (day,industry),g in f.groupby(['date','industry'],sort=True):
|
|||
|
|
active=g[g.treatment].sort_values('code');control=g[~g.treatment].sort_values('code')
|
|||
|
|
used=set()
|
|||
|
|
for idx,row in active.iterrows():
|
|||
|
|
treated+=1
|
|||
|
|
c=control.loc[~control.index.isin(used)]
|
|||
|
|
if c.empty:unmatched+=1;continue
|
|||
|
|
diff=np.abs(c[fields].to_numpy(float)-row[fields].to_numpy(float))
|
|||
|
|
valid=(diff<=cal+1e-12).all(axis=1)
|
|||
|
|
if not valid.any():unmatched+=1;continue
|
|||
|
|
distance=np.sum((diff/cal)**2,axis=1);distance[~valid]=np.inf
|
|||
|
|
target=c.index[int(np.argmin(distance))];used.add(target)
|
|||
|
|
rows.append({'treat_id':int(idx),'control_id':int(target),'date':day,'industry':industry,
|
|||
|
|
'distance':float(distance.min()),'treat_code':row['code'],'control_code':c.loc[target,'code']})
|
|||
|
|
return rows,{'treated_with_matching_fields':treated,'unmatched':unmatched,'matched':len(rows),'calipers':dict(zip(fields,cal.tolist()))}
|
|||
|
|
|
|||
|
|
def cluster_intervals(values,time_indices,treat_codes,control_codes,reps=1000,seed=20261030):
|
|||
|
|
"""固定匹配后,分别整块重抽时间与联合重抽两端股票。区间仅描述性使用。"""
|
|||
|
|
values=np.asarray(values,float);time_indices=np.asarray(time_indices,int)
|
|||
|
|
ok=np.isfinite(values);values=values[ok];time_indices=time_indices[ok]
|
|||
|
|
tc=np.asarray(treat_codes)[ok];cc=np.asarray(control_codes)[ok]
|
|||
|
|
if not len(values):return {'n':0,'time_blocks':0,'time_interval':None,'stock_interval':None}
|
|||
|
|
blocks=np.unique(time_indices//60);bi=np.searchsorted(blocks,time_indices//60)
|
|||
|
|
stocks=np.unique(np.r_[tc,cc]);ti=np.searchsorted(stocks,tc);ci=np.searchsorted(stocks,cc)
|
|||
|
|
rng=np.random.default_rng(seed);tb=[];sb=[]
|
|||
|
|
for _ in range(reps):
|
|||
|
|
if len(blocks)>1:
|
|||
|
|
count=rng.multinomial(len(blocks),np.ones(len(blocks))/len(blocks));w=count[bi]
|
|||
|
|
if w.sum():tb.append(float(np.sum(w*values)/w.sum()))
|
|||
|
|
count=rng.multinomial(len(stocks),np.ones(len(stocks))/len(stocks));w=count[ti]*count[ci]
|
|||
|
|
if w.sum():sb.append(float(np.sum(w*values)/w.sum()))
|
|||
|
|
degenerate=bool(np.ptp(values)==0)
|
|||
|
|
def interval(x):return np.quantile(x,[.025,.975]).tolist() if len(x)>50 and not degenerate else None
|
|||
|
|
return {'n':len(values),'mean':float(values.mean()),'time_blocks':len(blocks),'unique_stocks':len(stocks),
|
|||
|
|
'time_interval':interval(tb),'stock_interval':interval(sb),'formal_p_value':None,
|
|||
|
|
'degenerate_observed_differences':degenerate,
|
|||
|
|
'interval_note':'各配对观察差完全相同,经验重抽退化,不能给出有效不确定性区间。' if degenerate else '少量簇的重抽区间只作描述。',
|
|||
|
|
'interpretation':'固定配对的描述性区间;少于8个时间块不进行正式显著性判断。'}
|