52 lines
1.7 KiB
Python
52 lines
1.7 KiB
Python
|
|
"""离线公共函数。研究口径和原始快照均以摘要固定。"""
|
|||
|
|
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'
|
|||
|
|
|
|||
|
|
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():
|
|||
|
|
assert digest(ROOT/'protocol.json')==(ROOT/'protocol.sha256').read_text().split()[0]
|
|||
|
|
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 sample_slot(code): return int(hashlib.sha256(code.encode()).hexdigest()[:8],16)%14
|
|||
|
|
|
|||
|
|
def finite_float(x): return float(x) if np.isfinite(x) else None
|