tradingSystem/research/liquidity_tail_20261120/diagnostics.py

199 lines
7.9 KiB
Python
Raw Normal View History

"""已冻结研究的描述性对照。相同低位天数的风险集只用于可比性复核。"""
import csv
from pathlib import Path
from statistics import stdev
from explore import RULES, TARGETS, write_csv
BASE = Path(__file__).resolve().parent
def read(name):
with (BASE / name).open(encoding="utf-8-sig") as f:
return list(csv.DictReader(f))
def future_event(rows, i, target):
flags = [r["onset_" + target] for r in rows[i + 1 : i + 6]]
return None if len(flags) != 5 or "" in flags else int("1" in flags)
def issue_ledger(alarms, tails):
names = {"A": "首震", "B": "收回不足一半", "C": "新增扩散", "D": "恢复弱且扩散", "M": "市场自身"}
sources = {"market": "沪深有价股票等权组合", "proxy": "中证1000、中证500、沪深300等权组合"}
lines = [
"# 每次提醒、误报和漏报",
"",
"每个尾部只记首次进入日,连续在阈值外只算一次。提前量按交易日。"
"先列全部提醒的核对结果,再列完整日历的每一个尾部首日。主规则同时要求恢复弱、规模扩散。",
"",
]
outcomes = {
"hit": "命中",
"false_alarm": "误报",
"already": "收盘前已出险",
"duplicate": "重复提醒",
"censored": "数据不足",
}
for target, label in sources.items():
lines += [
f"## {label}",
"",
"### 发出过的提醒",
"",
"| 提醒交易日 | 低位段 | 观察条件 | 核对结果 | 随后尾部首日 | 提前交易日 |",
"|---|---:|---|---|---|---:|",
]
ordered = sorted((a for a in alarms if a["target"] == target), key=lambda a: (a["date"], a["rule"]))
for a in ordered:
lines.append(
f"| {a['date']} | {a['episode_id']} | {names[a['rule']]} | {outcomes[a['status']]} | {a['onset'] or '—'} | {a['lead'] or '—'} |"
)
lines += [
"",
"新增扩散条件和组合主规则都未发出提醒。",
"",
"### 逐次尾部与首震、主规则对照",
"",
"| 尾部首日 | 当天仍在低位 | 首震提醒 | 恢复弱且扩散 | 原因 |",
"|---|---|---|---|---|",
]
at = {(r["onset"], r["rule"]): r for r in tails if r["target"] == target}
for day in sorted({d for d, _ in at}):
a, main = at[day, "A"], at[day, "D"]
first = f"{a['alarm']},提前{a['lead']}天" if a["status"] == "hit" else "漏报"
main_result = "漏报" if main["status"] == "miss" else "命中"
low = "是" if main["low"] == "1" else "否"
lines.append(f"| {day} | {low} | {first} | {main_result} | {main['reason']} |")
lines.append("")
(BASE / "误报与漏报.md").write_text("\n".join(lines).rstrip() + "\n", encoding="utf8")
def main():
rows, episodes, alarms, tails = map(read, ("daily.csv", "episodes.csv", "alarms.csv", "tails.csv"))
issue_ledger(alarms, tails)
index = {r["date"]: i for i, r in enumerate(rows)}
stats, timing, controls = [], [], []
for target in TARGETS:
for year in ("2024", "2025", "2026", "全部"):
period = [r for r in rows if year == "全部" or r["date"][:4] == year]
for rule in RULES:
al = [
a
for a in alarms
if a["target"] == target
and a["rule"] == rule
and (year == "全部" or a["date"][:4] == year)
]
ts = [
t
for t in tails
if t["target"] == target
and t["rule"] == rule
and (year == "全部" or t["onset"][:4] == year)
]
stats.append(
dict(
target=target,
period=year,
rule=rule,
observed_days=sum(r["onset_" + target] != "" for r in period),
low_observed_days=sum(
r["low"] == "1" and r["onset_" + target] != "" for r in period
),
hit=sum(a["status"] == "hit" for a in al),
false_alarm=sum(a["status"] == "false_alarm" for a in al),
already=sum(a["status"] == "already" for a in al),
unknown=sum(a["status"] == "censored" for a in al),
misses=sum(t["status"] == "miss" for t in ts),
total_onsets=len(ts),
reachable=sum(t["reachable"] == "1" for t in ts),
)
)
for ep in episodes:
if not ep["d0"]:
continue
i = index[ep["d0"]]
start = index[ep["start"]]
age = i - start
a = rows[i]
# 同在低位第k天,别段截至该时点尚无微盘冲击;不要求以后也没有冲击。
for other in episodes:
if other == ep:
continue
j = index[other["start"]] + age
if j > index[other["end"]] or other["d0"] and index[other["d0"]] <= j:
continue
if abs(i - j) <= 5 or rows[j]["tail_" + target] != "0" or a["tail_" + target] != "0":
continue
if future_event(rows, j, target) is None or future_event(rows, i, target) is None:
continue
vals = [
[float(r[target + "_ret"]) for r in rows[max(0, t - 20) : t] if r[target + "_ret"]]
for t in (i, j)
]
if min(map(len, vals)) < 20:
continue
controls.append(
dict(
target=target,
trigger=ep["d0"],
control=rows[j]["date"],
low_day=age + 1,
trigger_pct=a["pct"],
control_pct=rows[j]["pct"],
trigger_shock=a["s2000"],
control_shock=rows[j]["s2000"],
trigger_market_loss=a["dd_" + target],
control_market_loss=rows[j]["dd_" + target],
trigger_prev20_vol=stdev(vals[0]),
control_prev20_vol=stdev(vals[1]),
trigger_future_tail=future_event(rows, i, target),
control_future_tail=future_event(rows, j, target),
)
)
for k in range(3):
j = i + k
if j >= len(rows):
continue
r = rows[j]
timing.append(
dict(
target=target,
episode_id=ep["episode_id"],
date=r["date"],
k=k,
shock_atr=r["s2000"],
market_loss=r["dd_" + target],
market_return=r[target + "_ret"],
new_tail_today=r["onset_" + target],
)
)
write_csv("yearly.csv", stats)
write_csv("landmarks.csv", timing)
write_csv(
"low_age_controls.csv",
controls,
[
"target",
"trigger",
"control",
"low_day",
"trigger_pct",
"control_pct",
"trigger_shock",
"control_shock",
"trigger_market_loss",
"control_market_loss",
"trigger_prev20_vol",
"control_prev20_vol",
"trigger_future_tail",
"control_future_tail",
],
)
if __name__ == "__main__":
main()