110 lines
8.0 KiB
Python
110 lines
8.0 KiB
Python
|
|
"""离线拼接评分、全市场复权行情、历史资格及截至当日可知的市场阶段。"""
|
||
|
|
import bisect, datetime as dt, gzip, hashlib, json, re, sys
|
||
|
|
from collections import defaultdict
|
||
|
|
from pathlib import Path
|
||
|
|
import numpy as np
|
||
|
|
import pandas as pd
|
||
|
|
ROOT=Path(__file__).resolve().parent
|
||
|
|
OLD=ROOT.parent/'macro_timing_20261026'
|
||
|
|
def read(path):
|
||
|
|
with gzip.open(path,'rt') if str(path).endswith('.gz') else open(path) as f:return json.load(f)
|
||
|
|
def dump(path,value):path.write_text(json.dumps(value,ensure_ascii=False,indent=2,allow_nan=False)+'\n')
|
||
|
|
def digest(path):return hashlib.sha256(path.read_bytes()).hexdigest()
|
||
|
|
def offline(event,args):
|
||
|
|
if event in ('socket.connect','socket.getaddrinfo','socket.sendto','socket.sendmsg'):raise RuntimeError('离线研究禁止联网')
|
||
|
|
def dot(code):return code[2:]+'.'+code[:2] if re.fullmatch(r'(SH|SZ|BJ)\d{6}',code) else code
|
||
|
|
def regime(rows,dates):
|
||
|
|
series=pd.Series({r['timestamp'][:10]:float(r['close']) for r in rows}).sort_index()
|
||
|
|
ma=series.rolling(60,min_periods=60).mean();r20=series/series.shift(20)-1
|
||
|
|
stage=np.where((series>=ma)&(r20>0),1,np.where((series<ma)&(r20<0),-1,0))
|
||
|
|
result=pd.DataFrame({'close':series,'ma60':ma,'return20':r20,'stage':stage})
|
||
|
|
assert result.loc[dates,['close','ma60','return20']].notna().all().all()
|
||
|
|
return result.loc[dates]
|
||
|
|
def main():
|
||
|
|
sys.addaudithook(offline);p=read(ROOT/'protocol.json');assert digest(ROOT/'protocol.json')==(ROOT/'protocol.sha256').read_text().split()[0]
|
||
|
|
sources={}
|
||
|
|
def tracked(path):sources[str(path.relative_to(ROOT.parent))]=digest(path);return read(path)
|
||
|
|
export=tracked(OLD/'raw/export.json')['data']['index_daily']
|
||
|
|
calendar=sorted({r['timestamp'][:10] for r in export['000001.SH']['rows'] if r['timestamp'][:10]<=p['data_cutoff']})
|
||
|
|
dates=[d for d in calendar if d>=p['source_start']];di={d:i for i,d in enumerate(dates)}
|
||
|
|
scores=[];total_raw=0;raw_dates=set()
|
||
|
|
for path in sorted((ROOT/'raw').glob('20*.json.gz')):
|
||
|
|
rr=tracked(path)['data'];total_raw+=len(rr);raw_dates.update(r['trade_date'] for r in rr)
|
||
|
|
scores.extend(r for r in rr if r['trade_date'] in di)
|
||
|
|
codes=sorted({dot(r['ts_code']) for r in scores if dot(r['ts_code'])[-2:] in ('SH','SZ')});ci={c:j for j,c in enumerate(codes)}
|
||
|
|
shape=(len(dates),len(codes));a={k:np.full(shape,np.nan) for k in ['open','close','mark','adj','raw_open','up','down','volume','total','smart','sector']}
|
||
|
|
score_seen=set()
|
||
|
|
for r in scores:
|
||
|
|
c=dot(r['ts_code'])
|
||
|
|
if c not in ci:continue
|
||
|
|
i,j=di[r['trade_date']],ci[c];assert (i,j) not in score_seen;score_seen.add((i,j))
|
||
|
|
for k in ['total','smart','sector']:
|
||
|
|
v=r[k+'_score']
|
||
|
|
if v is not None:assert 0<=v<=1;a[k][i,j]=v
|
||
|
|
del scores,score_seen
|
||
|
|
risk=np.zeros(shape,bool);quality=defaultdict(int)
|
||
|
|
repairs=tracked(OLD/'raw/timed_micro100/small_gap_candidates.json')
|
||
|
|
legacy=tracked(OLD/'raw/timed_micro100/gap_legacy.json.gz');assert legacy['ok']
|
||
|
|
wanted={(r['date'],r['code']) for r in repairs};legacy_map={(r['trade_date'],r['ts_code']):r for r in legacy['rows']}
|
||
|
|
repair_log=[]
|
||
|
|
for ym in sorted({d[:7].replace('-','') for d in dates}):
|
||
|
|
folder='timed_micro100' if ym<='202608' else 'micro100'
|
||
|
|
data=tracked(OLD/f'raw/{folder}/{ym}.json.gz')['data']
|
||
|
|
for key in ['bars','st','limits']:assert data[key]['ok']
|
||
|
|
rr=data['bars']['rows'];existing={(r['trade_date'][:10],r['ts_code']) for r in rr}
|
||
|
|
for r in rr:
|
||
|
|
key=(r['trade_date'][:10],r['ts_code'])
|
||
|
|
if key in legacy_map:
|
||
|
|
for k in ['open','close','adj_factor']:
|
||
|
|
if r[k] is not None and legacy_map[key][k] is not None:assert abs(r[k]-legacy_map[key][k])<1e-5
|
||
|
|
for day,c in sorted(wanted):
|
||
|
|
if day[:7].replace('-','')==ym and day in di and c in ci:
|
||
|
|
assert (day,c) not in existing;rr.append(legacy_map[day,c]);repair_log.append({'date':day,'code':c})
|
||
|
|
seen=set()
|
||
|
|
for r in rr:
|
||
|
|
day=r['trade_date'][:10];c=r['ts_code']
|
||
|
|
if day not in di or c not in ci:continue
|
||
|
|
i,j=di[day],ci[c];assert (i,j) not in seen;seen.add((i,j))
|
||
|
|
for k,s in [('raw_open','open'),('adj','adj_factor'),('volume','vol')]:
|
||
|
|
if r[s] is not None:a[k][i,j]=float(r[s])
|
||
|
|
if a['adj'][i,j]>0 and r['open'] and r['close'] and r['open']>0 and r['close']>0:
|
||
|
|
a['open'][i,j]=r['open']*a['adj'][i,j];a['close'][i,j]=r['close']*a['adj'][i,j]
|
||
|
|
for r in data['limits']['rows']:
|
||
|
|
if r['trade_date'][:10] in di and r['ts_code'] in ci:
|
||
|
|
i,j=di[r['trade_date'][:10]],ci[r['ts_code']]
|
||
|
|
for k in ['up','down']:
|
||
|
|
if r[k+'_limit']:a[k][i,j]=r[k+'_limit']
|
||
|
|
for r in data['st']['rows']:
|
||
|
|
if r['trade_date'][:10] in di and r['ts_code'] in ci:risk[di[r['trade_date'][:10]],ci[r['ts_code']]]=True
|
||
|
|
print(ym,'行情就绪',flush=True)
|
||
|
|
ref=tracked(OLD/'raw/micro100/reference.json.gz')['data'];listing={r['stock_code']:r['list_date'] for r in ref['listings']['rows']}
|
||
|
|
names=defaultdict(list)
|
||
|
|
for r in ref['names']['rows']:names[r['ts_code']].append(r)
|
||
|
|
eligible=np.zeros(shape,bool)
|
||
|
|
for j,c in enumerate(codes):
|
||
|
|
ld=listing.get(c)
|
||
|
|
if not ld:quality['missing_listing_codes']+=1;continue
|
||
|
|
for i,day in enumerate(dates):
|
||
|
|
if bisect.bisect_right(calendar,day)-bisect.bisect_left(calendar,ld)<120:continue
|
||
|
|
nr=[r for r in names[c] if r['start_date']<=day and (not r['end_date'] or day<=r['end_date']) and (not r['ann_date'] or r['ann_date']<=day)]
|
||
|
|
if not nr:quality['missing_historical_name_stock_days']+=1;continue
|
||
|
|
name=max(nr,key=lambda r:r['start_date'])['name']
|
||
|
|
eligible[i,j]=not risk[i,j] and not re.search(r'ST|退',name,re.I) and np.isfinite(a['close'][i,j])
|
||
|
|
valid=np.isfinite(a['open'])&(a['open']>0)&(a['volume']>0)
|
||
|
|
buy=valid&np.isfinite(a['up'])&np.isfinite(a['down'])&(a['raw_open']<a['up']-.005)&(a['raw_open']>a['down']+.005)&~risk
|
||
|
|
sell=valid&np.isfinite(a['down'])&(a['raw_open']>a['down']+.005)
|
||
|
|
fallback=np.array([np.isfinite(a['smart'][i]).any() and np.all(a['smart'][i,np.isfinite(a['smart'][i])]==0) and np.all(a['sector'][i,np.isfinite(a['sector'][i])]==0) for i in range(len(dates))])
|
||
|
|
scored=np.isfinite(a['total'])&np.isfinite(a['smart']);eligible&=scored&~fallback[:,None]
|
||
|
|
last=np.zeros(len(codes));age=np.full(len(codes),1000)
|
||
|
|
for i in range(len(dates)):
|
||
|
|
good=np.isfinite(a['close'][i])&(a['close'][i]>0);last[good]=a['close'][i,good];age[good]=0;age[~good]+=1;a['mark'][i]=np.where(age>20,0,last)
|
||
|
|
stage300=regime(export['000300.SH']['rows'],dates)
|
||
|
|
stage2000=regime(tracked(OLD/'raw/csi2000.json')['data']['daily']['rows'],dates)
|
||
|
|
stage300.add_prefix('csi300_').join(stage2000.add_prefix('csi2000_')).rename_axis('date').to_csv(ROOT/'regimes.csv',lineterminator='\n')
|
||
|
|
cache=ROOT/'cache';cache.mkdir(exist_ok=True)
|
||
|
|
np.savez_compressed(cache/'panel.npz',dates=dates,codes=codes,eligible=eligible,can_buy=buy,can_sell=sell,regime300=stage300.stage.to_numpy(),regime2000=stage2000.stage.to_numpy(),**a)
|
||
|
|
daily=[{'date':day,'scored':int(scored[i].sum()),'eligible':int(eligible[i].sum()),'missing_quotes':int((scored[i]&~np.isfinite(a['open'][i])).sum()),'fallback':bool(fallback[i]),'regime300':int(stage300.stage.iloc[i]),'regime2000':int(stage2000.stage.iloc[i])} for i,day in enumerate(dates)]
|
||
|
|
cov={'created_at_beijing':dt.datetime.now(dt.timezone(dt.timedelta(hours=8))).isoformat(),'source_rows':total_raw,'source_dates':len(raw_dates),'source_first':min(raw_dates),'source_last':max(raw_dates),'panel_dates':len(dates),'stocks':len(codes),'common_last_signal':dates[-13],'daily':daily,'quality':dict(quality),'repairs':repair_log,'fallback_dates':[d for d,f in zip(dates,fallback) if f],'source_sha256':sources,'panel_sha256':digest(cache/'panel.npz')}
|
||
|
|
dump(ROOT/'coverage.json',cov);print(json.dumps({k:v for k,v in cov.items() if k not in ['daily','source_sha256']},ensure_ascii=False))
|
||
|
|
if __name__=='__main__':main()
|