558 lines
30 KiB
Python
558 lines
30 KiB
Python
|
|
#!/usr/bin/env python3
|
|||
|
|
"""从固定实验表生成离线中文图册。"""
|
|||
|
|
|
|||
|
|
from base64 import b64encode
|
|||
|
|
from html import escape
|
|||
|
|
import json
|
|||
|
|
from pathlib import Path
|
|||
|
|
|
|||
|
|
import matplotlib
|
|||
|
|
|
|||
|
|
matplotlib.use("Agg")
|
|||
|
|
import matplotlib.pyplot as plt
|
|||
|
|
import numpy as np
|
|||
|
|
import pandas as pd
|
|||
|
|
from matplotlib import font_manager
|
|||
|
|
from matplotlib.ticker import MaxNLocator
|
|||
|
|
|
|||
|
|
|
|||
|
|
ROOT = Path(__file__).resolve().parent
|
|||
|
|
FIGURES = ROOT / "figures"
|
|||
|
|
ALBUM = ROOT / "逐段图册.html"
|
|||
|
|
INK = "#172e40"
|
|||
|
|
MUTED = "#496274"
|
|||
|
|
BLUE = "#23657d"
|
|||
|
|
ORANGE = "#b45324"
|
|||
|
|
TEAL = "#27785a"
|
|||
|
|
PLUM = "#83577d"
|
|||
|
|
GOLD = "#a37c1e"
|
|||
|
|
SHADE = "#f4e9cc"
|
|||
|
|
|
|||
|
|
|
|||
|
|
def setup_plotting():
|
|||
|
|
for path in [
|
|||
|
|
"/System/Library/Fonts/Hiragino Sans GB.ttc",
|
|||
|
|
"/System/Library/Fonts/STHeiti Light.ttc",
|
|||
|
|
"/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
|
|||
|
|
"C:/Windows/Fonts/msyh.ttc",
|
|||
|
|
]:
|
|||
|
|
if Path(path).is_file():
|
|||
|
|
font_manager.fontManager.addfont(path)
|
|||
|
|
family = font_manager.FontProperties(fname=path).get_name()
|
|||
|
|
break
|
|||
|
|
else:
|
|||
|
|
raise RuntimeError("绘图需要可显示中文的黑体、微软雅黑或思源黑体。")
|
|||
|
|
plt.rcParams.update({
|
|||
|
|
"font.family": family,
|
|||
|
|
"font.size": 10,
|
|||
|
|
"axes.unicode_minus": False,
|
|||
|
|
"axes.labelcolor": INK,
|
|||
|
|
"axes.edgecolor": "#b9c7cf",
|
|||
|
|
"axes.spines.right": False,
|
|||
|
|
"axes.spines.top": False,
|
|||
|
|
"xtick.color": MUTED,
|
|||
|
|
"ytick.color": MUTED,
|
|||
|
|
"text.color": INK,
|
|||
|
|
"svg.fonttype": "none",
|
|||
|
|
"svg.hashsalt": "liquidity-tail-20261120",
|
|||
|
|
"figure.facecolor": "#ffffff",
|
|||
|
|
})
|
|||
|
|
FIGURES.mkdir(exist_ok=True)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def chart_axes(axes, count=4):
|
|||
|
|
for ax in np.ravel(axes):
|
|||
|
|
ax.set_axisbelow(True)
|
|||
|
|
ax.grid(axis="y", color="#dbe4e9", linewidth=0.7)
|
|||
|
|
ax.yaxis.set_major_locator(MaxNLocator(nbins=count))
|
|||
|
|
ax.tick_params(length=3, width=0.6)
|
|||
|
|
ax.margins(x=0, y=0.12)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def chart_legend(ax, cols=3):
|
|||
|
|
handles, labels = ax.get_legend_handles_labels()
|
|||
|
|
if handles:
|
|||
|
|
ax.legend(handles, labels, loc="lower left", bbox_to_anchor=(0, 1.01),
|
|||
|
|
ncol=cols, frameon=False, handlelength=2, borderaxespad=0,
|
|||
|
|
fontsize=9, columnspacing=1.3)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def date_axis(ax, dates, count=8, year=False):
|
|||
|
|
positions = np.unique(np.rint(np.linspace(0, len(dates) - 1, min(count, len(dates)))).astype(int))
|
|||
|
|
fmt = "%Y-%m" if year else "%m-%d"
|
|||
|
|
ax.set_xticks(positions, [dates[position].strftime(fmt) for position in positions])
|
|||
|
|
if len(positions) > 1:
|
|||
|
|
ax.get_xticklabels()[0].set_ha("left")
|
|||
|
|
ax.get_xticklabels()[-1].set_ha("right")
|
|||
|
|
|
|||
|
|
|
|||
|
|
def save_svg(fig, path):
|
|||
|
|
fig.savefig(path, format="svg", metadata={"Date": None})
|
|||
|
|
drawing = path.read_text(encoding="utf8")
|
|||
|
|
path.write_text("\n".join(line.rstrip() for line in drawing.splitlines()) + "\n", encoding="utf8")
|
|||
|
|
plt.close(fig)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def picture(path, caption):
|
|||
|
|
img = b64encode(path.read_bytes()).decode("ascii")
|
|||
|
|
return (f'<img loading="lazy" alt="{escape(caption, quote=True)}" '
|
|||
|
|
f'src="data:image/svg+xml;base64,{img}">')
|
|||
|
|
|
|||
|
|
|
|||
|
|
def html_table(headers, rows):
|
|||
|
|
head = "".join(f'<th scope="col">{escape(str(item))}</th>' for item in headers)
|
|||
|
|
body = "".join(
|
|||
|
|
"<tr>" + "".join(f"<td>{escape(str(item))}</td>" for item in row) + "</tr>"
|
|||
|
|
for row in rows
|
|||
|
|
)
|
|||
|
|
return f'<div class="table-wrap"><table><thead><tr>{head}</tr></thead><tbody>{body}</tbody></table></div>'
|
|||
|
|
|
|||
|
|
|
|||
|
|
STYLE = """
|
|||
|
|
:root{font:16px/1.6 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;color:#172e40;background:#f4f6f7}
|
|||
|
|
*{box-sizing:border-box}body{margin:0}main{max-width:1180px;margin:auto;background:white;padding:34px clamp(14px,4vw,50px) 50px}
|
|||
|
|
h1,h2,h3{line-height:1.4;font-weight:650;margin:0 0 .55em}h1{font-size:clamp(24px,3vw,36px)}h2{font-size:23px}
|
|||
|
|
p{margin:.45em 0 .7em}.context{color:#496274}figure{margin:12px 0 20px}figure img{max-width:100%;height:auto;display:block;margin:auto}
|
|||
|
|
.nav{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin:12px 0 22px;padding:12px 0;border-block:1px solid #dbe4e9}
|
|||
|
|
select,button{font:inherit;padding:5px 9px;color:#172e40;border:1px solid #a8bac4;border-radius:4px;background:white}
|
|||
|
|
button[disabled]{opacity:.4}.js .episode:not(.shown){display:none}.episode{margin-bottom:28px}.table-wrap{overflow-x:auto}
|
|||
|
|
table{border-collapse:collapse;font-size:14px;font-variant-numeric:tabular-nums;width:100%;margin:.5em 0}td,th{white-space:nowrap;padding:6px 8px;text-align:right;border-bottom:1px solid #dce6ea}
|
|||
|
|
td:first-child,th:first-child{text-align:left}th{background:#f0f4f5}summary{cursor:pointer}section{scroll-margin-top:12px}small{color:#496274}
|
|||
|
|
@media(max-width:600px){main{padding:16px 10px}.nav{gap:5px}.chart-scroll{overflow-x:auto}.chart-scroll img{min-width:745px}}
|
|||
|
|
@media print{.nav{display:none}.js .episode:not(.shown){display:block}.episode{break-before:page}main{padding:0}figure{break-inside:avoid}}
|
|||
|
|
"""
|
|||
|
|
|
|||
|
|
NAVIGATION = """
|
|||
|
|
(() => {
|
|||
|
|
const episodes = Array.from(document.querySelectorAll('.episode'));
|
|||
|
|
if (!episodes.length) return;
|
|||
|
|
const selector = document.getElementById('chooser');
|
|||
|
|
const previous = document.getElementById('previous');
|
|||
|
|
const next = document.getElementById('next');
|
|||
|
|
document.documentElement.classList.add('js');
|
|||
|
|
function show(index) {
|
|||
|
|
episodes.forEach((item, i) => item.classList.toggle('shown', i === index));
|
|||
|
|
selector.selectedIndex = index;
|
|||
|
|
previous.disabled = index === 0;
|
|||
|
|
next.disabled = index === episodes.length - 1;
|
|||
|
|
}
|
|||
|
|
function fromHash() {
|
|||
|
|
const index = episodes.findIndex(item => '#' + item.id === location.hash);
|
|||
|
|
show(Math.max(0, index));
|
|||
|
|
}
|
|||
|
|
function select(index) {
|
|||
|
|
show(index);
|
|||
|
|
history.replaceState(null, '', '#' + episodes[index].id);
|
|||
|
|
}
|
|||
|
|
selector.addEventListener('change', () => select(selector.selectedIndex));
|
|||
|
|
previous.addEventListener('click', () => select(selector.selectedIndex - 1));
|
|||
|
|
next.addEventListener('click', () => select(selector.selectedIndex + 1));
|
|||
|
|
window.addEventListener('hashchange', fromHash);
|
|||
|
|
fromHash();
|
|||
|
|
})();
|
|||
|
|
"""
|
|||
|
|
|
|||
|
|
INDICES = {
|
|||
|
|
"2000": ("中证2000", ORANGE), "1000": ("中证1000", PLUM),
|
|||
|
|
"500": ("中证500", BLUE), "300": ("沪深300", TEAL),
|
|||
|
|
}
|
|||
|
|
TARGETS = {"market": ("沪深个股等权", BLUE), "proxy": ("三指数等权", TEAL),
|
|||
|
|
"micro": ("中证2000自身", ORANGE)}
|
|||
|
|
RULES = {"A": "A 初次冲击", "B": "B 收回不足", "C": "C 新增规模层",
|
|||
|
|
"D": "D 收回不足且扩散", "M": "M 市场自身跌幅"}
|
|||
|
|
STATUS = {"hit": "提前命中", "false_alarm": "误报", "duplicate": "重复提醒",
|
|||
|
|
"already": "尾部已发生", "censored": "观察不完整"}
|
|||
|
|
|
|||
|
|
|
|||
|
|
def date_label(value):
|
|||
|
|
return "—" if pd.isna(value) else pd.Timestamp(value).strftime("%Y-%m-%d")
|
|||
|
|
|
|||
|
|
|
|||
|
|
def percentage(value, digits=1):
|
|||
|
|
return "缺数据" if pd.isna(value) else f"{value * 100:.{digits}f}%"
|
|||
|
|
|
|||
|
|
|
|||
|
|
def name_levels(value):
|
|||
|
|
if pd.isna(value) or str(value).strip() == "":
|
|||
|
|
return "—"
|
|||
|
|
return "、".join(INDICES.get(item, (item,))[0] for item in str(value).split("|"))
|
|||
|
|
|
|||
|
|
|
|||
|
|
def episode_marks(axes, frame, start, end, d0, d5):
|
|||
|
|
dates = pd.Index(frame.date)
|
|||
|
|
first, last = dates.get_loc(start), dates.get_loc(end)
|
|||
|
|
for ax in axes:
|
|||
|
|
ax.axvspan(first - 0.43, last + 0.43, color=SHADE, alpha=.62, lw=0, zorder=0)
|
|||
|
|
for day, color in [(d0, ORANGE), (d5, MUTED)]:
|
|||
|
|
if pd.notna(day) and day in dates:
|
|||
|
|
ax.axvline(dates.get_loc(day), color=color, ls="--", lw=1, alpha=.9, zorder=2)
|
|||
|
|
ax.set_xlim(-0.55, len(dates) - .45)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def drawdown_chart(ax, frame):
|
|||
|
|
x = np.arange(len(frame))
|
|||
|
|
for key in ("micro", "proxy", "market"):
|
|||
|
|
name, color = TARGETS[key]
|
|||
|
|
drawdown = frame[f"dd_{key}"] * 100
|
|||
|
|
ax.plot(x, drawdown, color=color, lw=1.6, label=name,
|
|||
|
|
marker="." if len(frame) < 3 else None)
|
|||
|
|
starts = frame[f"onset_{key}"].eq(1) & drawdown.notna()
|
|||
|
|
ax.scatter(x[starts], drawdown[starts], marker="o", s=30, facecolor="white",
|
|||
|
|
edgecolor=color, linewidth=1.4, zorder=4)
|
|||
|
|
ax.set_ylabel("五日跌幅(%)")
|
|||
|
|
ax.set_ylim(bottom=0)
|
|||
|
|
chart_legend(ax)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def pressure_strip(ax, frame, x):
|
|||
|
|
for index, (code, (_, color)) in enumerate(INDICES.items()):
|
|||
|
|
values = frame["s" + code].to_numpy(dtype=float)
|
|||
|
|
valid = np.isfinite(values)
|
|||
|
|
active = valid & (values >= 1)
|
|||
|
|
ax.scatter(x[valid], np.full(valid.sum(), index), s=16, c="#bdc9ce", marker="o", zorder=2)
|
|||
|
|
ax.scatter(x[active], np.full(active.sum(), index), s=44, c=color, marker="D", zorder=3)
|
|||
|
|
ax.set_yticks(range(4), [item[0] for item in INDICES.values()])
|
|||
|
|
ax.set_ylim(3.55, -.55)
|
|||
|
|
ax.set_title("菱形为当日向下冲击达到 1 ATR,灰点为未达到", loc="left",
|
|||
|
|
fontsize=10, pad=6, color=MUTED)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def episode_chart(episode, frame):
|
|||
|
|
x = np.arange(len(frame))
|
|||
|
|
fig, axes = plt.subplots(4, 1, figsize=(11.8, 8.65), sharex=True,
|
|||
|
|
gridspec_kw={"height_ratios": [1.45, .75, .8, 1.4]})
|
|||
|
|
fig.subplots_adjust(left=.10, right=.98, top=.945, bottom=.075, hspace=.70)
|
|||
|
|
chart_axes(axes)
|
|||
|
|
episode_marks(axes, frame, episode.start, episode.end, episode.d0, episode.d5)
|
|||
|
|
for code, (label, color) in INDICES.items():
|
|||
|
|
close = frame["c" + code]
|
|||
|
|
axes[0].plot(x, close / close.iloc[0] * 100, color=color,
|
|||
|
|
lw=2.1 if code == "2000" else 1.4, label=label,
|
|||
|
|
marker="." if len(frame) < 3 else None)
|
|||
|
|
axes[0].set_ylabel("首日收盘 = 100")
|
|||
|
|
chart_legend(axes[0], 4)
|
|||
|
|
axes[1].axhline(15, color=GOLD, ls=":", lw=1.6, label="低位门槛(15)")
|
|||
|
|
axes[1].plot(x, frame.pct * 100, color=INK, lw=1.5, marker=".", markersize=4,
|
|||
|
|
label="中证2000成交活跃度")
|
|||
|
|
axes[1].set_ylabel("历史百分位(%)")
|
|||
|
|
axes[1].set_ylim(0, max(22, frame.pct.max() * 110))
|
|||
|
|
chart_legend(axes[1])
|
|||
|
|
pressure_strip(axes[2], frame, x)
|
|||
|
|
drawdown_chart(axes[3], frame)
|
|||
|
|
date_axis(axes[-1], frame.date.to_list())
|
|||
|
|
axes[-1].set_xlabel("交易日期(每格位置按交易日等距)")
|
|||
|
|
name = f"低位段-{int(episode.episode_id):03d}.svg"
|
|||
|
|
path = FIGURES / name
|
|||
|
|
save_svg(fig, path)
|
|||
|
|
return path
|
|||
|
|
|
|||
|
|
|
|||
|
|
def rule_counts(alarms, tails):
|
|||
|
|
rows = []
|
|||
|
|
for target in ("market", "proxy"):
|
|||
|
|
for rule in ("A", "B", "C", "D", "M"):
|
|||
|
|
warn = alarms[(alarms.target == target) & (alarms.rule == rule)]
|
|||
|
|
results = tails[(tails.target == target) & (tails.rule == rule)]
|
|||
|
|
observed = warn.status.value_counts()
|
|||
|
|
rows.append([
|
|||
|
|
TARGETS[target][0], RULES[rule], len(warn),
|
|||
|
|
*[observed.get(key, 0) for key in STATUS],
|
|||
|
|
results.status.eq("miss").sum(),
|
|||
|
|
])
|
|||
|
|
return html_table(["目标", "规则", "提醒", *STATUS.values(), "日历内漏报"], rows)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def recovery_comparison(episodes, paths, alarms, breadth, tail_threshold):
|
|||
|
|
warnings = alarms[(alarms.target == "market") & (alarms.rule == "B")
|
|||
|
|
& alarms.status.isin(["hit", "false_alarm"])].sort_values("date")
|
|||
|
|
if warnings.empty:
|
|||
|
|
return ""
|
|||
|
|
fig, (recovery_ax, breadth_ax, market_ax) = plt.subplots(1, 3, figsize=(13, 4.6))
|
|||
|
|
axes = [recovery_ax, breadth_ax, market_ax]
|
|||
|
|
fig.subplots_adjust(left=.065, right=.986, top=.74, bottom=.22, wspace=.29)
|
|||
|
|
chart_axes(axes)
|
|||
|
|
for ax in axes:
|
|||
|
|
ax.axvspan(-.1, 2.12, color=SHADE, alpha=.6, lw=0)
|
|||
|
|
ax.axvline(2.12, color=MUTED, ls=":", lw=.9)
|
|||
|
|
ax.set_xlim(-.15, 5.15)
|
|||
|
|
ax.set_xticks(range(6), [f"D{k}" for k in range(6)])
|
|||
|
|
for idx, warning in enumerate(warnings.itertuples(index=False)):
|
|||
|
|
ep = episodes.loc[episodes.episode_id.eq(warning.episode_id)].iloc[0]
|
|||
|
|
frame = paths[paths.episode_id.eq(ep.episode_id) & paths.k.between(0, 5)].sort_values("k")
|
|||
|
|
color = [ORANGE, BLUE, TEAL, PLUM][idx % 4]
|
|||
|
|
label = f"{date_label(ep.d0)} 初震"
|
|||
|
|
recovery_ax.plot(frame.k, frame.recovery * 100, lw=2.0, color=color,
|
|||
|
|
marker=".", markersize=8, label=label)
|
|||
|
|
market_ax.plot(frame.k, frame.dd_market * 100, lw=2.0, color=color,
|
|||
|
|
marker=".", markersize=8, label=label)
|
|||
|
|
newly = breadth.loc[breadth.episode_id.eq(ep.episode_id)].sort_values("k")
|
|||
|
|
if len(newly):
|
|||
|
|
cumulative = newly.first_shock_today.cumsum() * 100 / newly.initially_unpressured_count
|
|||
|
|
breadth_ax.plot(newly.k, cumulative, color=color, lw=2, marker=".", markersize=8)
|
|||
|
|
d2 = cumulative[newly.k.eq(2)]
|
|||
|
|
if len(d2):
|
|||
|
|
breadth_ax.annotate(f"{d2.iloc[0]:.2f}%", (2, d2.iloc[0]), xytext=(-5, 6),
|
|||
|
|
textcoords="offset points", ha="right", color=color, fontsize=10)
|
|||
|
|
first = frame[frame.onset_market.eq(1)]
|
|||
|
|
market_ax.scatter(first.k, first.dd_market * 100, s=100, facecolors="white",
|
|||
|
|
edgecolors=color, lw=2.1, zorder=5)
|
|||
|
|
recovery_ax.axhline(0, color=MUTED, lw=.8)
|
|||
|
|
recovery_ax.axhline(50, color=GOLD, ls="--", lw=1)
|
|||
|
|
market_ax.axhline(tail_threshold * 100, color=GOLD, ls="--", lw=1)
|
|||
|
|
for ax, level, text in [(recovery_ax, 50, "收回50%"),
|
|||
|
|
(market_ax, tail_threshold * 100, f"尾部阈值 {tail_threshold:.2%}")]:
|
|||
|
|
ax.annotate(text, xy=(.985, level), xycoords=("axes fraction", "data"),
|
|||
|
|
xytext=(0, 3), textcoords="offset points", ha="right", va="bottom",
|
|||
|
|
color="#705614", fontsize=9)
|
|||
|
|
lo, hi = recovery_ax.get_ylim()
|
|||
|
|
recovery_ax.set_ylim(lo, max(hi, 50 + .12 * (hi - lo)))
|
|||
|
|
for ax, title in zip(axes, ["中证2000收回首轮跌幅(%)", "累计首次下冲个股比例(%)",
|
|||
|
|
"沪深个股等权五日跌幅(%)"]):
|
|||
|
|
ax.set_title(title, loc="left", fontsize=11, pad=9)
|
|||
|
|
breadth_ax.set_ylim(bottom=0)
|
|||
|
|
market_ax.set_ylim(bottom=0)
|
|||
|
|
fig.legend(*recovery_ax.get_legend_handles_labels(), frameon=False, loc="upper center",
|
|||
|
|
bbox_to_anchor=(.52, .905), ncol=min(4, len(warnings)))
|
|||
|
|
fig.suptitle("收回不足的两条路径 | 微盘恢复、逐股扩散与沪深个股等权跌幅", y=.985, fontsize=15)
|
|||
|
|
fig.text(.52, .103, "浅黄区截至D2收盘。中图以D0未受压股票为固定分母,累计它们首次下冲达到1 ATR的比例,含中证2000成份股。", ha="center", fontsize=10)
|
|||
|
|
fig.text(.52, .043, "右图跌幅相对此前5个交易日最高收盘计算,空心圆为首次进入尾部。", ha="center", fontsize=10)
|
|||
|
|
fig.savefig(FIGURES / "收回不足的路径对照.png", dpi=150, metadata={"Software": "matplotlib"})
|
|||
|
|
path = FIGURES / "收回不足的路径对照.svg"
|
|||
|
|
save_svg(fig, path)
|
|||
|
|
return ('<h2>收回不足后的路径</h2><p class="context">下图覆盖B规则对沪深个股等权形成提醒、'
|
|||
|
|
'且能判为提前命中或误报的全部低位段。逐股分母固定为D0可计算且未受压的股票,'
|
|||
|
|
'未能按历史名单剔除中证2000成份股。D2收盘可见的走势位于浅黄区内。</p>'
|
|||
|
|
f'<figure class="chart-scroll">{picture(path, "收回比例与沪深个股等权的后续五日跌幅对照")}</figure>')
|
|||
|
|
|
|||
|
|
|
|||
|
|
def episode_body(ep, frame, warnings):
|
|||
|
|
identifier = int(ep.episode_id)
|
|||
|
|
label = f"第{identifier}段 {date_label(ep.start)} 至 {date_label(ep.end)}"
|
|||
|
|
entire = episode_chart(ep, frame)
|
|||
|
|
pieces = [f'<article id="episode-{identifier}" class="episode"><h3>{label}</h3>',
|
|||
|
|
f'<p>{int(ep.size)}个低位交易日。']
|
|||
|
|
if pd.isna(ep.d0):
|
|||
|
|
pieces.append("本段中证2000没有出现达到1 ATR的首轮下冲。</p>")
|
|||
|
|
else:
|
|||
|
|
pieces.append(f'首轮下冲 D0 为 {date_label(ep.d0)}。')
|
|||
|
|
if pd.notna(ep.d5):
|
|||
|
|
pieces.append(f'第5个后续交易日 D5 为 {date_label(ep.d5)}。</p>')
|
|||
|
|
else:
|
|||
|
|
pieces.append("样本末端尚未覆盖D5。</p>")
|
|||
|
|
initial = name_levels(ep.initial)
|
|||
|
|
pieces.append(f'<p>D0中证2000下跌 {ep.shock_atr:.2f} ATR。'
|
|||
|
|
+ (f"同日已受压的规模层为{initial}。" if initial != "—" else "同日其余三个规模层均未受压。"))
|
|||
|
|
if pd.notna(ep.spread_first):
|
|||
|
|
spread_k = int(frame.loc[frame.date.eq(ep.spread_first), "k"].iloc[0])
|
|||
|
|
pieces.append(f"首次新增规模层出现在D{spread_k}({date_label(ep.spread_first)})。")
|
|||
|
|
if spread_k > 2:
|
|||
|
|
pieces.append("该次扩散晚于D1至D2的规则观察期。")
|
|||
|
|
elif frame.loc[frame.k.eq(0), ["s1000", "s500", "s300"]].ge(1).all(axis=None):
|
|||
|
|
pieces.append("三个规模层在D0均已受压,后续可计入新增的规模层为零。")
|
|||
|
|
else:
|
|||
|
|
pieces.append("至已观察到的D5窗口末端,未发生新增规模层受压。")
|
|||
|
|
pieces.append("</p>")
|
|||
|
|
pieces.append(f"<p>从D0至D5,沪深个股等权的结果为“{escape(ep.market_outcome)}”,"
|
|||
|
|
f"三指数等权对照为“{escape(ep.proxy_outcome)}”。</p>")
|
|||
|
|
if ep.left_open or ep.right_open:
|
|||
|
|
side = "起点" if ep.left_open else "终点"
|
|||
|
|
pieces.append(f'<p class="context">低位延伸至样本{side},本段完整时长未知。</p>')
|
|||
|
|
pieces.append(f'<figure class="chart-scroll">{picture(entire, label + ",四指数、成交活跃度及五日跌幅")}</figure>')
|
|||
|
|
if pd.notna(ep.d0):
|
|||
|
|
zoom = shock_chart(ep, frame)
|
|||
|
|
pieces.append(f'<h3>首轮冲击后的五个交易日</h3><figure class="chart-scroll">'
|
|||
|
|
f'{picture(zoom, label + ",D0至D5收回比例和每日受冲击指数")}</figure>')
|
|||
|
|
rows = []
|
|||
|
|
for day in frame[frame.k.between(0, 5)].itertuples(index=False):
|
|||
|
|
k = int(day.k)
|
|||
|
|
stressed = [name for code, (name, _) in INDICES.items() if getattr(day, "s" + code) >= 1]
|
|||
|
|
rows.append([
|
|||
|
|
f'D{k} {date_label(day.date)}', percentage(day.recovery), "、".join(stressed) or "—",
|
|||
|
|
"起始日" if k == 0 else name_levels(day.new_today),
|
|||
|
|
int(day.new_count) if pd.notna(day.new_count) else "—",
|
|||
|
|
*[percentage(getattr(day, "dd_" + target)) for target in TARGETS],
|
|||
|
|
])
|
|||
|
|
pieces.append(html_table(["收盘", "微盘收回", "当日下冲达到1 ATR", "当日首次新增规模层",
|
|||
|
|
"累计新增层数", "个股等权五日跌幅", "三指数五日跌幅", "微盘五日跌幅"], rows))
|
|||
|
|
starts = []
|
|||
|
|
for target, (name, _) in TARGETS.items():
|
|||
|
|
points = frame.loc[frame[f"onset_{target}"].eq(1), "date"]
|
|||
|
|
if len(points):
|
|||
|
|
starts.append(f'{name} {", ".join(date_label(day) for day in points)}')
|
|||
|
|
pieces.append('<p><strong>图内尾部首日</strong> '
|
|||
|
|
+ ("。".join(starts) + "。" if starts else "未观察到可确认的尾部首日。") + "</p>")
|
|||
|
|
if len(warnings):
|
|||
|
|
rows = [
|
|||
|
|
[TARGETS[row.target][0], RULES[row.rule], date_label(row.date), STATUS[row.status],
|
|||
|
|
date_label(row.onset), int(row.lead) if pd.notna(row.lead) else "—"]
|
|||
|
|
for row in warnings.sort_values(["target", "date", "rule"]).itertuples(index=False)
|
|||
|
|
]
|
|||
|
|
pieces.append("<h3>当段提醒及后来结果</h3>")
|
|||
|
|
pieces.append(html_table(["目标", "规则", "提醒收盘", "核对结果", "对应尾部首日", "提前交易日"], rows))
|
|||
|
|
else:
|
|||
|
|
pieces.append("<p><strong>当段提醒</strong> 没有候选提醒。</p>")
|
|||
|
|
if int(frame.dd_market.isna().sum()):
|
|||
|
|
pieces.append(f'<p class="context">图内有 {int(frame.dd_market.isna().sum())} 个交易日缺少'
|
|||
|
|
'有效的沪深个股等权五日跌幅,蓝线缺失期间全市场尾部未知。</p>')
|
|||
|
|
pieces.append("</article>")
|
|||
|
|
return label, "".join(pieces)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def load_tables():
|
|||
|
|
tables = {}
|
|||
|
|
for name, dates in {"daily": ["date"], "episodes": ["start", "end", "d0", "d5"],
|
|||
|
|
"paths": ["date"], "alarms": ["date", "onset"], "tails": ["onset"]}.items():
|
|||
|
|
frame = pd.read_csv(ROOT / f"{name}.csv", dtype={"initial": "string", "new_today": "string"})
|
|||
|
|
for key in dates:
|
|||
|
|
# 八位日期也可能被 pandas 推断成整数。
|
|||
|
|
frame[key] = pd.to_datetime(frame[key].astype("string").str.replace(r"\.0$", "", regex=True),
|
|||
|
|
format="mixed", errors="raise")
|
|||
|
|
tables[name] = frame
|
|||
|
|
return tables
|
|||
|
|
|
|||
|
|
|
|||
|
|
def render():
|
|||
|
|
setup_plotting()
|
|||
|
|
tables = load_tables()
|
|||
|
|
daily = tables["daily"].sort_values("date").reset_index(drop=True)
|
|||
|
|
episodes = tables["episodes"].sort_values("start").reset_index(drop=True)
|
|||
|
|
alarms = tables["alarms"]
|
|||
|
|
tails = tables["tails"]
|
|||
|
|
if daily.date.duplicated().any() or episodes.episode_id.duplicated().any():
|
|||
|
|
raise ValueError("每个交易日和每个低位段只应出现一次。")
|
|||
|
|
peak = overview_chart(daily, episodes, alarms, tails)
|
|||
|
|
paths = tables["paths"][["episode_id", "date", "k", "recovery", "new_count", "new_today"]]
|
|||
|
|
paths = paths.merge(daily.drop(columns=["episode_id"]), on="date", how="left",
|
|||
|
|
indicator=True, validate="many_to_one")
|
|||
|
|
if paths["_merge"].ne("both").any() or paths.duplicated(["episode_id", "date"]).any():
|
|||
|
|
raise ValueError("逐段轨迹日期缺失或重复。")
|
|||
|
|
options, pages = [], []
|
|||
|
|
for ep in episodes.itertuples(index=False):
|
|||
|
|
frame = paths.loc[paths.episode_id == ep.episode_id].sort_values("date").reset_index(drop=True)
|
|||
|
|
if not (frame.date.eq(ep.start).any() and frame.date.eq(ep.end).any()):
|
|||
|
|
raise ValueError(f"第{ep.episode_id}段未覆盖首尾交易日。")
|
|||
|
|
label, page = episode_body(ep, frame, alarms.loc[alarms.episode_id == ep.episode_id])
|
|||
|
|
options.append(f'<option value="episode-{ep.episode_id}">{label} · {int(ep.size)}日</option>')
|
|||
|
|
pages.append(page)
|
|||
|
|
count = len(episodes)
|
|||
|
|
shock_count = int(episodes.d0.notna().sum())
|
|||
|
|
valid_market = daily.loc[daily.dd_market.notna(), "date"]
|
|||
|
|
primary_count = alarms.loc[alarms.rule.eq("D"), ["episode_id", "date"]].drop_duplicates().shape[0]
|
|||
|
|
summary = json.loads((ROOT / "summary.json").read_text(encoding="utf-8"))
|
|||
|
|
breadth = pd.read_csv(ROOT / "breadth.csv")
|
|||
|
|
comparison = recovery_comparison(episodes, paths, alarms, breadth, summary["thresholds"]["market"]["q95"])
|
|||
|
|
header = f"""<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">
|
|||
|
|
<meta name="viewport" content="width=device-width, initial-scale=1"><title>中证2000成交低位逐段图册</title>
|
|||
|
|
<style>{STYLE}</style></head><body><main><h1>中证2000成交低位与沪深尾部</h1>
|
|||
|
|
<p>{date_label(daily.date.min())} 至 {date_label(daily.date.max())},共 {count} 个成交低位段,其中 {shock_count} 段出现中证2000收盘下跌至少一个此前平均真实波幅(ATR)。</p>
|
|||
|
|
<p><strong>主规则形成 {primary_count} 次候选提醒。</strong>它要求在D1或D2同日看到首轮跌幅收回不足50%、且至少新增一个受压规模层。沪深个股等权五日跌幅最后一个有读数的收盘为 {date_label(valid_market.max())},其后仅宽基与微盘对照可观察。</p>
|
|||
|
|
<h2>全部低位段与尾部首日</h2>
|
|||
|
|
<p class="context">浅黄色为中证2000成交活跃度低于自身历史第15百分位的连续交易日。折线中的空心圆为各组合进入自身尾部的首日。五日跌幅按当日收盘相对前五日最高收盘计算,尾部阈值取各组合2021至2023年五日跌幅的第95百分位。数据缺口以断线表示。</p>
|
|||
|
|
<figure class="chart-scroll">{picture(peak, "全观察期成交活跃度、三种五日跌幅、主规则提醒和尾部首日")}</figure>
|
|||
|
|
<p class="context">沪深个股等权使用当日有有效收益的沪深A股。三指数等权组合按沪深300、中证500、中证1000各占三分之一计算。中证2000自身用于查看局部下跌。提醒在当日收盘形成,最早从下一交易日起计提前命中。</p>
|
|||
|
|
<details><summary>查看五种规则的提醒和漏报数量</summary>{rule_counts(alarms, tails)}</details>
|
|||
|
|
{comparison}
|
|||
|
|
<section id="episodes"><h2>逐段核对</h2>
|
|||
|
|
<p class="context">首张图从该段起点画到低位结束与D5两者中较晚的一天。浅黄色仅标本段,橙色虚线为D0,灰色虚线为D5。微盘收回比例低于零表示跌破D0收盘,高于100%表示已收回超过首轮的下跌。新增规模层只计D0之后首次受压的其他指数。</p>
|
|||
|
|
<div class="nav"><label for="chooser">选择低位段</label><select id="chooser">{"".join(options)}</select>
|
|||
|
|
<button id="previous" type="button">上一段</button><button id="next" type="button">下一段</button></div>
|
|||
|
|
"""
|
|||
|
|
ALBUM.write_text(header + "".join(pages) + f"</section></main><script>{NAVIGATION}</script></body></html>",
|
|||
|
|
encoding="utf-8")
|
|||
|
|
print(f"已生成{count}段完整图、{shock_count}张冲击路径图和首轮总览。")
|
|||
|
|
|
|||
|
|
|
|||
|
|
def shock_chart(episode, frame):
|
|||
|
|
"""只画实际存在的D0至D5观察点,短随访保留空白列。"""
|
|||
|
|
follow = frame[frame.k.between(0, 5)].copy().set_index("k").reindex(range(6))
|
|||
|
|
fig, (recovery, orders) = plt.subplots(2, 1, figsize=(8.4, 4.4), sharex=True,
|
|||
|
|
gridspec_kw={"height_ratios": [1.4, 1]})
|
|||
|
|
fig.subplots_adjust(left=.14, right=.97, top=.90, bottom=.15, hspace=.42)
|
|||
|
|
chart_axes([recovery])
|
|||
|
|
recovery.axhline(0, color=MUTED, lw=.8)
|
|||
|
|
recovery.axhline(50, color=GOLD, ls="--", lw=1.2, label="收回50%")
|
|||
|
|
recovery.plot(range(6), follow.recovery * 100, color=ORANGE, lw=1.85, marker="o",
|
|||
|
|
label="中证2000收回首日冲击的比例")
|
|||
|
|
chart_legend(recovery)
|
|||
|
|
recovery.set_ylabel("收回比例(%)")
|
|||
|
|
pressure_strip(orders, follow, np.arange(6))
|
|||
|
|
orders.set_title("菱形为当日下冲达 1 ATR,黑圈标出首次新增的受压规模层", loc="left",
|
|||
|
|
fontsize=10, pad=6, color=MUTED)
|
|||
|
|
for k, value in follow.new_today.dropna().items():
|
|||
|
|
for code in str(value).split("|"):
|
|||
|
|
if code in INDICES:
|
|||
|
|
orders.scatter(k, list(INDICES).index(code), s=127, facecolors="none",
|
|||
|
|
edgecolors=INK, linewidths=1.35, zorder=4)
|
|||
|
|
orders.set_xlim(-.3, 5.3)
|
|||
|
|
orders.grid(axis="x", color="#dbe4e9", lw=.7)
|
|||
|
|
orders.set_xticks(range(6), [
|
|||
|
|
f"D{k}\n{day.strftime('%m-%d')}" if pd.notna(day) else f"D{k}\n缺观察"
|
|||
|
|
for k, day in enumerate(follow.date)
|
|||
|
|
])
|
|||
|
|
path = FIGURES / f"冲击路径-{int(episode.episode_id):03d}.svg"
|
|||
|
|
save_svg(fig, path)
|
|||
|
|
return path
|
|||
|
|
|
|||
|
|
|
|||
|
|
def overview_chart(daily, episodes, alarms, tails):
|
|||
|
|
fig, axes = plt.subplots(3, 1, figsize=(12.2, 7.35), sharex=True,
|
|||
|
|
gridspec_kw={"height_ratios": [.85, 1.45, 1.0]})
|
|||
|
|
fig.subplots_adjust(left=.12, right=.975, top=.89, bottom=.125, hspace=.64)
|
|||
|
|
n_main = len(alarms.loc[alarms.rule.eq("D"), ["episode_id", "date"]].drop_duplicates())
|
|||
|
|
fig.suptitle(f"中证2000成交低位与尾部风险 | {len(episodes)}个低位段,"
|
|||
|
|
f"{int(episodes.d0.notna().sum())}段首次下冲,主规则提醒{n_main}次",
|
|||
|
|
y=.98, fontsize=15)
|
|||
|
|
chart_axes(axes[:2])
|
|||
|
|
dates = pd.Index(daily.date)
|
|||
|
|
for ep in episodes.itertuples(index=False):
|
|||
|
|
start = dates.get_loc(ep.start) - .5
|
|||
|
|
end = dates.get_loc(ep.end) + .5
|
|||
|
|
for ax in axes:
|
|||
|
|
ax.axvspan(start, end, color=SHADE, alpha=.68, lw=0, zorder=0)
|
|||
|
|
x = np.arange(len(daily))
|
|||
|
|
axes[0].plot(x, daily.pct * 100, color=INK, lw=.85, label="中证2000成交活跃度")
|
|||
|
|
axes[0].axhline(15, color=GOLD, ls="--", lw=1.25, label="低位门槛(15)")
|
|||
|
|
axes[0].set_ylim(0, 103)
|
|||
|
|
axes[0].set_ylabel("历史百分位(%)")
|
|||
|
|
chart_legend(axes[0])
|
|||
|
|
drawdown_chart(axes[1], daily)
|
|||
|
|
last_market = daily.loc[daily.dd_market.notna(), "date"].max()
|
|||
|
|
if pd.notna(last_market) and last_market < daily.date.max():
|
|||
|
|
position = dates.get_loc(last_market)
|
|||
|
|
axes[1].axvline(position, color=BLUE, lw=.9, ls=":")
|
|||
|
|
axes[1].annotate(f"个股等权覆盖至 {date_label(last_market)}", xy=(position, .96),
|
|||
|
|
xycoords=("data", "axes fraction"), xytext=(-5, 0), textcoords="offset points",
|
|||
|
|
ha="right", va="top", color=BLUE, fontsize=9)
|
|||
|
|
events_ax = axes[2]
|
|||
|
|
for offset, target in enumerate(("market", "proxy")):
|
|||
|
|
rows = tails[(tails.rule == "D") & (tails.target == target)]
|
|||
|
|
for status, marker, color in [("hit", "o", TEAL), ("miss", "x", ORANGE)]:
|
|||
|
|
points = dates.get_indexer(pd.Index(rows.loc[rows.status == status, "onset"]))
|
|||
|
|
points = points[points >= 0]
|
|||
|
|
labels = {"hit": "提前命中的尾部首日", "miss": "漏报的尾部首日"}
|
|||
|
|
events_ax.scatter(points, np.full(len(points), offset * 2), marker=marker,
|
|||
|
|
color=color, label=labels[status] if offset == 0 else None, s=31, lw=1.2)
|
|||
|
|
warnings = alarms[(alarms.rule == "D") & (alarms.target == target)]
|
|||
|
|
points = dates.get_indexer(pd.Index(warnings.date))
|
|||
|
|
points = points[points >= 0]
|
|||
|
|
events_ax.scatter(points, np.full(len(points), offset * 2 + 1), marker="|", s=77,
|
|||
|
|
color=PLUM, label="D规则的提醒日" if offset == 0 else None, lw=1.4)
|
|||
|
|
events_ax.set_yticks(range(4), ["个股等权 · 尾部", "个股等权 · 提醒",
|
|||
|
|
"三指数 · 尾部", "三指数 · 提醒"])
|
|||
|
|
events_ax.set_ylim(3.65, -.65)
|
|||
|
|
events_ax.grid(axis="y", color="#e1e8eb", lw=.7)
|
|||
|
|
chart_legend(events_ax)
|
|||
|
|
date_axis(events_ax, daily.date.to_list(), count=9, year=True)
|
|||
|
|
events_ax.set_xlabel("交易月份")
|
|||
|
|
events_ax.set_xlim(-.5, len(daily) - .5)
|
|||
|
|
fig.text(.53, .02, "浅黄为成交低位段。空心圆为各组合五日跌幅达到自身历史尾部的首日。"
|
|||
|
|
" 主规则要求初震后两日内同时收回不足、出现新增规模层下冲。", fontsize=9, ha="center")
|
|||
|
|
fig.savefig(FIGURES / "首轮总览.png", dpi=150, metadata={"Software": "matplotlib"})
|
|||
|
|
path = FIGURES / "首轮总览.svg"
|
|||
|
|
save_svg(fig, path)
|
|||
|
|
return path
|
|||
|
|
|
|||
|
|
|
|||
|
|
if __name__ == "__main__":
|
|||
|
|
render()
|