410 lines
22 KiB
Python
410 lines
22 KiB
Python
|
|
"""独立重算研究结果,再用逐日截断及记分反例检验实际入口。"""
|
|||
|
|
import csv
|
|||
|
|
import gzip
|
|||
|
|
import hashlib
|
|||
|
|
import json
|
|||
|
|
import math
|
|||
|
|
import sys
|
|||
|
|
from collections import Counter
|
|||
|
|
from pathlib import Path
|
|||
|
|
|
|||
|
|
import pandas as pd
|
|||
|
|
|
|||
|
|
|
|||
|
|
HERE = Path(__file__).resolve().parent
|
|||
|
|
MACRO = HERE.parent / "macro_grid_20261029"
|
|||
|
|
SMOOTH = HERE.parent / "micro_smoothing_20261028"
|
|||
|
|
START, END = "2024-01-02", "2026-10-23"
|
|||
|
|
IDS = {"300": "000300.SH", "500": "000905.SH", "1000": "000852.SH", "2000": "932000.CSI"}
|
|||
|
|
|
|||
|
|
|
|||
|
|
def read_json(path):
|
|||
|
|
opener = gzip.open if path.suffix == ".gz" else open
|
|||
|
|
with opener(path, "rt", encoding="utf-8") as stream:
|
|||
|
|
return json.load(stream)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def read_rows(filename):
|
|||
|
|
with (HERE / filename).open(encoding="utf-8-sig", newline="") as stream:
|
|||
|
|
return list(csv.DictReader(stream))
|
|||
|
|
|
|||
|
|
|
|||
|
|
def digest(path):
|
|||
|
|
checksum = hashlib.sha256()
|
|||
|
|
with path.open("rb") as stream:
|
|||
|
|
for block in iter(lambda: stream.read(1 << 20), b""):
|
|||
|
|
checksum.update(block)
|
|||
|
|
return checksum.hexdigest()
|
|||
|
|
|
|||
|
|
|
|||
|
|
def same(got, expected, where, tol=5e-9):
|
|||
|
|
if pd.isna(expected) or expected == "":
|
|||
|
|
ok = pd.isna(got) or got == ""
|
|||
|
|
else:
|
|||
|
|
ok = got != "" and not pd.isna(got) and math.isclose(
|
|||
|
|
float(got), float(expected), rel_tol=tol, abs_tol=tol)
|
|||
|
|
if not ok:
|
|||
|
|
raise ValueError(f"{where} 与独立复算不同,输出 {got!r},预期 {expected!r}")
|
|||
|
|
|
|||
|
|
|
|||
|
|
def logical(value):
|
|||
|
|
if pd.isna(value) or value == "":
|
|||
|
|
return None
|
|||
|
|
if isinstance(value, str):
|
|||
|
|
if value.lower() in {"true", "1", "1.0"}:
|
|||
|
|
return True
|
|||
|
|
if value.lower() in {"false", "0", "0.0"}:
|
|||
|
|
return False
|
|||
|
|
raise ValueError(f"未知真假值 {value!r}")
|
|||
|
|
return bool(value)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def index_data():
|
|||
|
|
verified = {}
|
|||
|
|
bars, returns = {}, {}
|
|||
|
|
hashes = read_json(MACRO / "results/delivery_manifest.json")["files_sha256"]
|
|||
|
|
for size, symbol in IDS.items():
|
|||
|
|
filename = f"results/features_{symbol}.json.gz"
|
|||
|
|
path = MACRO / filename
|
|||
|
|
assert digest(path) == hashes[filename], f"宏观归档摘要变化 {symbol}"
|
|||
|
|
frame = pd.DataFrame(read_json(path)["data"]).set_index("timestamp")
|
|||
|
|
frame.index = frame.index.str[:10]
|
|||
|
|
assert frame.index.is_monotonic_increasing and frame.index.is_unique
|
|||
|
|
close = frame.anchor + frame.atr * frame.price_z
|
|||
|
|
checked = {}
|
|||
|
|
for period in (5, 20):
|
|||
|
|
implied = close / close.shift(period) - 1
|
|||
|
|
original = frame[f"r{period}"]
|
|||
|
|
present = implied.notna() & original.notna() & (frame.index >= "2020-01-01")
|
|||
|
|
error = (implied[present] - original[present]).abs().max()
|
|||
|
|
assert present.any() and error < 5e-10, f"{symbol} {period}日归档收益不符"
|
|||
|
|
checked[f"r{period}"] = {"rows": int(present.sum()), "max_abs_diff": float(error)}
|
|||
|
|
bars[size] = pd.DataFrame({"close": close, "atr": frame.atr,
|
|||
|
|
"shock": (close.shift() - close) / frame.atr})
|
|||
|
|
returns[size] = close / close.shift() - 1
|
|||
|
|
verified[size] = checked
|
|||
|
|
return bars, returns, verified
|
|||
|
|
|
|||
|
|
|
|||
|
|
def verify_stocks():
|
|||
|
|
"""直接扫描沪深合格代码,独立复算交易日聚合。恢复期只读取本项目允许的证券。"""
|
|||
|
|
import numpy as np
|
|||
|
|
import pyarrow.compute as pc
|
|||
|
|
import pyarrow.dataset as ds
|
|||
|
|
|
|||
|
|
summary = read_json(HERE / "market_coverage.json")
|
|||
|
|
exported = pd.read_csv(HERE / "market_daily.csv", index_col="date")
|
|||
|
|
assert digest(HERE / "market_daily.csv") == summary["market_daily_sha256"]
|
|||
|
|
codes_seen, panels = set(), []
|
|||
|
|
fields = ["trade_date", "stock_code", "close", "pre_close", "volume", "amount"]
|
|||
|
|
sh = r"^SH(600|601|603|605|688)[0-9]{3}$"
|
|||
|
|
sz = r"^SZ(000|001|002|003|300|301|302)[0-9]{3}$"
|
|||
|
|
annual = {}
|
|||
|
|
for year, source in sorted(summary["annual_sources"].items()):
|
|||
|
|
path = Path(source["input"])
|
|||
|
|
if not path.exists():
|
|||
|
|
path = HERE.parents[2] / "quant_factor_service/data/parquet_cache/gp_day_data" / path.name
|
|||
|
|
assert digest(path) == source["sha256"], f"逐股输入变化 {year}"
|
|||
|
|
field = ds.field("stock_code")
|
|||
|
|
quoted = ds.dataset(path, format="parquet").to_table(
|
|||
|
|
columns=fields, filter=pc.match_substring_regex(field, sh) |
|
|||
|
|
pc.match_substring_regex(field, sz)).to_pandas()
|
|||
|
|
quoted = quoted.drop_duplicates().set_index(["stock_code", "trade_date"])
|
|||
|
|
quoted = quoted.loc[~quoted.index.duplicated(keep=False)].reset_index()
|
|||
|
|
observed = (quoted[["close", "volume", "amount"]].gt(0).all(axis=1) &
|
|||
|
|
np.isfinite(quoted[["close", "volume", "amount"]]).all(axis=1))
|
|||
|
|
trades = quoted.loc[observed].copy()
|
|||
|
|
first_date = trades.groupby("stock_code").trade_date.transform("min")
|
|||
|
|
old = trades.stock_code.isin(codes_seen) | trades.trade_date.ne(first_date)
|
|||
|
|
codes_seen.update(trades.stock_code.unique())
|
|||
|
|
keep = old & trades.pre_close.gt(0) & np.isfinite(trades.pre_close)
|
|||
|
|
trades = trades.loc[keep].copy()
|
|||
|
|
trades["r"] = trades.close.astype(float) / trades.pre_close.astype(float) - 1
|
|||
|
|
trades["sh"] = trades.stock_code.str.startswith("SH")
|
|||
|
|
panel = trades.groupby("trade_date").agg(stock_count=("r", "size"),
|
|||
|
|
stocks_SH=("sh", "sum"), independent_return=("r", "mean"))
|
|||
|
|
panel.index = pd.to_datetime(panel.index).strftime("%Y-%m-%d")
|
|||
|
|
panels.append(panel)
|
|||
|
|
annual[year] = int(len(trades))
|
|||
|
|
combined = pd.concat(panels)
|
|||
|
|
combined["stocks_SZ"] = combined.stock_count - combined.stocks_SH
|
|||
|
|
for column in ("stock_count", "stocks_SH", "stocks_SZ"):
|
|||
|
|
values = combined[column].reindex(exported.index, fill_value=0)
|
|||
|
|
assert values.eq(exported[column]).all(), f"逐日{column}不符"
|
|||
|
|
cols = ["stock_count", "stocks_SH", "stocks_SZ"]
|
|||
|
|
acceptable = (combined[cols] / combined[cols].shift(1).rolling(20).median()).ge(.90).all(axis=1)
|
|||
|
|
assert acceptable.reindex(exported.index, fill_value=False).eq(exported.coverage_valid).all()
|
|||
|
|
recalculated = combined.independent_return.where(acceptable).reindex(exported.index)
|
|||
|
|
assert recalculated.isna().eq(exported.market_return.isna()).all()
|
|||
|
|
delta = (recalculated - exported.market_return).abs().max()
|
|||
|
|
assert delta < 1e-11
|
|||
|
|
return recalculated, {"stock_days_by_year": annual, "daily_returns_compared": int(recalculated.count()),
|
|||
|
|
"max_abs_daily_difference": float(delta), "last": recalculated.last_valid_index()}
|
|||
|
|
|
|||
|
|
|
|||
|
|
def reference():
|
|||
|
|
bars, returns, index_checks = index_data()
|
|||
|
|
raw_market, market_checks = verify_stocks()
|
|||
|
|
signal_file = "results/signals.json.gz"
|
|||
|
|
assert digest(SMOOTH / signal_file) == read_json(SMOOTH / "delivery_manifest.json")["sha256"][signal_file]
|
|||
|
|
signals = pd.DataFrame(read_json(SMOOTH / signal_file)["rows"]["baseline"]).set_index("date")
|
|||
|
|
days = list(signals.index)
|
|||
|
|
assert days == list(bars["300"].loc[START:END].index) and len(set(days)) == len(days)
|
|||
|
|
pct = signals.activity_percentile
|
|||
|
|
assert pct.dropna().between(0, 1).all() and ((pct.dropna() * 756).round() - pct.dropna()*756).abs().max() < 1e-10
|
|||
|
|
series = pd.DataFrame(index=returns["300"].loc["2020-11-02":END].index)
|
|||
|
|
series["market"] = raw_market
|
|||
|
|
series["proxy"] = (returns["300"] + returns["500"] + returns["1000"]) / 3
|
|||
|
|
series["micro"] = returns["2000"]
|
|||
|
|
labels, thresholds = {}, {}
|
|||
|
|
for target in series:
|
|||
|
|
# 五个单日收益重建本日相对于每个先前收盘的五条路径,与净值/滚动峰值法独立。
|
|||
|
|
paths = pd.concat([(1 + series[target]).rolling(n).apply(math.prod, raw=True) - 1
|
|||
|
|
for n in range(1, 6)], axis=1)
|
|||
|
|
dd = -paths.min(axis=1, skipna=False).clip(upper=0)
|
|||
|
|
train = dd.loc["2021-01-01":"2023-12-31"].dropna()
|
|||
|
|
warn, extreme = train.quantile([.80, .95], interpolation="linear")
|
|||
|
|
tail = dd.ge(extreme).astype("boolean").where(dd.notna())
|
|||
|
|
onset = (tail & ~tail.shift(1)).where(tail.notna() & tail.shift(1).notna())
|
|||
|
|
labels[target] = pd.DataFrame({"dd": dd, "tail": tail, "onset": onset})
|
|||
|
|
thresholds[target] = {"calibration_first": train.index[0], "calibration_last": train.index[-1],
|
|||
|
|
"days": len(train), "p80": float(warn), "p95": float(extreme)}
|
|||
|
|
return days, pct, bars, series, labels, thresholds, index_checks, market_checks
|
|||
|
|
|
|||
|
|
|
|||
|
|
def check_daily(days, pct, bars, series, labels):
|
|||
|
|
rows = read_rows("daily.csv")
|
|||
|
|
assert [x["date"] for x in rows] == days
|
|||
|
|
for day, row in zip(days, rows):
|
|||
|
|
same(row["pct"], pct[day], day + " 成交百分位")
|
|||
|
|
assert logical(row["low"]) == bool(pct[day] < .15)
|
|||
|
|
for size in IDS:
|
|||
|
|
bar = bars[size].loc[day]
|
|||
|
|
for column, field in (("c", "close"), ("atr", "atr"), ("s", "shock")):
|
|||
|
|
same(row[column + size], bar[field], day + " " + column + size)
|
|||
|
|
for target in series:
|
|||
|
|
same(row[target + "_ret"], series.at[day, target], day + " " + target)
|
|||
|
|
same(row["dd_" + target], labels[target].at[day, "dd"], day + " 回撤 " + target)
|
|||
|
|
for field in ("tail", "onset"):
|
|||
|
|
assert logical(row[field + "_" + target]) == logical(labels[target].at[day, field]), (day, field, target)
|
|||
|
|
return rows
|
|||
|
|
|
|||
|
|
|
|||
|
|
def check_paths(days, pct, bars, series, daily):
|
|||
|
|
low = pct.lt(.15)
|
|||
|
|
groups = low.ne(low.shift()).cumsum()
|
|||
|
|
low_groups = [block for _, block in low[low].groupby(groups)]
|
|||
|
|
episodes = read_rows("episodes.csv")
|
|||
|
|
assert len(episodes) == len(low_groups)
|
|||
|
|
paths = read_rows("paths.csv")
|
|||
|
|
path_rows = {(int(row["episode_id"]), row["date"]): row for row in paths}
|
|||
|
|
assert len(path_rows) == len(paths)
|
|||
|
|
episode_days, predictions = {}, {}
|
|||
|
|
covered = set()
|
|||
|
|
group_in_daily = [""] * len(days)
|
|||
|
|
for n, (group, ep) in enumerate(zip(low_groups, episodes), 1):
|
|||
|
|
start, end = group.index[0], group.index[-1]
|
|||
|
|
lo, hi = days.index(start), days.index(end)
|
|||
|
|
assert (ep["start"], ep["end"], int(ep["episode_id"]), int(ep["size"])) == (start, end, n, len(group))
|
|||
|
|
assert logical(ep["left_open"]) == (lo == 0)
|
|||
|
|
assert logical(ep["right_open"]) == (hi == len(days) - 1)
|
|||
|
|
group_in_daily[lo:hi+1] = [str(n)] * len(group)
|
|||
|
|
shock_days = bars["2000"].loc[start:end, "shock"]
|
|||
|
|
qualifying = list(shock_days[shock_days >= 1].index)
|
|||
|
|
date0 = qualifying[0] if qualifying else ""
|
|||
|
|
assert ep["d0"] == date0
|
|||
|
|
last = hi
|
|||
|
|
if date0:
|
|||
|
|
t = days.index(date0)
|
|||
|
|
last = max(hi, min(t + 5, len(days) - 1))
|
|||
|
|
episode_days[n] = t
|
|||
|
|
assert ep["d5"] == (days[t + 5] if t + 5 < len(days) else "")
|
|||
|
|
start_close = bars["2000"].at[date0, "close"]
|
|||
|
|
fall = bars["2000"].at[days[t-1], "close"] - start_close
|
|||
|
|
starts = {s for s in ("1000", "500", "300") if bars[s].at[date0, "shock"] >= 1}
|
|||
|
|
assert set(filter(None, ep["initial"].split("|"))) == starts
|
|||
|
|
for target in series:
|
|||
|
|
future = series[target].loc[days[t+1:min(len(days), t+6)]]
|
|||
|
|
worst = None if len(future) < 5 or future.isna().any() else max(0, 1 - (1 + future).cumprod().min())
|
|||
|
|
same(ep[f"worst_{target}_5"], worst, date0 + " 五天路径 " + target)
|
|||
|
|
prior_layers = set()
|
|||
|
|
for j in range(lo, last + 1):
|
|||
|
|
day = days[j]
|
|||
|
|
covered.add((n, day))
|
|||
|
|
row = path_rows[n, day]
|
|||
|
|
assert logical(row["low"]) == low[day]
|
|||
|
|
same(row["k"], j-t if date0 else None, day + " D0时钟")
|
|||
|
|
if not date0 or j < t or j > t+5:
|
|||
|
|
assert all(row[f] == "" for f in ("recovery", "new_count", "new_today", "repeat", "initial_count"))
|
|||
|
|
continue
|
|||
|
|
layers_now = {s for s in ("1000", "500", "300") if bars[s].at[day, "shock"] >= 1} - starts
|
|||
|
|
add = layers_now - prior_layers
|
|||
|
|
prior_layers.update(layers_now)
|
|||
|
|
recovery = (bars["2000"].at[day, "close"] - start_close) / fall
|
|||
|
|
same(row["recovery"], recovery, day + " 收回比例")
|
|||
|
|
same(row["new_count"], len(prior_layers), day + " 新增规模层数")
|
|||
|
|
assert set(filter(None, row["new_today"].split("|"))) == add, day
|
|||
|
|
same(row["initial_count"], len(starts), day + " 同步规模数")
|
|||
|
|
assert logical(row["repeat"]) == (j > t and bars["2000"].at[day, "shock"] >= 1)
|
|||
|
|
if j == t:
|
|||
|
|
predictions[n, "A"] = j
|
|||
|
|
if 1 <= j-t <= 2:
|
|||
|
|
# 收盘可见的信息仅含首次冲击和截至当前的新增层,排除 D3 以后的确认。
|
|||
|
|
for rule, flag in {"B": recovery < .5, "C": bool(prior_layers),
|
|||
|
|
"D": bool(prior_layers) and recovery < .5}.items():
|
|||
|
|
if flag:
|
|||
|
|
predictions.setdefault((n, rule), j)
|
|||
|
|
assert covered == set(path_rows)
|
|||
|
|
assert group_in_daily == [row["episode_id"] for row in daily]
|
|||
|
|
return episode_days, predictions, {"low_days": int(low.sum()), "episodes": len(episodes),
|
|||
|
|
"shock_episodes": len(episode_days), "path_rows": len(paths)}
|
|||
|
|
|
|||
|
|
|
|||
|
|
def check_scoring(days, labels, thresholds, initial_days, forecasts):
|
|||
|
|
reported = read_rows("alarms.csv")
|
|||
|
|
reported_tails = read_rows("tails.csv")
|
|||
|
|
expected_alarm_keys, expected_tail_keys = set(), set()
|
|||
|
|
results = {}
|
|||
|
|
by_key = {(r["target"], r["rule"], int(r["episode_id"])): r for r in reported}
|
|||
|
|
by_event = {(r["target"], r["rule"], r["onset"]): r for r in reported_tails}
|
|||
|
|
assert len(by_key) == len(reported) and len(by_event) == len(reported_tails)
|
|||
|
|
for target in ("market", "proxy"):
|
|||
|
|
data = labels[target].loc[days]
|
|||
|
|
active = [logical(x) for x in data["tail"]]
|
|||
|
|
onset = [logical(x) for x in data["onset"]]
|
|||
|
|
events = [i for i, flag in enumerate(onset) if flag]
|
|||
|
|
predictions = dict(forecasts)
|
|||
|
|
for n, t in initial_days.items():
|
|||
|
|
for j in range(t+1, min(t+3, len(days))):
|
|||
|
|
if data.dd.iloc[j] >= thresholds[target]["p80"]:
|
|||
|
|
predictions[n, "M"] = j
|
|||
|
|
break
|
|||
|
|
results[target] = {"tail_dates": [days[e] for e in events],
|
|||
|
|
"held_out_period_tail_events": sum(days[e] >= "2025-01-01" for e in events), "rules": {}}
|
|||
|
|
for rule in ("A", "B", "C", "D", "M"):
|
|||
|
|
pending, counts = [], Counter()
|
|||
|
|
for (n, r), mark in predictions.items():
|
|||
|
|
if r != rule:
|
|||
|
|
continue
|
|||
|
|
t = initial_days[n]
|
|||
|
|
key = target, rule, n
|
|||
|
|
expected_alarm_keys.add(key)
|
|||
|
|
out = by_key[key]
|
|||
|
|
assert out["date"] == days[mark]
|
|||
|
|
statuses = active[t:mark+1]
|
|||
|
|
future = next((x for x in events if mark < x <= t+5), None)
|
|||
|
|
if True in statuses:
|
|||
|
|
classification = "already"
|
|||
|
|
elif None in statuses:
|
|||
|
|
classification = "censored"
|
|||
|
|
elif future is not None and None not in onset[mark+1:future+1]:
|
|||
|
|
classification = "match"
|
|||
|
|
elif t + 5 >= len(days) or None in onset[mark+1:t+6]:
|
|||
|
|
classification = "censored"
|
|||
|
|
else:
|
|||
|
|
classification = "false_alarm"
|
|||
|
|
if classification == "match":
|
|||
|
|
pending.append((future, mark, n))
|
|||
|
|
else:
|
|||
|
|
assert out["status"] == classification and not out["onset"] and not out["lead"], key
|
|||
|
|
counts[classification] += 1
|
|||
|
|
winners = {}
|
|||
|
|
for event, mark, n in sorted(pending):
|
|||
|
|
status = "duplicate" if event in winners else "hit"
|
|||
|
|
winners.setdefault(event, (n, mark))
|
|||
|
|
entry = by_key[target, rule, n]
|
|||
|
|
assert entry["status"] == status and entry["onset"] == days[event] and int(entry["lead"]) == event-mark
|
|||
|
|
counts[status] += 1
|
|||
|
|
reach = 0
|
|||
|
|
for e in events:
|
|||
|
|
key = target, rule, days[e]
|
|||
|
|
expected_tail_keys.add(key)
|
|||
|
|
out = by_event[key]
|
|||
|
|
can_reach = any(t < e <= t + 5 and all(v is False for v in active[t:e]) for t in initial_days.values())
|
|||
|
|
assert logical(out["reachable"]) == can_reach
|
|||
|
|
reach += can_reach
|
|||
|
|
if e in winners:
|
|||
|
|
n, mark = winners[e]
|
|||
|
|
assert out["status"] == "hit" and int(out["episode_id"]) == n
|
|||
|
|
assert out["alarm"] == days[mark] and int(out["lead"]) == e-mark > 0
|
|||
|
|
else:
|
|||
|
|
assert out["status"] == "miss" and not out["alarm"] and not out["lead"]
|
|||
|
|
results[target]["rules"][rule] = {**dict(counts), "reachable_episodes": reach,
|
|||
|
|
"all_missed": len(events)-len(winners), "leads": [e-m for e, (_,m) in sorted(winners.items())]}
|
|||
|
|
assert expected_alarm_keys == set(by_key) and expected_tail_keys == set(by_event)
|
|||
|
|
return results
|
|||
|
|
|
|||
|
|
|
|||
|
|
def replay_as_of(days):
|
|||
|
|
# 这一节才调用被审计脚本。逐日截断后,观察今天收盘到底能否发出相同提醒。
|
|||
|
|
import explore
|
|||
|
|
|
|||
|
|
full, cutoffs = explore.load_daily()
|
|||
|
|
output = {(r["target"], r["rule"], r["episode_id"], r["date"]) for r in read_rows("alarms.csv")}
|
|||
|
|
assert [r["date"] for r in full] == days
|
|||
|
|
checked = 0
|
|||
|
|
for i, day in enumerate(days):
|
|||
|
|
through_today = [dict(r) for r in full[:i+1]]
|
|||
|
|
_, _, anchors = explore.segments(through_today)
|
|||
|
|
alarms, _, _ = explore.score(through_today, cutoffs, anchors)
|
|||
|
|
emitted = {(r["target"], r["rule"], str(r["episode_id"]), r["date"]) for r in alarms}
|
|||
|
|
assert emitted == {r for r in output if r[3] <= day}, f"截断到 {day} 后,历史提醒改变"
|
|||
|
|
checked += len(emitted)
|
|||
|
|
|
|||
|
|
# 真实样本没有两段认领同一尾部;构造两个重叠窗口和一个右侧不完整窗口检查实际记分。
|
|||
|
|
synthetic = []
|
|||
|
|
for i in range(8):
|
|||
|
|
synthetic.append({"date": f"t{i}", "low": 1, "dd_market": 0, "dd_proxy": 0,
|
|||
|
|
"tail_market": int(i == 4), "onset_market": int(i == 4),
|
|||
|
|
"tail_proxy": int(i == 0), "onset_proxy": int(i == 0)})
|
|||
|
|
anchors = {n: {"d0": t, "marks": {k: {"recovery": 1, "new_count": 0}
|
|||
|
|
for k in range(3)}} for n, t in ((1, 0), (2, 2), (3, 5))}
|
|||
|
|
fake, ledger, _ = explore.score(synthetic, cutoffs, anchors)
|
|||
|
|
actual = {(r["target"], r["episode_id"]): r["status"] for r in fake if r["rule"] == "A"}
|
|||
|
|
assert actual == {("market", 1): "hit", ("market", 2): "duplicate", ("market", 3): "censored",
|
|||
|
|
("proxy", 1): "already", ("proxy", 2): "false_alarm", ("proxy", 3): "censored"}
|
|||
|
|
market_event = [r for r in ledger if r["target"] == "market" and r["rule"] == "A"]
|
|||
|
|
assert len(market_event) == 1 and market_event[0]["episode_id"] == 1 and market_event[0]["lead"] == 4
|
|||
|
|
return {"day_end_prefixes": len(days), "cumulative_alert_rows_compared": checked,
|
|||
|
|
"synthetic_overlapping_and_incomplete_window_outcomes": len(actual)}
|
|||
|
|
|
|||
|
|
|
|||
|
|
def main():
|
|||
|
|
summary = read_json(HERE / "summary.json")
|
|||
|
|
frozen = digest(HERE / "实验协议.md")
|
|||
|
|
assert frozen == (HERE / "protocol.sha256").read_text().split()[0] == summary["protocol_sha256"]
|
|||
|
|
days, pct, bars, series, labels, thresholds, index_checks, market_checks = reference()
|
|||
|
|
for target, values in thresholds.items():
|
|||
|
|
for independently, stored in (("p80", "q80"), ("p95", "q95"), ("days", "n")):
|
|||
|
|
same(summary["thresholds"][target][stored], values[independently], target + " 训练")
|
|||
|
|
daily = check_daily(days, pct, bars, series, labels)
|
|||
|
|
starts, forecasts, path_checks = check_paths(days, pct, bars, series, daily)
|
|||
|
|
scores = check_scoring(days, labels, thresholds, starts, forecasts)
|
|||
|
|
for target, obj in scores.items():
|
|||
|
|
for rule, result in obj["rules"].items():
|
|||
|
|
totals = summary["score"][target][rule]
|
|||
|
|
assert totals["tail_events"] == len(obj["tail_dates"])
|
|||
|
|
assert totals["reachable"] == result["reachable_episodes"] and totals["leads"] == result["leads"]
|
|||
|
|
for key in ("hit", "false_alarm", "already", "censored", "duplicate"):
|
|||
|
|
assert totals.get(key, 0) == result.get(key, 0)
|
|||
|
|
if not any(rule == "D" for _, rule in forecasts):
|
|||
|
|
assert not read_rows("budget.csv"), "没有主规则提醒时,同预算也应为零"
|
|||
|
|
replay = replay_as_of(days)
|
|||
|
|
audit = {"status": "通过", "protocol_sha256": frozen, "signal_first": days[0], "signal_last": days[-1],
|
|||
|
|
"signal_days": len(days), "signal_source": "旧未平滑基线,核对交付SHA及756个历史分位的离散刻度",
|
|||
|
|
"indices": index_checks, "stocks": market_checks, "thresholds": thresholds, "paths": path_checks,
|
|||
|
|
"scoring": scores, "prefix_and_overlap_checks": replay, "limits": [
|
|||
|
|
"本机缺少旧研究的原始指数日线和完整历史成交额,本轮不能从逐日原始成交额重造百分位、从OHLC重造ATR。收盘重建另用归档5日和20日收益对拍。",
|
|||
|
|
"全体为沪深可见且具备有效收益的交易股票,包含微盘。指数对照不含中证2000,双方不可互代。",
|
|||
|
|
"实际样本中未发生的分支不冒充自然数据验收。2025起是按时间留后的复核,之前的独立研究已使用同一时期。"]}
|
|||
|
|
(HERE / "audit.json").write_text(json.dumps(audit, ensure_ascii=False, indent=2, allow_nan=False) + "\n")
|
|||
|
|
print(json.dumps({"status": audit["status"], "signal_days": len(days), **path_checks}, ensure_ascii=False))
|
|||
|
|
|
|||
|
|
|
|||
|
|
if __name__ == "__main__":
|
|||
|
|
def deny_network(event, _args):
|
|||
|
|
if event in {"socket.connect", "socket.getaddrinfo", "socket.sendto", "socket.sendmsg"}:
|
|||
|
|
raise RuntimeError("离线审计禁止联网")
|
|||
|
|
sys.addaudithook(deny_network)
|
|||
|
|
main()
|