tradingSystem/research/chip_accumulation_20261030/prepare_chips.py

84 lines
5.7 KiB
Python
Raw Permalink Normal View History

"""计算当日筹码特征、固定价格坐标下的变化,并独立核对现存压力表。"""
from collections import defaultdict
import numpy as np
import pandas as pd
from common import ROOT,read,dump,digest,dot,protocol,install_offline
from chip_features import chip_features
def main():
install_offline();protocol();a=dict(np.load(ROOT/'cache/prices.npz'))
di={d:i for i,d in enumerate(a['dates'])};ci={c:j for j,c in enumerate(a['codes'])}
samples=pd.read_csv(ROOT/'cache/samples_before_outcomes.csv.gz',keep_default_na=False)
records={};raw_dist={};audit=defaultdict(int);sources={};checks=[]
requests=read(ROOT/'cache/chip_requests.json')
files=sorted((ROOT/'raw').glob('chips_*.json.gz'))
assert {f.name[6:14] for f in files}==set(requests),'所需筹码导出日期未齐'
trap=read(ROOT/'raw/trap.json.gz')['data'];assert trap['ok']
trapmap={(r['trade_date'],dot(r['symbol'])):r for r in trap['rows']}
for f in files:
data=read(f)['data'];sources[f.name]=digest(f)
assert data['requested_symbols']==requests[f.name[6:14]],'导出股票清单不匹配'
dist=data['distribution'];summary=data['summary'];assert dist['ok'] and summary['ok']
groups=defaultdict(list)
for r in dist['rows']:groups[(r['trade_date'],dot(r['symbol']))].append(r)
sm={(r['trade_date'],dot(r['symbol'])):r for r in summary['rows']}
audit['raw_rows']+=len(dist['rows']);audit['requested_stock_dates']+=len(data['requested_symbols'])
for key,rows in groups.items():
d,c=key
if d not in di or c not in ci:continue
i,j=di[d],ci[c];close=a['raw_close'][i,j]
prices=np.array([r['price'] for r in rows]);weights=np.array([r['percent'] for r in rows],float)
feat=chip_features(prices,weights,close);feat.pop('valleys',None)
times=[r['create_time'] for r in rows if r.get('create_time')]
feat.update(chip_created_min=min(times) if times else '',chip_created_max=max(times) if times else '',
chip_rows=len(rows),date=d,code=c)
if key in sm:
s=sm[key];feat['summary_winner']=s['winner_rate'];feat['summary_cost']=s['weight_avg']
if feat['chip_valid'] and s['winner_rate'] is not None:
feat['winner_summary_gap_pp']=feat['winner_from_dist']*100-s['winner_rate']
if feat['chip_valid'] and s['weight_avg']:
feat['cost_summary_relative_error']=feat['weighted_cost']/s['weight_avg']-1
if feat['chip_valid']:
raw_dist[key]=(prices.astype(float),weights/weights.sum())
if key in trapmap:
t=trapmap[key]
checks.append({'date':d,'code':c,'close_difference':float(close-t['close']) if t['close'] else None,
'above_difference_pp':feat['overhead']*100-t['ocr_above'] if t['ocr_above'] is not None else None,
'far15_difference_pp':feat['overhead_far15']*100-t['ocr_115'] if t['ocr_115'] is not None else None,
'near15_difference_pp':feat['overhead_near15']*100-t['ocr_115'] if t['ocr_115'] is not None else None,
'raw_mass':feat['raw_mass']})
records[key]=feat;audit[feat['chip_reason']]+=1
print(f.name,'筹码股票日',len(groups),flush=True)
rows=[]
for _,r in samples.iterrows():
key=(r['date'],r['code']);f=records.get(key,{'chip_valid':False,'valley_evaluable':False,'chip_reason':'missing_distribution'})
x=dict(r);x.update(f);x['pressure_change20_fixed_price']=np.nan
prev=(r['previous20_date'],r['code'])
if key in raw_dist and prev in raw_dist:
i,j=int(r['i']),int(r['j']);ip=di[prev[0]];oldp,oldw=raw_dist[prev]
factor=a['adj'][ip,j]/a['adj'][i,j]
oldmass=oldw[oldp*factor>a['raw_close'][i,j]].sum()
x['pressure_change20_fixed_price']=float(f['overhead']-oldmass)
x['return_last20']=float(a['close'][i,j]/a['close'][ip,j]-1)
rows.append(x)
frame=pd.DataFrame(rows)
frame.to_csv(ROOT/'cache/features_before_outcomes.csv.gz',index=False,compression={'method':'gzip','mtime':0})
pd.DataFrame(records.values()).to_csv(ROOT/'cache/chip_features_all.csv.gz',index=False,compression={'method':'gzip','mtime':0})
pd.DataFrame(checks).to_csv(ROOT/'trap_reconciliation.csv',index=False)
valid=frame[frame.chip_valid]
cov={'source_sha256':sources,'audit':dict(audit),'samples':len(frame),'valid_chip_samples':len(valid),
'valley_evaluable_samples':int(frame.valley_evaluable.sum()),'upper_gap_samples':int(valid.upper_gap.sum()) if len(valid) else 0,
'above_valley_samples':int(valid.valley_above.sum()) if len(valid) else 0,
'chip_created_later_than_data_day':int((valid.chip_created_max.str[:10]>valid.date).sum()) if len(valid) else 0,
'fixed_price_change_pairs':int(frame.pressure_change20_fixed_price.notna().sum()),'trap_reconciliation_rows':len(checks)}
if len(checks):
q=pd.DataFrame(checks)
cov['trap_max_abs_difference_pp']={k:float(q[k].abs().max()) for k in ['above_difference_pp','far15_difference_pp','near15_difference_pp']}
if len(valid):
cov['winner_summary_abs_gap_pp_quantiles']={str(k):float(v) for k,v in valid.winner_summary_gap_pp.abs().quantile([.5,.9,.99]).items()}
cov['weighted_cost_abs_error_quantiles']={str(k):float(v) for k,v in valid.cost_summary_relative_error.abs().quantile([.5,.9,.99]).items()}
dump(ROOT/'chip_coverage.json',cov)
print('有效筹码样本',len(valid),'上方稀疏',cov['upper_gap_samples'],'上方双峰断档',cov['above_valley_samples'],flush=True)
if __name__=='__main__':main()