144 lines
7.9 KiB
Python
144 lines
7.9 KiB
Python
|
|
"""仅处理本地缓存,生成日期×股票矩阵和热度可用性证据。"""
|
|||
|
|
import bisect
|
|||
|
|
import datetime as dt
|
|||
|
|
import gzip
|
|||
|
|
import hashlib
|
|||
|
|
import json
|
|||
|
|
import re
|
|||
|
|
import sys
|
|||
|
|
from collections import defaultdict
|
|||
|
|
from pathlib import Path
|
|||
|
|
|
|||
|
|
import numpy as np
|
|||
|
|
|
|||
|
|
ROOT = Path(__file__).resolve().parent
|
|||
|
|
OLD = ROOT.parent/'macro_timing_20261026'
|
|||
|
|
|
|||
|
|
def offline(event,args):
|
|||
|
|
if event in ('socket.connect','socket.getaddrinfo','socket.sendto','socket.sendmsg'):
|
|||
|
|
raise RuntimeError('离线研究禁止联网')
|
|||
|
|
|
|||
|
|
def read(path):
|
|||
|
|
return json.load(gzip.open(path) if str(path).endswith('.gz') else open(path))
|
|||
|
|
|
|||
|
|
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 dot(code):
|
|||
|
|
if re.fullmatch(r'(SH|SZ|BJ)\d{6}',code): return code[2:]+'.'+code[:2]
|
|||
|
|
return code
|
|||
|
|
|
|||
|
|
def chosen_batch(rows, deadline=None, offset_hours=8):
|
|||
|
|
"""整批最晚入库时间小于截止时间才可用,不能逐股混合不同批次。"""
|
|||
|
|
batches=defaultdict(list)
|
|||
|
|
for r in rows: batches[r['batch_no']].append(r)
|
|||
|
|
eligible=[]
|
|||
|
|
for b,rr in batches.items():
|
|||
|
|
stamp=max(dt.datetime.fromisoformat(r['create_time']) for r in rr)
|
|||
|
|
if deadline is None or stamp+dt.timedelta(hours=offset_hours)<deadline:
|
|||
|
|
eligible.append(b)
|
|||
|
|
return batches[max(eligible)] if eligible else []
|
|||
|
|
|
|||
|
|
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)
|
|||
|
|
ix=tracked(OLD/'raw/export.json')['data']['index_daily']['000001.SH']['rows']
|
|||
|
|
calendar=sorted({r['timestamp'][:10] for r in ix if r['timestamp'][:10]<=p['data_cutoff']})
|
|||
|
|
dates=[d for d in calendar if d>='2026-04-27']
|
|||
|
|
heat=[]
|
|||
|
|
for path in sorted((ROOT/'raw').glob('2026*.json.gz')):
|
|||
|
|
d=tracked(path)['data'];assert d['ok'];heat+=d['rows']
|
|||
|
|
codes=sorted({dot(r['stock_code']) for r in heat})
|
|||
|
|
ci={c:i for i,c in enumerate(codes)};di={d:i for i,d in enumerate(dates)}
|
|||
|
|
shape=(len(dates),len(codes))
|
|||
|
|
arrays={k:np.full(shape,np.nan) for k in ['open','close','mark','pct','adj','raw_open','up','down','volume','amount','heat','asof','asof_raw']}
|
|||
|
|
risk=np.zeros(shape,dtype=bool);quality=defaultdict(int)
|
|||
|
|
# 原始行情缓存只读复用;不把微盘402只股票名单带入本次全市场研究。
|
|||
|
|
for ym in [f'2026{m:02}' for m in range(4,11)]:
|
|||
|
|
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']
|
|||
|
|
seen=set()
|
|||
|
|
for r in data['bars']['rows']:
|
|||
|
|
day=r['trade_date'][:10];code=r['ts_code']
|
|||
|
|
if day not in di or code not in ci:continue
|
|||
|
|
i,j=di[day],ci[code]
|
|||
|
|
assert (i,j) not in seen;seen.add((i,j))
|
|||
|
|
for key,src in [('raw_open','open'),('pct','pct_chg'),('adj','adj_factor'),('volume','vol'),('amount','amount')]:
|
|||
|
|
v=r[src];arrays[key][i,j]=float(v) if v is not None else np.nan
|
|||
|
|
a=arrays['adj'][i,j]
|
|||
|
|
if a>0 and r['open'] and r['close'] and r['open']>0 and r['close']>0:
|
|||
|
|
arrays['open'][i,j]=float(r['open'])*a;arrays['close'][i,j]=float(r['close'])*a
|
|||
|
|
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']:
|
|||
|
|
v=r[k+'_limit'];arrays[k][i,j]=float(v) if v else np.nan
|
|||
|
|
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,dtype=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(arrays['pct'][i,j])
|
|||
|
|
groups=defaultdict(list)
|
|||
|
|
for r in heat:groups[r['trade_date']].append(r)
|
|||
|
|
coverage=[]
|
|||
|
|
for i,day in enumerate(dates):
|
|||
|
|
rr=groups.get(day,[])
|
|||
|
|
deadline=dt.datetime.fromisoformat(dates[i+1]+'T09:25:00') if i+1<len(dates) else None
|
|||
|
|
selected={k:chosen_batch(rr,deadline if k!='heat' else None,hours) if i+1<len(dates) or k=='heat' else []
|
|||
|
|
for k,hours in [('heat',8),('asof',8),('asof_raw',0)]}
|
|||
|
|
for k,rs in selected.items():
|
|||
|
|
seen=set()
|
|||
|
|
for r in rs:
|
|||
|
|
c=dot(r['stock_code']);assert c not in seen;seen.add(c)
|
|||
|
|
v=float(r['score']);assert 0<=v<=1
|
|||
|
|
arrays[k][i,ci[c]]=v
|
|||
|
|
coverage.append({'date':day,'raw_rows':len(rr),'latest_batch':selected['heat'][0]['batch_no'] if selected['heat'] else None,
|
|||
|
|
'latest_create_min':min((r['create_time'] for r in selected['heat']),default=None),
|
|||
|
|
'latest_create_max':max((r['create_time'] for r in selected['heat']),default=None),
|
|||
|
|
'heat_stocks':len(selected['heat']),'asof_stocks':len(selected['asof']),
|
|||
|
|
'asof_raw_stocks':len(selected['asof_raw']),
|
|||
|
|
'eligible':int(np.sum(eligible[i]&np.isfinite(arrays['heat'][i]))),
|
|||
|
|
'missing_quotes':int(np.sum(np.isfinite(arrays['heat'][i])&~np.isfinite(arrays['open'][i])))})
|
|||
|
|
valid=np.isfinite(arrays['open'])&(arrays['open']>0)&(arrays['volume']>0)
|
|||
|
|
can_buy=valid&np.isfinite(arrays['up'])&np.isfinite(arrays['down'])&(arrays['raw_open']<arrays['up']-.005)&(arrays['raw_open']>arrays['down']+.005)&~risk
|
|||
|
|
can_sell=valid&np.isfinite(arrays['down'])&(arrays['raw_open']>arrays['down']+.005)
|
|||
|
|
# 估值只向前持有最后已知价;缺价20个交易日后归零并记录,绝不倒填未来价格。
|
|||
|
|
last=np.zeros(len(codes));age=np.full(len(codes),1000)
|
|||
|
|
for i in range(len(dates)):
|
|||
|
|
good=np.isfinite(arrays['close'][i])&(arrays['close'][i]>0)
|
|||
|
|
last[good]=arrays['close'][i,good];age[good]=0;age[~good]+=1
|
|||
|
|
arrays['mark'][i]=np.where(age>20,0,last)
|
|||
|
|
cache=ROOT/'cache';cache.mkdir(exist_ok=True)
|
|||
|
|
np.savez_compressed(cache/'panel.npz',dates=dates,codes=codes,eligible=eligible,can_buy=can_buy,can_sell=can_sell,**arrays)
|
|||
|
|
c={'created_at_beijing':dt.datetime.now(dt.timezone(dt.timedelta(hours=8))).isoformat(),
|
|||
|
|
'raw_heat_rows':len(heat),'raw_heat_dates':len(groups),'raw_heat_first':min(groups),'raw_heat_last':max(groups),
|
|||
|
|
'dates':len(dates),'stocks':len(codes),'exchanges':sorted({c[-2:] for c in codes}),
|
|||
|
|
'common_last_signal':dates[-12],'daily':coverage,'quality':dict(quality),
|
|||
|
|
'source_sha256':sources,'panel_sha256':digest(cache/'panel.npz'),
|
|||
|
|
'timestamp_note':'create_time为DATETIME,未找到上游写入代码核实其时区。主口径按原值+8小时,原值另作敏感性,均不将回填数据倒用。'}
|
|||
|
|
dump(ROOT/'coverage.json',c)
|
|||
|
|
print(json.dumps({k:v for k,v in c.items() if k not in ['daily','source_sha256']},ensure_ascii=False))
|
|||
|
|
|
|||
|
|
if __name__=='__main__':main()
|