398 lines
16 KiB
Python
398 lines
16 KiB
Python
"""离线研究。先执行 market_data.py,再从任意目录执行本脚本。"""
|
||
|
||
import csv
|
||
import gzip
|
||
import hashlib
|
||
import json
|
||
import math
|
||
import sys
|
||
from collections import Counter
|
||
from pathlib import Path
|
||
|
||
BASE = Path(__file__).resolve().parent
|
||
RESEARCH = BASE.parent
|
||
INDEX_FILES = {"2000": "932000.CSI", "1000": "000852.SH", "500": "000905.SH", "300": "000300.SH"}
|
||
OTHERS = ("1000", "500", "300")
|
||
SOURCES = {}
|
||
RULES = ("A", "B", "C", "D", "M")
|
||
TARGETS = ("market", "proxy")
|
||
|
||
|
||
def offline(event, args):
|
||
if event.startswith("socket."):
|
||
raise RuntimeError("离线实验禁止联网")
|
||
|
||
|
||
def record(path):
|
||
SOURCES[str(path.relative_to(RESEARCH))] = hashlib.sha256(path.read_bytes()).hexdigest()
|
||
return path
|
||
|
||
|
||
def read_gzip(path):
|
||
with gzip.open(record(path), "rt", encoding="utf8") as f:
|
||
return json.load(f)
|
||
|
||
|
||
def write_csv(name, rows, fields=None):
|
||
with (BASE / name).open("w", encoding="utf-8-sig", newline="") as f:
|
||
writer = csv.DictWriter(f, fieldnames=fields or list(rows[0]), lineterminator="\n")
|
||
writer.writeheader()
|
||
writer.writerows(rows)
|
||
|
||
|
||
def quantile(xs, q):
|
||
xs = sorted(xs)
|
||
k = (len(xs) - 1) * q
|
||
l = int(k)
|
||
return xs[l] + (xs[min(l + 1, len(xs) - 1)] - xs[l]) * (k - l)
|
||
|
||
|
||
def five_day_loss(returns, i):
|
||
window = returns[i - 4 : i + 1]
|
||
if len(window) != 5 or any(x is None for x in window):
|
||
return None
|
||
ratio, loss = 1.0, 0.0
|
||
for r in reversed(window):
|
||
ratio *= 1 + r
|
||
loss = max(loss, 1 - ratio)
|
||
return loss
|
||
|
||
|
||
def load_daily():
|
||
archive = RESEARCH / "macro_grid_20261029/results"
|
||
book = {}
|
||
for code, filename in INDEX_FILES.items():
|
||
series = read_gzip(archive / f"features_{filename}.json.gz")["data"]
|
||
prev = None
|
||
for r in series:
|
||
date = r["timestamp"][:10]
|
||
price = None if r["price_z"] is None else r["anchor"] + r["price_z"] * r["atr"]
|
||
if date >= "2020-01-01":
|
||
item = book.setdefault(date, {"date": date})
|
||
if price is None or prev is None or not r["atr"]:
|
||
raise ValueError(f"无有效宽基收盘或ATR {date} {code}")
|
||
item["c" + code] = price
|
||
item["atr" + code] = r["atr"]
|
||
item["s" + code] = (prev - price) / r["atr"]
|
||
item["r" + code] = price / prev - 1
|
||
prev = price
|
||
market = {}
|
||
with record(BASE / "market_daily.csv").open(encoding="utf-8-sig") as f:
|
||
for r in csv.DictReader(f):
|
||
market[r["date"]] = float(r["market_return"]) if r["market_return"] else None
|
||
signals = read_gzip(RESEARCH / "micro_smoothing_20261028/results/signals.json.gz")["rows"]["baseline"]
|
||
pcts = {r["date"]: r["activity_percentile"] for r in signals}
|
||
dates = sorted(book)
|
||
assert list(pcts) == [d for d in dates if min(pcts) <= d <= max(pcts)]
|
||
rows = [book[d] for d in dates]
|
||
for row in rows:
|
||
date = row["date"]
|
||
row["pct"] = pcts.get(date)
|
||
row["low"] = int(date in pcts and pcts[date] < 0.15)
|
||
row["market_ret"] = market.get(date)
|
||
row["micro_ret"] = row["r2000"]
|
||
row["proxy_ret"] = sum(row["r" + n] for n in OTHERS) / len(OTHERS)
|
||
row["episode_id"] = None
|
||
thresholds = {}
|
||
for target in (*TARGETS, "micro"):
|
||
returns = [r[target + "_ret"] for r in rows]
|
||
losses = [five_day_loss(returns, i) for i in range(len(rows))]
|
||
train = [v for r, v in zip(rows, losses) if "2021" <= r["date"][:4] <= "2023" and v is not None]
|
||
t80, t95 = [quantile(train, q) for q in (0.8, 0.95)]
|
||
thresholds[target] = {"n": len(train), "q80": t80, "q95": t95}
|
||
prev = None
|
||
for row, loss in zip(rows, losses):
|
||
tail = int(loss >= t95) if loss is not None else None
|
||
row["dd_" + target] = loss
|
||
row["tail_" + target] = tail
|
||
row["onset_" + target] = None if tail is None or prev is None else int(tail and not prev)
|
||
prev = tail
|
||
return [r for r in rows if r["date"] in pcts], thresholds
|
||
|
||
|
||
def segments(rows):
|
||
episodes, paths, anchors = [], [], {}
|
||
i = 0
|
||
while i < len(rows):
|
||
if not rows[i]["low"]:
|
||
i += 1
|
||
continue
|
||
begin = i
|
||
while i < len(rows) and rows[i]["low"]:
|
||
i += 1
|
||
end = i - 1
|
||
num = len(episodes) + 1
|
||
d0 = next((j for j in range(begin, i) if rows[j]["s2000"] >= 1), None)
|
||
getdate = lambda j: rows[j]["date"] if j is not None and j < len(rows) else None
|
||
for r in rows[begin:i]:
|
||
r["episode_id"] = num
|
||
ep = dict(
|
||
episode_id=num,
|
||
start=getdate(begin),
|
||
end=getdate(end),
|
||
size=i - begin,
|
||
d0=getdate(d0),
|
||
d5=getdate(d0 + 5) if d0 is not None else None,
|
||
left_open=int(begin == 0),
|
||
right_open=int(i == len(rows)),
|
||
)
|
||
initial = set() if d0 is None else {c for c in OTHERS if rows[d0]["s" + c] >= 1}
|
||
ep["initial"] = "|".join(c for c in OTHERS if c in initial)
|
||
ep["shock_atr"] = None if d0 is None else rows[d0]["s2000"]
|
||
for name in (
|
||
"recovery_d1",
|
||
"recovery_d2",
|
||
"repeat_first",
|
||
"spread_first",
|
||
"spread_all",
|
||
"worst_market_5",
|
||
"worst_proxy_5",
|
||
"worst_micro_5",
|
||
"market_outcome",
|
||
"proxy_outcome",
|
||
):
|
||
ep[name] = None
|
||
episodes.append(ep)
|
||
anchors[num] = {"begin": begin, "end": end, "d0": d0, "marks": {}}
|
||
seen = set()
|
||
for j in range(begin, max(end, min(d0 + 5, len(rows) - 1) if d0 is not None else end) + 1):
|
||
r = rows[j]
|
||
k = j - d0 if d0 is not None else None
|
||
p = dict(
|
||
episode_id=num,
|
||
date=r["date"],
|
||
k=k,
|
||
low=r["low"],
|
||
recovery=None,
|
||
new_count=None,
|
||
new_today="",
|
||
repeat=None,
|
||
initial_count=None,
|
||
)
|
||
if k is not None and 0 <= k <= 5:
|
||
shock = rows[d0]["s2000"] * rows[d0]["atr2000"]
|
||
recovery = (r["c2000"] - rows[d0]["c2000"]) / shock
|
||
new = [c for c in OTHERS if c not in initial | seen and r["s" + c] >= 1]
|
||
seen.update(new)
|
||
repeat = int(k > 0 and r["s2000"] >= 1)
|
||
p.update(
|
||
recovery=recovery,
|
||
new_count=len(seen),
|
||
new_today="|".join(new),
|
||
repeat=repeat,
|
||
initial_count=len(initial),
|
||
)
|
||
anchors[num]["marks"][k] = p
|
||
if k in (1, 2):
|
||
ep["recovery_d" + str(k)] = recovery
|
||
if repeat and ep["repeat_first"] is None:
|
||
ep["repeat_first"] = r["date"]
|
||
if new and ep["spread_first"] is None:
|
||
ep["spread_first"] = r["date"]
|
||
ep["spread_all"] = "|".join(c for c in OTHERS if c in seen)
|
||
paths.append(p)
|
||
if d0 is None:
|
||
continue
|
||
for target in (*TARGETS, "micro"):
|
||
horizon = rows[d0 + 1 : d0 + 6]
|
||
returns = [r[target + "_ret"] for r in horizon]
|
||
if len(returns) == 5 and None not in returns:
|
||
total = low = 1.0
|
||
for v in returns:
|
||
total *= 1 + v
|
||
low = min(low, total)
|
||
ep["worst_" + target + "_5"] = 1 - low
|
||
for target in TARGETS:
|
||
status = [r["tail_" + target] for r in rows[d0 : d0 + 6]]
|
||
micro = [r["tail_micro"] for r in rows[d0 : d0 + 6]]
|
||
if status[0] == 1:
|
||
label = "D0已在尾部"
|
||
elif any(v == 1 for v in status[1:]):
|
||
label = "随后进入尾部"
|
||
elif len(status) < 6 or None in status:
|
||
label = "覆盖不全"
|
||
elif 1 in micro:
|
||
label = "仅微盘入尾"
|
||
else:
|
||
label = "均未入尾"
|
||
ep[target + "_outcome"] = label
|
||
return episodes, paths, anchors
|
||
|
||
|
||
def score(rows, thresholds, anchors):
|
||
alarms, tails, budgets = [], [], []
|
||
for target in TARGETS:
|
||
starts = [i for i, r in enumerate(rows) if r["onset_" + target] == 1]
|
||
for rule in RULES:
|
||
candidates = []
|
||
eligible_points = []
|
||
windows = {}
|
||
for num, seg in anchors.items():
|
||
d0 = seg["d0"]
|
||
if d0 is None:
|
||
continue
|
||
windows[num] = (d0, min(d0 + 5, len(rows) - 1))
|
||
for k, p in seg["marks"].items():
|
||
if k not in (0, 1, 2):
|
||
continue
|
||
j = d0 + k
|
||
r = rows[j]
|
||
state = [x["tail_" + target] for x in rows[d0 : j + 1]]
|
||
if k > 0 and all(v == 0 for v in state):
|
||
eligible_points.append((num, j, k, r["dd_" + target]))
|
||
poor = p["recovery"] < 0.5
|
||
spread = p["new_count"] > 0
|
||
warn = (rule == "A" and k == 0) or (
|
||
k > 0
|
||
and (
|
||
(rule == "B" and poor)
|
||
or (rule == "C" and spread)
|
||
or (rule == "D" and poor and spread)
|
||
or (
|
||
rule == "M"
|
||
and r["dd_" + target] is not None
|
||
and r["dd_" + target] >= thresholds[target]["q80"]
|
||
)
|
||
)
|
||
)
|
||
if warn and (not candidates or candidates[-1][0] != num):
|
||
candidates.append((num, j))
|
||
used = {}
|
||
eval_count = 0
|
||
for num, j in sorted(candidates, key=lambda pair: (pair[1], pair[0])):
|
||
a, b = windows[num]
|
||
state = [r["tail_" + target] for r in rows[a : j + 1]]
|
||
follow = [r["onset_" + target] for r in rows[j + 1 : b + 1]]
|
||
idx = next((u for u in range(j + 1, b + 1) if rows[u]["onset_" + target] == 1), None)
|
||
lead = None
|
||
if 1 in state:
|
||
result = "already"
|
||
elif None in state:
|
||
result = "censored"
|
||
elif idx is not None and None not in [r["onset_" + target] for r in rows[j + 1 : idx + 1]]:
|
||
result = "duplicate" if idx in used else "hit"
|
||
lead = idx - j
|
||
if result == "hit":
|
||
used[idx] = (num, j)
|
||
elif b < a + 5 or None in follow:
|
||
result = "censored"
|
||
else:
|
||
result = "false_alarm"
|
||
if result in ("hit", "duplicate", "false_alarm"):
|
||
eval_count += 1
|
||
alarms.append(
|
||
dict(
|
||
target=target,
|
||
rule=rule,
|
||
episode_id=num,
|
||
date=rows[j]["date"],
|
||
status=result,
|
||
onset=rows[idx]["date"] if lead is not None else "",
|
||
lead=lead,
|
||
)
|
||
)
|
||
for u in starts:
|
||
first = used.get(u)
|
||
reachable = [
|
||
n
|
||
for n, (a, b) in windows.items()
|
||
if a < u <= b and all(r["tail_" + target] == 0 for r in rows[a:u])
|
||
]
|
||
covering = [n for n, (a, b) in windows.items() if a <= u <= b]
|
||
if first:
|
||
reason = "提前命中"
|
||
elif reachable:
|
||
reason = "冲击后五日内未提前命中"
|
||
elif covering:
|
||
reason = "冲击当日同步或窗口内已有尾部"
|
||
elif rows[u]["low"]:
|
||
reason = "低位中但未在可预警冲击窗口"
|
||
else:
|
||
reason = "低位及冲击随访窗口外"
|
||
tails.append(
|
||
dict(
|
||
target=target,
|
||
rule=rule,
|
||
onset=rows[u]["date"],
|
||
status="hit" if first else "miss",
|
||
episode_id=first[0] if first else "",
|
||
alarm=rows[first[1]]["date"] if first else "",
|
||
lead=(u - first[1]) if first else None,
|
||
reason=reason,
|
||
reachable=int(bool(reachable)),
|
||
related_episodes="|".join(map(str, covering)),
|
||
low=rows[u]["low"],
|
||
)
|
||
)
|
||
if rule == "D":
|
||
# 与主提醒同一组D1/D2候选,按每段最严重且可完整验收的市场读数比较。
|
||
best = {}
|
||
for n, j, k, v in eligible_points:
|
||
a, b = windows[n]
|
||
if b != a + 5 or any(r["onset_" + target] is None for r in rows[j + 1 : b + 1]):
|
||
continue
|
||
if n not in best or best[n][0] < v:
|
||
best[n] = (v, j)
|
||
chosen = sorted(best.items(), key=lambda x: (-x[1][0], x[1][1]))[:eval_count]
|
||
found = set()
|
||
for n, (v, j) in chosen:
|
||
end = windows[n][1]
|
||
idx = next((u for u in range(j + 1, end + 1) if u in starts), None)
|
||
if idx is not None:
|
||
found.add(idx)
|
||
budgets.append(
|
||
dict(
|
||
target=target,
|
||
episode_id=n,
|
||
date=rows[j]["date"],
|
||
market_loss=v,
|
||
onset=rows[idx]["date"] if idx is not None else "",
|
||
lead=idx - j if idx is not None else None,
|
||
)
|
||
)
|
||
return alarms, tails, budgets
|
||
|
||
|
||
def main():
|
||
sys.addaudithook(offline)
|
||
expected = (BASE / "protocol.sha256").read_text().split()[0]
|
||
assert hashlib.sha256((BASE / "实验协议.md").read_bytes()).hexdigest() == expected
|
||
rows, thresholds = load_daily()
|
||
ep, paths, anchors = segments(rows)
|
||
alarms, tails, budgets = score(rows, thresholds, anchors)
|
||
write_csv("daily.csv", rows)
|
||
write_csv("episodes.csv", ep)
|
||
write_csv("paths.csv", paths)
|
||
write_csv("alarms.csv", alarms)
|
||
write_csv("tails.csv", tails)
|
||
write_csv("budget.csv", budgets, ["target", "episode_id", "date", "market_loss", "onset", "lead"])
|
||
summary = {
|
||
"protocol_sha256": expected,
|
||
"source_sha256": SOURCES,
|
||
"thresholds": thresholds,
|
||
"first": rows[0]["date"],
|
||
"last": rows[-1]["date"],
|
||
"days": len(rows),
|
||
"low_days": sum(r["low"] for r in rows),
|
||
"episodes": len(ep),
|
||
"with_shock": sum(e["d0"] is not None for e in ep),
|
||
"score": {},
|
||
}
|
||
for t in TARGETS:
|
||
summary["score"][t] = {}
|
||
for rule in RULES:
|
||
counts = Counter(a["status"] for a in alarms if a["target"] == t and a["rule"] == rule)
|
||
ts = [x for x in tails if x["target"] == t and x["rule"] == rule]
|
||
summary["score"][t][rule] = {
|
||
**dict(counts),
|
||
"tail_events": len(ts),
|
||
"reachable": sum(x["reachable"] for x in ts),
|
||
"leads": [a["lead"] for a in ts if a["status"] == "hit"],
|
||
}
|
||
(BASE / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n")
|
||
print(json.dumps(summary["score"], ensure_ascii=False))
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|