107 lines
6.2 KiB
Python
107 lines
6.2 KiB
Python
|
|
"""复用已核验的全市场原始行情;不读取或筛选未来收益。"""
|
|||
|
|
import bisect
|
|||
|
|
import collections
|
|||
|
|
import re
|
|||
|
|
import numpy as np
|
|||
|
|
import pandas as pd
|
|||
|
|
from common import ROOT,OLD,read,dump,digest,dot,protocol,install_offline
|
|||
|
|
|
|||
|
|
def main():
|
|||
|
|
install_offline();p=protocol();sources={}
|
|||
|
|
def tracked(path):
|
|||
|
|
sources[str(path.relative_to(ROOT.parent))]=digest(path);return read(path)
|
|||
|
|
exp=tracked(OLD/'raw/export.json')['data']['index_daily']['000001.SH']['rows']
|
|||
|
|
calendar=sorted({r['timestamp'][:10] for r in exp})
|
|||
|
|
recent=tracked(ROOT/'raw/recent_prices.json.gz')['data']
|
|||
|
|
recent_dates=sorted({r['trade_date'] for r in recent['bars']['rows']})
|
|||
|
|
calendar=sorted(set(calendar)|set(recent_dates))
|
|||
|
|
dates=[d for d in calendar if p['price_source_start']<=d<=p['data_cutoff']]
|
|||
|
|
di={d:i for i,d in enumerate(dates)}
|
|||
|
|
monthly=[]
|
|||
|
|
for ym in sorted({d[:7].replace('-','') for d in dates}):
|
|||
|
|
folder='timed_micro100' if ym<='202608' else 'micro100'
|
|||
|
|
f=OLD/f'raw/{folder}/{ym}.json.gz'
|
|||
|
|
monthly.append((f,tracked(f)['data']))
|
|||
|
|
monthly.append((ROOT/'raw/recent_prices.json.gz',recent))
|
|||
|
|
codes=sorted({r['ts_code'] for _,data in monthly for r in data['bars']['rows'] if r['ts_code'].endswith(('.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 ['raw_open','raw_close','open','close','low','high','adj','volume','market_cap','turnover','up','down']}
|
|||
|
|
risk=np.zeros(shape,bool);seen=set();repairs=[]
|
|||
|
|
repairlist=tracked(OLD/'raw/timed_micro100/small_gap_candidates.json')
|
|||
|
|
legacy=tracked(OLD/'raw/timed_micro100/gap_legacy.json.gz');assert legacy['ok']
|
|||
|
|
lm={(r['trade_date'][:10],r['ts_code']):r for r in legacy['rows']}
|
|||
|
|
wanted={(r['date'],r['code']) for r in repairlist}
|
|||
|
|
for path,data in monthly:
|
|||
|
|
assert all(data[k]['ok'] for k in ['bars','st','limits'])
|
|||
|
|
for r in data['bars']['rows']:
|
|||
|
|
d,c=r['trade_date'][:10],r['ts_code']
|
|||
|
|
if d not in di or c not in ci:continue
|
|||
|
|
i,j=di[d],ci[c]
|
|||
|
|
assert (i,j) not in seen,(d,c,path)
|
|||
|
|
seen.add((i,j))
|
|||
|
|
for dest,src in [('raw_open','open'),('raw_close','close'),('volume','vol'),('market_cap','total_mv'),('turnover','turnover_rate'),('adj','adj_factor')]:
|
|||
|
|
if r.get(src) is not None:a[dest][i,j]=r[src]
|
|||
|
|
adj=a['adj'][i,j]
|
|||
|
|
if adj>0:
|
|||
|
|
for k in ['open','close','low','high']:
|
|||
|
|
if r.get(k) and r[k]>0:a[k][i,j]=r[k]*adj
|
|||
|
|
for r in data['limits']['rows']:
|
|||
|
|
d,c=r['trade_date'][:10],r['ts_code']
|
|||
|
|
if d not in di or c not in ci:continue
|
|||
|
|
for k in ['up','down']:
|
|||
|
|
if r.get(k+'_limit'):a[k][di[d],ci[c]]=r[k+'_limit']
|
|||
|
|
for r in data['st']['rows']:
|
|||
|
|
d,c=r['trade_date'][:10],r['ts_code']
|
|||
|
|
if d in di and c in ci:risk[di[d],ci[c]]=True
|
|||
|
|
for d,c in sorted(wanted):
|
|||
|
|
if d not in di or c not in ci:continue
|
|||
|
|
i,j=di[d],ci[c]
|
|||
|
|
if (i,j) in seen:continue
|
|||
|
|
r=lm[(d,c)];adj=r.get('adj_factor')
|
|||
|
|
if adj and r.get('open') and r.get('close'):
|
|||
|
|
for dest,src in [('raw_open','open'),('raw_close','close'),('volume','vol'),('market_cap','total_mv'),('turnover','turnover_rate'),('adj','adj_factor')]:
|
|||
|
|
if r.get(src) is not None:a[dest][i,j]=r[src]
|
|||
|
|
for k in ['open','close','low','high']:
|
|||
|
|
if r.get(k):a[k][i,j]=r[k]*adj
|
|||
|
|
repairs.append({'date':d,'code':c})
|
|||
|
|
ref=tracked(OLD/'raw/micro100/reference.json.gz')['data']
|
|||
|
|
listing={r['stock_code']:r['list_date'] for r in ref['listings']['rows']}
|
|||
|
|
names=collections.defaultdict(list)
|
|||
|
|
for r in ref['names']['rows']:names[r['ts_code']].append(r)
|
|||
|
|
eligible=np.zeros(shape,bool);missing_listing=[];missing_name=0
|
|||
|
|
for j,c in enumerate(codes):
|
|||
|
|
ld=listing.get(c)
|
|||
|
|
if not ld:missing_listing.append(c);continue
|
|||
|
|
for i,d in enumerate(dates):
|
|||
|
|
if bisect.bisect_right(calendar,d)-bisect.bisect_left(calendar,ld)<120:continue
|
|||
|
|
nr=[r for r in names[c] if r['start_date']<=d and (not r['end_date'] or d<=r['end_date']) and (not r['ann_date'] or r['ann_date']<=d)]
|
|||
|
|
if not nr:missing_name+=1;continue
|
|||
|
|
name=max(nr,key=lambda r:r['start_date'])['name']
|
|||
|
|
eligible[i,j]=not risk[i,j] and not re.search('ST|退',name,re.I) and a['close'][i,j]>0
|
|||
|
|
tradable=(a['open']>0)&(a['volume']>0)&np.isfinite(a['up'])&np.isfinite(a['down'])
|
|||
|
|
can_buy=tradable&(a['raw_open']<a['up']-.005)&(a['raw_open']>a['down']+.005)&~risk
|
|||
|
|
can_sell=(a['open']>0)&(a['volume']>0)&np.isfinite(a['down'])&(a['raw_open']>a['down']+.005)
|
|||
|
|
cl=pd.DataFrame(a['close'])
|
|||
|
|
ret60=(cl/cl.shift(60)-1).to_numpy()
|
|||
|
|
x=np.arange(61,dtype=float);x-=x.mean()
|
|||
|
|
slope=np.full(shape,np.nan)
|
|||
|
|
logs=np.log(a['close'])
|
|||
|
|
for i in range(60,len(dates)):
|
|||
|
|
w=logs[i-60:i+1];slope[i]=np.sum(w*x[:,None],axis=0)/np.sum(x*x)
|
|||
|
|
volatility=np.log(cl/cl.shift()).rolling(60,min_periods=60).std().to_numpy()
|
|||
|
|
turn20=pd.DataFrame(a['turnover']).rolling(20,min_periods=20).mean().to_numpy()
|
|||
|
|
position=np.full(shape,np.nan)
|
|||
|
|
for i in range(60,len(dates)):
|
|||
|
|
w=a['close'][i-60:i]
|
|||
|
|
valid=np.isfinite(w).all(axis=0)&np.isfinite(a['close'][i])
|
|||
|
|
position[i,valid]=(w[:,valid]<a['close'][i,valid]).mean(axis=0)
|
|||
|
|
np.savez_compressed(ROOT/'cache/prices.npz',**a,dates=np.array(dates),codes=np.array(codes),eligible=eligible,
|
|||
|
|
can_buy=can_buy,can_sell=can_sell,ret60=ret60,slope61=slope,volatility60=volatility,turnover20=turn20,position60=position)
|
|||
|
|
dump(ROOT/'price_coverage.json',{'source_sha256':sources,'dates':[dates[0],dates[-1]],'market_days':len(dates),'stocks':len(codes),
|
|||
|
|
'eligible_stock_days':int(eligible.sum()),'missing_listing_codes':missing_listing,'missing_historical_name_stock_days':missing_name,
|
|||
|
|
'legacy_repairs':repairs,'calendar_extension':'2026-10-26至29取全市场原始日线共同日期,后续与trade_cal交叉核验',
|
|||
|
|
'survivorship_limit':'已退市证券和名称历史覆盖未完全认证;不能解释为全体历史A股无偏样本。'})
|
|||
|
|
print('价格面板',shape,'合格股票日',int(eligible.sum()),flush=True)
|
|||
|
|
|
|||
|
|
if __name__=='__main__':main()
|