60 lines
3.2 KiB
Python
60 lines
3.2 KiB
Python
|
|
"""研究公共函数,仅处理离线缓存。"""
|
|||
|
|
import gzip,hashlib,json,sys
|
|||
|
|
from pathlib import Path
|
|||
|
|
import numpy as np
|
|||
|
|
import pandas as pd
|
|||
|
|
ROOT=Path(__file__).resolve().parent
|
|||
|
|
PREVIOUS=ROOT.parent/'heat_calibration_20261028'
|
|||
|
|
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 divide(a,b):return np.divide(a,b,out=np.full(np.broadcast_shapes(a.shape,b.shape),np.nan),where=b>0)
|
|||
|
|
def mean(a,axis=0):
|
|||
|
|
a=np.asarray(a);return divide(np.nansum(a,axis=axis),np.sum(np.isfinite(a),axis=axis))
|
|||
|
|
def previous_counts(hit,window=20):
|
|||
|
|
"""明确排除当天,前window个日历交易日不足则返回-1。"""
|
|||
|
|
c=np.vstack([np.zeros((1,hit.shape[1]),dtype=np.int32),np.cumsum(hit,axis=0,dtype=np.int32)])
|
|||
|
|
out=np.full(hit.shape,-1,dtype=np.int16)
|
|||
|
|
out[window:]=c[window:-1]-c[:-window-1]
|
|||
|
|
return out
|
|||
|
|
|
|||
|
|
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))
|
|||
|
|
z=pd.DataFrame({'close':series,'ma60':ma,'return20':r20,'stage':stage})
|
|||
|
|
assert z.loc[dates,['close','ma60','return20']].notna().all().all()
|
|||
|
|
return z.loc[dates]
|
|||
|
|
|
|||
|
|
def aggregate(ids,valid,weights,t):
|
|||
|
|
"""按当天是否达标及历史达标次数分桶,再累加为>=K。"""
|
|||
|
|
x=np.bincount(ids[valid],weights=None if weights is None else weights[valid],minlength=t*42).reshape(t,2,21)
|
|||
|
|
x=x[:,:,::-1].cumsum(2)[:,:,::-1]
|
|||
|
|
return np.concatenate([x[:,1,:1],x.sum(1),x[:,1]],axis=1)
|
|||
|
|
def configuration():
|
|||
|
|
p=read(ROOT/'protocol.json');rows=[]
|
|||
|
|
for score in p['scores']:
|
|||
|
|
for threshold in p['thresholds']:
|
|||
|
|
for mode,ks in [('current',[0]),('frequency',range(21)),('both',range(21))]:
|
|||
|
|
for k in ks:rows.append({'config':len(rows),'score':score,'threshold':threshold,'mode':mode,'k':k})
|
|||
|
|
return rows
|
|||
|
|
|
|||
|
|
def load():
|
|||
|
|
p=read(ROOT/'protocol.json');cov=read(ROOT/'coverage.json')
|
|||
|
|
assert digest(ROOT/'protocol.json')==(ROOT/'protocol.sha256').read_text().split()[0]
|
|||
|
|
assert digest(PREVIOUS/'cache/panel.npz')==cov['source_sha256']['heat_calibration_20261028/cache/panel.npz']
|
|||
|
|
panel=dict(np.load(PREVIOUS/'cache/panel.npz'));features=dict(np.load(ROOT/'cache/features.npz'))
|
|||
|
|
for field in p['scores']:panel[field]=features['today_'+field]
|
|||
|
|
return p,panel,features,cov
|
|||
|
|
|
|||
|
|
def mask_for(panel,features,config):
|
|||
|
|
field=config['score'];base=features['base_'+field];q=config['threshold'];mode=config['mode'];k=config['k']
|
|||
|
|
if mode=='current':return base&(panel[field]>=q)
|
|||
|
|
group=next(i for i,c in enumerate(features['group_keys']) if c==field+':'+str(q))
|
|||
|
|
mask=base&(features['counts'][group]>=k)
|
|||
|
|
return mask if mode=='frequency' else mask&(panel[field]>=q)
|