tradingSystem/research/micro_calibration_20261028/prepare.py

114 lines
5.5 KiB
Python
Raw Normal View History

"""从既有修复数据准备离线缓存;不读取服务器、不覆盖旧研究。"""
import bisect
import gzip
import hashlib
import json
import sys
from collections import defaultdict
from pathlib import Path
ROOT = Path(__file__).resolve().parent
OLD = ROOT.parent/'macro_timing_20261026'
def read(path):
return json.load(gzip.open(path) if str(path).endswith('.gz') else open(path))
def no_network(event, args):
if event in ('socket.connect', 'socket.getaddrinfo', 'socket.sendto'):
raise RuntimeError('研究过程禁止联网')
def quantile(history, q):
values = sorted(history)
at = (len(values)-1)*q
lo = int(at)
return values[lo] + (values[min(lo+1, len(values)-1)]-values[lo])*(at-lo)
def threshold_rows(signals, observations, quantiles):
days = [r['date'][:10] for r in observations]
assert days == sorted(set(days))
out = []
for row in signals:
i = bisect.bisect_left(days, row['date'])
assert days[i] == row['date'] and i >= 756
history = [x['activity'] for x in observations[i-756:i]]
assert len(history) == 756 and all(x is not None for x in history)
assert abs(observations[i]['activity']-row['activity']) < 1e-12
thresholds = {str(q): quantile(history, q/100) for q in quantiles}
assert abs(thresholds['5']-row['low_threshold']) < 1e-10
assert abs(thresholds['95']-row['high_threshold']) < 1e-10
assert abs(sum(x <= row['activity'] for x in history)/756-row['activity_percentile']) < 1e-12
out.append({**row, 'thresholds': thresholds})
return out
def main():
sys.addaudithook(no_network)
protocol = read(ROOT/'protocol.json')
assert hashlib.sha256((ROOT/'protocol.json').read_bytes()).hexdigest() == (ROOT/'protocol.sha256').read_text().split()[0]
original_manifest = read(OLD/'results/timed_micro30/manifest.json')
checked = {}
for rel, digest in original_manifest['sha256'].items():
f = OLD/rel
actual = hashlib.sha256(f.read_bytes()).hexdigest()
assert actual == digest, rel
checked[str(f.relative_to(OLD))] = actual
print('原研究来源摘要核验通过', len(checked), flush=True)
members = read(OLD/'results/timed_micro100_repaired/memberships.json.gz')
targets = {r['date']: [x['code'] for x in r['members']] for r in members}
universe = {c for v in targets.values() for c in v}
signals = threshold_rows(read(OLD/'results/timed_micro30/signals.json.gz'),
read(OLD/'results/rebalancing_observation/observations.json.gz')['groups']['small'],
sorted(set(protocol['entry_percentiles']+protocol['exit_percentiles'])))
sys.path.insert(0, str(OLD))
import repair_timed_micro100 as repair
import micro100 as m
additions, details = repair.prepare()
names = m.make_names(read(OLD/'raw/micro100/reference.json.gz')['data']['names']['rows'])
prepared = []
signal_map = {r['date']: r for r in signals}
for month in sorted({d[:7].replace('-', '') for d in targets}):
data, source = repair.ORIGINAL_MONTHLY(month)
data['bars']['rows'].extend(additions.get(month, []))
bars, limits, risk = defaultdict(dict), defaultdict(dict), defaultdict(set)
for r in data['bars']['rows']:
if r['ts_code'] in universe:
day, code = r['trade_date'], r['ts_code']
assert code not in bars[day]
bars[day][code] = {k:r.get(k) for k in ('open','close','adj_factor','vol','amount')}
if m.risky(m.historical_name(code, day, names)):
risk[day].add(code)
for r in data['limits']['rows']:
if r['ts_code'] in universe:
limits[r['trade_date']][r['ts_code']] = {k:r[k] for k in ('up_limit','down_limit')}
for r in data['st']['rows']:
if r['ts_code'] in universe:
risk[r['trade_date']].add(r['ts_code'])
for day in sorted(d for d in targets if d[:7].replace('-', '') == month):
assert len(targets[day]) == 100 and len(set(targets[day])) == 100
assert all(c in bars[day] for c in targets[day])
prepared.append({'date':day, 'members':targets[day], 'rows':bars[day],
'limits':limits[day], 'risk':sorted(risk[day]), 'signal':signal_map[day]})
print(month, len(prepared), '日', flush=True)
assert len(prepared) == 678
(ROOT/'cache').mkdir(exist_ok=True)
payload = json.dumps(prepared, ensure_ascii=False, allow_nan=False, separators=(',', ':')).encode()
path = ROOT/'cache/daily.json.gz'
path.write_bytes(gzip.compress(payload, mtime=0))
for name in ['results/timed_micro100_repaired/memberships.json.gz',
'results/timed_micro30/signals.json.gz', 'results/rebalancing_observation/observations.json.gz']:
checked[name] = hashlib.sha256((OLD/name).read_bytes()).hexdigest()
(ROOT/'coverage.json').write_text(json.dumps({'start':prepared[0]['date'], 'end':prepared[-1]['date'],
'days':len(prepared), 'candidate_universe':len(universe), 'members_checked':67800,
'source_hashes':checked, 'cache_sha256':hashlib.sha256(path.read_bytes()).hexdigest(),
'data_repair':details, 'selection_note':'只数不超过100,直接使用已核验历史100股名单前N名,保留原资格筛选与修复。',
'sources':'原始本地导出,不读取线上服务'}, ensure_ascii=False, indent=2)+'\n')
print('缓存完成', len(payload), 'bytes', flush=True)
if __name__ == '__main__':
main()