tradingSystem/research/chip_absolute_all_20261030/common.py

52 lines
1.8 KiB
Python
Raw Permalink Normal View History

"""离线公共函数。研究口径和原始快照均以摘要固定。"""
import gzip
import hashlib
import json
import re
import sys
from pathlib import Path
import numpy as np
ROOT=Path(__file__).resolve().parent
OLD=ROOT.parent/'macro_timing_20261026'
BASE=ROOT.parent/'chip_accumulation_20261030'
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(path).write_text(json.dumps(value,ensure_ascii=False,indent=2,allow_nan=False)+'\n')
def digest(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def protocol():
for name in ['protocol','coverage_rules','implementation_notes']:
assert digest(ROOT/(name+'.json'))==(ROOT/(name+'.sha256')).read_text().split()[0],name+'冻结摘要不符'
return read(ROOT/'protocol.json')
def offline(event,args):
if event in ('socket.connect','socket.getaddrinfo','socket.sendto','socket.sendmsg'):
raise RuntimeError('离线研究禁止联网')
def install_offline(): sys.addaudithook(offline)
def dot(s):
s=str(s)
return s[2:]+'.'+s[:2] if re.fullmatch(r'(SH|SZ|BJ)\d{6}',s) else s
def prefix(s): return s[-2:]+s[:6]
def previous_sum(x,window):
"""前window个市场交易日,不含当天;不足窗口为NaN。"""
x=np.asarray(x,dtype=float)
bad=np.isnan(x)
totals=np.concatenate([np.zeros((1,)+x.shape[1:]),np.cumsum(np.nan_to_num(x),axis=0)])
missing=np.concatenate([np.zeros((1,)+x.shape[1:]),np.cumsum(bad,axis=0)])
out=np.full(x.shape,np.nan)
out[window:]=np.where(missing[window:-1]-missing[:-window-1]==0,
totals[window:-1]-totals[:-window-1],np.nan)
return out
def finite_float(x): return float(x) if np.isfinite(x) else None