TrueHOOHA/shanxi-securities-tushare-skill / sxsc-tushare-analysis
sxsc-tushare-analysis
Verified对用户提到的标的(沪深股票、指数、公募基金、期货)进行综合分析,输出带 ECharts 图表的 HTML 分析报告。 触发条件:用户说"分析""研究""评估""看看XX怎么样""XX基本面""XX技术面""XX估值""XX财务""深度研究""对比"等分析类请求,且标的属于 A 股/指数/公募基金/期货。 本 skill 自动调用 sxsc_tushare 取数并输出完整报告,接管数据获取与分析全流程。当本 skill 被触发时,数据获取类 skill 不应同时激活——分析已包含数据。
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 43.8 KB |
| scripts/adjustment.py | script | 8.7 KB |
| scripts/analysis_runner.py | script | 120.8 KB |
| scripts/attribution.py | script | 10.1 KB |
| scripts/basic_metrics.py | script | 4.3 KB |
| scripts/check_env.py | script | 8.8 KB |
| scripts/data_api.py | script | 41.2 KB |
| scripts/factor_signals.py | script | 10.3 KB |
| scripts/fund_analysis_runner.py | script | 61.7 KB |
| scripts/fut_analysis_runner.py | script | 41.4 KB |
| scripts/index_analysis_runner.py | script | 54.6 KB |
| scripts/report_html.py | script | 38.0 KB |
| scripts/result_model.py | script | 4.4 KB |
| scripts/risk_modeling.py | script | 6.3 KB |
| scripts/stock_analyzer.py | script | 1.1 KB |
| scripts/technical_indicators.py | script | 5.9 KB |
| scripts/token_util.py | script | 4.0 KB |
scripts/report_html.py
View on GitHub#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""HTML 报告渲染器:把 runner 产出的 markdown 报告 + DimensionResult 图表数据渲染为独立 HTML。
图表规格(由各 runner 在 DimensionResult.data["chart"] 中填入):
{"title": str, "type": "line" | "bar" | "candlestick",
"dates": [...], # x 轴日期(str)
"series": [{"name": str, "data": [...]}, ...], # line / bar 用
"ohlc": [[open, close, low, high], ...], "vol": [...]} # candlestick 用
数组须为 JSON 安全类型(pandas Series 用 .tolist() 转换)。
"""
import html as _html
import json
import math
import re
from datetime import datetime
ECHARTS_CDN = "https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js"
_CSS = """
:root{--ink:#1a1a1a;--accent:#2c6fbb;--muted:#5f656d;--faint:#9aa0a8;--border:#e6e8eb}
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:-apple-system,'Segoe UI','Microsoft YaHei','PingFang SC',system-ui,sans-serif;max-width:none;margin:0 auto;padding:0;color:var(--ink);line-height:1.75;background:#fff;-webkit-font-smoothing:antialiased}
/* 目录点击/锚点跳转平滑滚动;尊重系统"减少动态效果"设置 */
html{scroll-behavior:smooth}
@media (prefers-reduced-motion: reduce){html{scroll-behavior:auto}}
.layout{display:flex;gap:28px;max-width:1240px;margin:0 auto;padding:44px 24px 80px;align-items:flex-start}
.content{flex:1;min-width:0}
.toc{position:sticky;top:20px;flex:0 0 190px;max-height:calc(100vh - 40px);overflow:auto;font-size:12.5px;background:#fafbfc;border:1px solid var(--border);border-radius:10px;padding:12px 10px}
.toc-title{font-size:12px;color:var(--faint);font-weight:600;margin-bottom:8px;letter-spacing:.05em}
.toc a{display:flex;gap:8px;color:var(--muted);text-decoration:none;padding:4px 6px;border-radius:6px;line-height:1.4}
.toc a:hover{color:var(--accent);background:#eef4fb}
.toc a.active{color:var(--accent);background:#eef4fb;font-weight:600}
.toc a .n{color:var(--faint);font-size:11px;min-width:16px;text-align:right}
@media (max-width:920px){.layout{display:block;padding:44px 20px 80px}.toc{display:none}}
h1{font-size:24px;font-weight:700;letter-spacing:.005em;margin-bottom:6px}
blockquote{font-size:13px;color:var(--muted);margin:0 0 12px;padding-left:10px;border-left:2px solid var(--border)}
h2{font-size:17px;font-weight:600;display:flex;align-items:baseline;gap:10px;margin:38px 0 14px;padding-bottom:10px;border-bottom:1px solid var(--border);scroll-margin-top:16px}
h2 .num{color:var(--faint);font-weight:600;font-size:12.5px}
h3{font-size:13.5px;font-weight:600;color:#333;margin:20px 0 8px}
p{font-size:13.5px;margin-bottom:10px}
p.ph{margin-top:20px}
p em{color:var(--muted);font-size:12px}
.table-wrap{overflow-x:auto;margin:14px 0 8px;border:1px solid var(--border);border-radius:8px}
/* 固定布局 + 等分列宽:表头与数据列按列数均分,数值列右对齐 */
table{border-collapse:collapse;width:100%;table-layout:fixed;font-size:13px;font-variant-numeric:tabular-nums}
thead th{padding:8px 12px;font-weight:600;color:#333;text-align:left;background:#f7f8f9;border-bottom:1.5px solid #333;word-break:break-word;letter-spacing:.02em}
tbody td{padding:8px 12px;border-bottom:1px solid var(--border);vertical-align:top;word-break:break-word}
td.r{text-align:right;word-break:keep-all;overflow-wrap:anywhere}
th.r{text-align:right}
tbody td:first-child{font-weight:500;padding-right:22px}
/* 两列表:首列收窄、值列留白,避免内容被拉向两端 */
table.col-2 th:first-child,table.col-2 td:first-child{width:34%}
table.col-2 th:not(:first-child),table.col-2 td:not(:first-child){width:66%}
tbody tr:nth-child(even){background:#fafbfc}
tbody tr:hover{background:#eef4fb}
tbody tr:last-child td{border-bottom:none}
code{font-family:ui-monospace,'SF Mono',Consolas,Menlo,monospace;font-size:12.5px;background:#f4f5f6;padding:1px 6px;border-radius:4px}
ul{margin:8px 0 14px;padding-left:20px}
ul li{font-size:13.5px;margin:3px 0}
hr{border:none;border-top:1px solid var(--border);margin:30px 0 10px}
.chart{width:100%;height:430px;margin:14px 0 4px}
.kpi-bar{display:flex;flex-wrap:wrap;gap:12px;margin:0 0 6px}
.kpi{background:#f7f8f9;border:1px solid var(--border);border-radius:12px;padding:10px 18px;min-width:96px}
.kpi-label{font-size:11.5px;color:var(--muted);margin-bottom:3px}
.kpi-value{font-size:19px;font-weight:700;font-variant-numeric:tabular-nums}
.kpi-value.up{color:#d0342c}
.kpi-value.down{color:#16a34a}
.badge{display:inline-block;color:#fff;font-size:12px;font-weight:600;padding:1px 10px;border-radius:10px;margin:0 2px;vertical-align:1px}
.footer{color:var(--faint);font-size:12px;margin-top:0;padding-top:6px;text-align:center}
@media print{.toc{display:none}.layout{display:block;max-width:none;padding:0}.chart{height:340px}body{-webkit-print-color-adjust:exact;print-color-adjust:exact}h2{page-break-after:avoid}.table-wrap{page-break-inside:avoid}}
"""
_INIT_JS = """
for (const [id, option] of Object.entries(CHARTS)) {
const el = document.getElementById(id);
if (!el) continue;
const chart = echarts.init(el);
chart.setOption(option);
window.addEventListener("resize", () => chart.resize());
}
// 目录点击跳转:用 scrollIntoView 平滑滚动到目标章节,并同步高亮。
// ⚠️ 不能只依赖原生 #hash 跳转:报告在 iframe 预览 / srcdoc / blob URL 场景下
// 文档地址不是真实文件路径,点击 <a href="#sec-N"> 可能不触发滚动。
// scrollIntoView 与文档地址无关,任何打开方式都可用;保留 href 作为降级。
document.querySelectorAll('.toc a').forEach(_a => {
_a.addEventListener('click', _e => {
const _t = document.querySelector(_a.getAttribute('href'));
if (_t) {
_e.preventDefault();
_t.scrollIntoView({behavior: 'smooth', block: 'start'});
document.querySelectorAll('.toc a').forEach(_x => _x.classList.remove('active'));
_a.classList.add('active');
}
});
});
// 目录 scrollspy:滚动时高亮当前章节
if (window.IntersectionObserver) {
const _links = [...document.querySelectorAll('.toc a')];
if (_links.length) {
const _byId = {};
_links.forEach(a => _byId[a.getAttribute('href').slice(1)] = a);
const _obs = new IntersectionObserver(es => {
es.forEach(e => {
if (e.isIntersecting) {
_links.forEach(a => a.classList.remove('active'));
const a = _byId[e.target.id];
if (a) a.classList.add('active');
}
});
}, {rootMargin: '-15% 0px -75% 0px'});
document.querySelectorAll('h2[id]').forEach(h => _obs.observe(h));
}
}
"""
# ---------- 内联脚本序列化 ----------
def _json_default(o):
"""json.dumps 的兜底:numpy 标量/数组转原生类型(数字仍是数字),其余转字符串。
图表数据来自 pandas(np.int64 / np.bool_ / Timestamp / pd.NA 等),
这些都不是 JSON 原生类型;没有兜底时 json.dumps 会抛 TypeError 让整页渲染失败。
"""
tolist = getattr(o, "tolist", None)
if callable(tolist):
try:
return tolist() # ndarray / Series → 原生 list
except Exception:
pass
item = getattr(o, "item", None)
if callable(item):
try:
v = item() # numpy 标量 → Python 标量,保住数值类型
if v is None or isinstance(v, (str, int, float, bool)):
return v
except Exception:
pass
return str(o)
def _json_script(obj) -> str:
r"""序列化为可安全内联进 <script> 的 JSON 文本。
必须把 `<` 转义为 `\u003c`:图表标题/序列名里一旦出现 `</script>`
(股东名、指数名、基金名含 `<` 时很常见)就会提前闭合脚本标签,
其后内容被浏览器当 HTML 解析,图表脚本失效且可注入任意标签。
`>`、`&`、U+2028/2029 同理转义;转义后的 `\u003c` 在 JS 字符串里仍是字面 `<`,
JS 取到的值不变,只是源码里不再出现可闭合标签的字符。
"""
s = json.dumps(obj, ensure_ascii=False, default=_json_default)
for ch, esc in (("<", "\\u003c"), (">", "\\u003e"), ("&", "\\u0026"),
("\u2028", "\\u2028"), ("\u2029", "\\u2029")):
s = s.replace(ch, esc)
return s
# ---------- 数值占位 ----------
# 缺失/非数值的统一占位:不再输出 "nan" / "N/A%" 这类半成品文案
_NA_TEXT = "—"
def _num_text(v, digits=2, suffix=""):
"""安全数值格式化:None / NaN / inf / 非数值一律返回统一占位,绝不抛异常。"""
try:
f = float(v)
except (TypeError, ValueError):
return _NA_TEXT
if not math.isfinite(f):
return _NA_TEXT
return f"{f:,.{digits}f}{suffix}"
def _inline(text):
"""行内 markdown → HTML(code / 加粗 / 斜体),先转义再套标签。"""
s = _html.escape(text)
s = re.sub(r"`([^`]+)`", r"<code>\1</code>", s)
s = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", s)
s = re.sub(r"(?<!\*)\*([^*]+)\*(?!\*)", r"<em>\1</em>", s)
return s
def _is_block_start(s):
"""该行是否开启新块(段落应在此停止续行)。"""
return (
not s
or s.startswith("#")
or s.startswith("|")
or s.startswith("- ")
or s.startswith("> ")
or re.fullmatch(r"-{3,}", s)
)
_NUM_RE = re.compile(r"^[-+]?[0-9][0-9,]*(?:\.[0-9]+)?(?:%|亿|万|万亿|元)?$")
# 缺失/无数据占位符:这些值不参与数值列判定,但单元格本身仍需与同列数字对齐
_MISSING = {"N/A", "-", "—", "NA", "None", "nan"}
# 含中文(含全角标点)的单元格一律视为文本:数值列不应出现中文描述
_HAS_CJK = re.compile(r"[\u4e00-\u9fff\uff00-\uffef]")
# 日期(YYYYMMDD 8 位 或 YYYY-MM-DD / YYYY-MM):形似数字但属文本列,须左对齐。
# ⚠️ 不能匹配 6 位数字:成交量"100000"这类值会被误判成日期列(YYYYMM),
# 整列变成文本左对齐(样式错)。8 位整串或带横线的完整日期才判日期。
_DATE_RE = re.compile(r"^(?:\d{8}|\d{4}-\d{2}(?:-\d{2})?)$")
# 表头日期/标识列关键词(中英文):这些列的值即便形似数字也按文本左对齐
_DATE_KEY = re.compile(
r"(日期|时间|日$|date|trade_date|end_date|ann_date|start_date|float_date|ex_date)", re.I)
# 单元格切分:裸 `|` 是列分隔符,`\|` 是转义(评级「AAA|AA+」等值必须能原样落在单元格里)
_PIPE_SPLIT = re.compile(r"(?<!\\)\|")
def _split_row(s):
r"""按裸管道切分表格行,`\|` 转义还原为字面 `|`。
原先直接 split("|"):`| 债券 | AAA\|AA+ |` 会被切成 3 段,
table-layout:fixed 下多出的单元格把整表挤错位。
"""
body = s.strip()
if body.startswith("|"):
body = body[1:]
while body.endswith("|"):
# 行尾裸 | 是分隔符;`\|` 属单元格内容,反斜杠为奇数个时不能剥
bs = 0
k = len(body) - 2
while k >= 0 and body[k] == "\\":
bs += 1
k -= 1
if bs % 2:
break
body = body[:-1]
return [c.replace("\\|", "|").strip() for c in _PIPE_SPLIT.split(body)]
def _md_table(lines, i):
"""解析从 lines[i] 起的管道表格;数值列自动右对齐,返回 (html, 下一行下标)。"""
header = _split_row(lines[i])
j = i + 1
if j < len(lines) and re.fullmatch(r"[\s|:\-]+", lines[j].strip()):
j += 1 # 表头分隔行
rows = []
while j < len(lines) and lines[j].strip().startswith("|"):
rows.append(_split_row(lines[j]))
j += 1
# 每行单元格数必须与表头一致:多则截断(否则 fixed 布局整表错位),少则补空
ncol = len(header)
rows = [(r + [""] * ncol)[:ncol] for r in rows]
# 逐列判定右对齐:以「整列」为单位,禁止逐单元格切换——否则同列内
# 文本左对齐、数字右对齐会左右横跳(概况表「员工数/注册资本」即此类)。
# 判定用「该列不含中文文本」而非占比:占比法会把
# {简称, 员工数 34,992, 注册资本 12.50亿} 这类文本列误判为数值列。
def _is_numeric_col(col):
# 表头参与判定:「除权除息日」「end_date」等已明示为日期/标识列,
# 其值即使形如 20240619 也应按文本左对齐
if _DATE_KEY.search(header[col]):
return False
vals = [r[col] for r in rows if col < len(r) and r[col]]
if not vals:
return False
if any(_HAS_CJK.search(v) or _DATE_RE.match(v) for v in vals):
return False # 含中文或日期 → 文本列,左对齐
return any(_NUM_RE.match(v) or v in _MISSING for v in vals)
numeric = [_is_numeric_col(c) for c in range(len(header))]
cls = lambda col: " class='r'" if col < len(numeric) and numeric[col] else ""
head = "".join(f"<th{cls(col)}>{_inline(header[col])}</th>" for col in range(ncol))
body = ""
for r in rows:
# 行已在上面按 ncol 截断/补齐,故 td 数恒等于表头列数,不再单独补缺列
cells_html = "".join(
f"<td{cls(col)}>{_inline(c)}</td>" for col, c in enumerate(r))
body += f"<tr>{cells_html}</tr>"
# col-2 供 CSS 收窄首列,其余表型沿用 fixed 布局均分
return (f"<div class='table-wrap'><table class='col-{ncol}'>"
f"<thead><tr>{head}</tr></thead>"
f"<tbody>{body}</tbody></table></div>", j)
def df_to_md_table(df):
"""已格式化的 DataFrame → GFM 管道表格(替代 to_markdown,无 tabulate 依赖)。"""
if df is None or df.empty:
return ""
# 值里的裸 | 必须转义成 \|(_split_row 会还原),否则它被当成列分隔符:
# 行内单元格数多于表头,截断后数据静默丢失;换行同理会把一行拆成两行破坏表格
def _cell(v):
return " ".join(str(v).splitlines()).replace("|", "\\|")
header = [_cell(c) for c in df.columns]
lines = [
"| " + " | ".join(header) + " |",
"|" + "|".join(["---"] * len(header)) + "|",
]
for row in df.astype(str).values.tolist():
lines.append("| " + " | ".join(_cell(v) for v in row) + " |")
return "\n".join(lines)
def md_to_html(md: str) -> str:
"""把 runner 生成的 markdown 子集转换为 HTML 正文。"""
lines = md.splitlines()
out = []
i = 0
while i < len(lines):
s = lines[i].strip()
if not s: # 跳过空行:避免空行并入下一段落(段首空格 + 破坏 ** 前缀判定)
i += 1
continue
if s.startswith("# "):
out.append(f"<h1>{_inline(s[2:])}</h1>")
elif s.startswith("## "):
out.append(f"<h2>{_inline(s[3:])}</h2>")
elif s.startswith("### "):
out.append(f"<h3>{_inline(s[4:])}</h3>")
elif re.fullmatch(r"-{3,}", s):
out.append("<hr>")
elif s.startswith("|"):
table_html, i = _md_table(lines, i)
out.append(table_html)
continue
elif s.startswith("- "):
items = []
while i < len(lines) and lines[i].strip().startswith("- "):
items.append(f"<li>{_inline(lines[i].strip()[2:])}</li>")
i += 1
out.append("<ul>" + "".join(items) + "</ul>")
continue
elif s.startswith("> "):
quotes = []
while i < len(lines) and lines[i].strip().startswith("> "):
quotes.append(_inline(lines[i].strip()[2:]))
i += 1
out.append("<blockquote>" + "<br>".join(quotes) + "</blockquote>")
continue
else:
para = [s]
i += 1
while i < len(lines) and not _is_block_start(lines[i].strip()):
para.append(lines[i].strip())
i += 1
_pcls = " class='ph'" if para and para[0].startswith("**") else ""
out.append(f"<p{_pcls}>{_inline(' '.join(para))}</p>")
continue
i += 1
return "\n".join(out)
# ---------- ECharts option ----------
def _candlestick_option(c):
# 红涨绿跌(收敛色),无上/右边框,统一深色 tooltip,细网格
return {
"title": {"text": c.get("title", ""), "left": 0,
"textStyle": {"color": "#1a1a1a", "fontSize": 13, "fontWeight": 600}},
"animationDuration": 500,
"tooltip": {"trigger": "axis",
"axisPointer": {"type": "cross", "crossStyle": {"color": "#bbb"}},
"backgroundColor": "rgba(26,26,26,.92)", "borderColor": "transparent",
"padding": [8, 12], "textStyle": {"color": "#fff", "fontSize": 12}},
"axisPointer": {"link": [{"xAxisIndex": "all"}]},
"grid": [
{"left": 56, "right": 16, "top": 36, "height": "52%"},
{"left": 56, "right": 16, "top": "70%", "height": "16%"},
],
"xAxis": [
{"type": "category", "data": c["dates"], "gridIndex": 0,
"axisLabel": {"show": False}, "axisLine": {"show": False}, "axisTick": {"show": False}},
{"type": "category", "data": c["dates"], "gridIndex": 1,
"axisLabel": {"color": "#9aa0a8", "fontSize": 9, "fontWeight": 500},
"axisLine": {"lineStyle": {"color": "#e6e8eb"}}, "axisTick": {"show": False}},
],
"yAxis": [
{"type": "value", "gridIndex": 0, "scale": True,
"axisLabel": {"color": "#9aa0a8", "fontSize": 9.5, "fontWeight": 500},
"axisLine": {"show": False}, "axisTick": {"show": False},
"splitLine": {"lineStyle": {"color": "#eef0f2", "width": 1}}},
{"type": "value", "gridIndex": 1,
"axisLabel": {"show": False}, "axisLine": {"show": False}, "axisTick": {"show": False},
"splitLine": {"show": False}},
],
"dataZoom": [
{"type": "inside", "xAxisIndex": [0, 1], "start": 40, "end": 100},
{"type": "slider", "xAxisIndex": [0, 1], "top": "92%", "start": 40, "end": 100,
"height": 12, "borderColor": "transparent", "backgroundColor": "#f0f1f3",
"fillerColor": "#d5e2f2", "handleStyle": {"color": "#2c6fbb"},
"textStyle": {"color": "#9aa0a8", "fontSize": 9}},
],
"series": [
{"type": "candlestick", "name": "日K", "data": c["ohlc"], "barWidth": "55%",
"itemStyle": {"color": "#d0342c", "color0": "#16a34a",
"borderColor": "#d0342c", "borderColor0": "#16a34a",
"borderWidth": 1}},
{"type": "bar", "name": "成交量", "xAxisIndex": 1, "yAxisIndex": 1,
"data": c.get("vol", []),
"itemStyle": {"color": "rgba(44,111,187,.35)"}},
],
}
def _line_bar_option(c):
# 受控语义色板:蓝=主指标,红=对比/流出,灰=辅助,绿=正向
_SERIES = ["#2c6fbb", "#d0342c", "#8a8f98", "#16a34a"]
t = c.get("type", "line")
# 系列通过 "yAxisIndex": 1 挂右轴(如 PE/PB 量纲悬殊时);未指定则默认左轴
dual = any(s.get("yAxisIndex") == 1 for s in c.get("series", []))
series = []
for i, s in enumerate(c.get("series", [])):
color = _SERIES[i % len(_SERIES)]
base = dict(s, type=t, itemStyle={"color": color})
if t == "line":
base.update({"smooth": True, "symbol": "none",
"lineStyle": {"width": 1.6, "color": color}})
else:
base.update({"barMaxWidth": 16})
series.append(base)
axis_style = {"axisLabel": {"color": "#9aa0a8", "fontSize": 9.5, "fontWeight": 500},
"axisLine": {"show": False}, "axisTick": {"show": False}}
y_axes = [dict(axis_style, type="value",
splitLine={"lineStyle": {"color": "#eef0f2", "width": 1}})]
if dual:
y_axes.append(dict(axis_style, type="value", splitLine={"show": False})) # 右轴不重复画网格
return {
"title": {"text": c.get("title", ""), "left": 0,
"textStyle": {"color": "#1a1a1a", "fontSize": 13, "fontWeight": 600}},
"animationDuration": 600,
"animationEasing": "quarticOut",
"tooltip": {"trigger": "axis", "backgroundColor": "rgba(26,26,26,.92)",
"borderColor": "transparent", "padding": [8, 12],
"textStyle": {"color": "#fff", "fontSize": 12}},
"legend": {"top": 0, "right": 0, "itemWidth": 10, "itemHeight": 3,
"textStyle": {"color": "#5f656d", "fontSize": 11}},
"grid": {"left": 50, "right": 30, "top": 38, "bottom": 48},
"xAxis": {"type": "category", "data": c["dates"], "boundaryGap": t == "bar",
"axisLabel": {"color": "#9aa0a8", "fontSize": 9.5, "fontWeight": 500},
"axisLine": {"lineStyle": {"color": "#e6e8eb"}}, "axisTick": {"show": False}},
"yAxis": y_axes,
"dataZoom": [
{"type": "inside", "start": 0, "end": 100},
{"type": "slider", "bottom": 4, "start": 0, "end": 100,
"height": 12, "borderColor": "transparent", "backgroundColor": "#f0f1f3",
"fillerColor": "#d5e2f2", "handleStyle": {"color": "#2c6fbb"},
"textStyle": {"color": "#9aa0a8", "fontSize": 9}},
],
"series": series,
}
def _pie_option(c):
"""饼图规格:c["data"] = [{"name": str, "value": number}, ...],value 为占比数值(如持股比例%)。"""
return {
"tooltip": {"trigger": "item", "formatter": "{b}<br/>{c}%"},
"legend": {"type": "scroll", "orient": "vertical", "right": 4, "top": "middle",
"icon": "circle", "itemWidth": 8, "textStyle": {"fontSize": 11}},
"series": [{
"type": "pie",
"radius": ["38%", "64%"],
"center": ["36%", "52%"],
"minAngle": 2,
"avoidLabelOverlap": True,
"itemStyle": {"borderRadius": 4, "borderColor": "#fff", "borderWidth": 1},
"label": {"show": False},
"emphasis": {"label": {"show": True, "fontSize": 12}},
"data": c["data"],
}],
}
def _chart_options(results):
"""按维度顺序收集各维度的图表 option,返回 [(维度标题, option), ...]。"""
out = []
for _key, res in (results or {}).items():
# res 可能为 None(维度缺失/上游未产出)、data 可能不是 dict:跳过而不是整页崩
if res is None or not res.is_ok() or not isinstance(res.data, dict):
continue
c = res.data.get("chart")
if not isinstance(c, dict):
continue # 无图表数据或图表规格非法(如 None / list)
t = c.get("type")
# dates 是各 option 的必需字段,缺了会在 _line_bar_option 里 KeyError
if t == "candlestick" and c.get("ohlc") and c.get("dates"):
out.append((res.title, _candlestick_option(c)))
elif t in ("line", "bar") and c.get("series") and c.get("dates"):
out.append((res.title, _line_bar_option(c)))
elif t == "pie" and c.get("data"):
out.append((res.title, _pie_option(c)))
return out
def _page_title(md: str) -> str:
for line in md.splitlines():
s = line.strip()
if s.startswith("# "):
return _html.escape(s[2:])
return "分析报告"
def _kpi_items(results):
"""从分析结果提取核心指标,供报告顶部 KPI 速览条(四类标的通用)。"""
results = results or {} # results 可能为 None(上游未产出)
items = []
# 最新价/净值:优先 runner 显式字段(未复权),退化到图表序列
for key in ("trend", "nav"):
r = results.get(key)
if not (r and r.is_ok() and r.data):
continue
d = r.data
v = None
for fld in ("latest_close_unadj", "latest_close", "latest_nav"):
if d.get(fld) is not None:
v = d[fld]
break
if v is None:
c = d.get("chart") or {}
if c.get("series"):
dd = c["series"][0].get("data") or []
if dd and dd[-1] is not None:
v = dd[-1]
elif c.get("ohlc"): # candlestick 规格
o = c["ohlc"][-1]
v = o[1] if isinstance(o, (list, tuple)) and len(o) > 1 else o
if v is not None:
# 口径可能是 np.nan 或 'N/A' 这类字符串:_num_text 统一兜底,不再 float() 崩
items.append(("最新价", _num_text(v)))
break
# 区间涨幅 + 波动率
for r in results.values():
if not (r and r.is_ok() and r.data):
continue
d = r.data
if isinstance(d.get("returns"), dict) and "近20日涨幅%" in d["returns"]:
rets = d["returns"]
# 缺键/非数值一律走占位文案,不再拼出 "N/A%"
items.append(("近20日", _num_text(rets.get("近20日涨幅%"), suffix="%")))
items.append(("近250日", _num_text(rets.get("近250日涨幅%"), suffix="%")))
vol = d.get("volatility")
if vol is not None:
items.append(("年化波动", _num_text(vol, suffix="%")))
break
# 估值分位
val = results.get("valuation")
if val and val.is_ok() and val.data:
pe = val.data.get("pe_hist_percentile")
if pe is not None:
items.append(("PE 5年分位", _num_text(pe, digits=1, suffix="%")))
return items
def _kpi_html(items):
if not items:
return ""
def _kpi_cls(k, v):
s = str(v)
# 仅对区间涨跌幅着色(红涨绿跌);波动/分位等无方向语义的不着色
if not ("日" in k or "涨幅" in k) or not s.endswith("%"):
return ""
return " down" if s.startswith("-") else " up"
cards = "".join(
f'<div class="kpi"><div class="kpi-label">{_html.escape(k)}</div><div class="kpi-value{_kpi_cls(k, v)}">{_html.escape(str(v))}</div></div>'
for k, v in items
)
return f'<div class="kpi-bar">{cards}</div>'
def _split_sections(md: str):
"""按 h1/h2 切分 markdown:h1 行与其后的非章节行(如数据日期)归入 head,返回 (head, [(h2标题行, 正文行列表)])。"""
head = []
sections = []
cur_heading = None
cur = []
for line in md.splitlines():
if line.startswith("# "):
head.append(line)
elif line.startswith("## "):
if cur_heading is not None:
sections.append((cur_heading, cur))
cur = []
cur_heading = line
else:
if cur_heading is None:
head.append(line)
else:
cur.append(line)
if cur_heading is not None:
sections.append((cur_heading, cur))
return "\n".join(head), sections
_CHART_PH = re.compile(r"^<!--\s*chart:\s*(.+?)\s*-->$")
def _norm_dim(name) -> str:
"""维度标识归一化:去掉章节编号与全部空白,用于「维度标题 ↔ 章节标题 ↔ 占位符名」互配。
占位符里写「股东 筹码」「5. 股东筹码」而维度标题是「股东筹码」时,
严格相等会判为不匹配,图表被挪走——归一化后仍能对上。
"""
s = re.sub(r"^\d+\s*[.、)]\s*", "", str(name or "").strip())
return re.sub(r"\s+", "", s)
def render_html_report(md_text: str, results) -> str:
"""markdown 报告 + 图表数据 → 完整 HTML 页面字符串。
图表按维度标题分发到对应 `## N. 标题` 章节内;正文可用 `<!--chart:维度名-->`
指定图表的插入位置(用于让图与相关小节相邻,如饼图紧跟前十大股东表);
未使用占位符的维度仍回退到章节开头,匹配不上的回退到附录。
维度名按 `_norm_dim` 归一化后比较,占位符名对不上时该章节图表回退到章节开头、
其余回退到附录,并在原位置留 HTML 注释——保证图表不因命名不一致而丢失。
"""
head_md, sections = _split_sections(md_text)
# 图表按维度归一化标题归类,all_opts 保留全局编号(供 id/JS 映射)
by_title = {}
all_opts = []
for title, opt in _chart_options(results):
all_opts.append(opt)
by_title.setdefault(_norm_dim(title), []).append(len(all_opts) - 1)
def _chart_divs(section_title):
return "".join(
f'<div id="chart-{i}" class="chart"></div>'
for i in by_title.pop(_norm_dim(section_title), []))
parts = [md_to_html(head_md)] if head_md else []
try:
kpi = _kpi_html(_kpi_items(results))
except Exception:
kpi = "" # KPI 条是装饰性内容,任何意外都不该让整页渲染失败
if kpi:
parts.append(kpi)
toc = []
for h2_md, body in sections:
heading = h2_md[3:] # 去掉 '## '
m = re.match(r"^(\d+)\.\s*(.*)$", heading)
if m:
head_html = f'<span class="num">{m.group(1)}</span>{_inline(m.group(2))}'
toc.append((m.group(1), _inline(m.group(2))))
parts.append(f"<h2 id='sec-{m.group(1)}'>{head_html}</h2>")
else:
head_html = _inline(heading)
parts.append(f"<h2>{head_html}</h2>")
# 章节开头连续引用块(维度含义)先于图表渲染,保持 含义→图→正文 顺序
lead, k = [], 0
while k < len(body) and body[k].strip().startswith("> "):
lead.append(body[k])
k += 1
if lead:
parts.append(md_to_html("\n".join(lead)))
# 正文占位符 `<!--chart:维度名-->`:就地插入该维度图表
body = body[k:]
placeholders = [i for i, ln in enumerate(body) if _CHART_PH.match(ln.strip())]
if placeholders:
chunks, prev = [], 0
for i in placeholders:
chunks.append(body[prev:i])
chunks.append(["__CHART__:" + _CHART_PH.match(body[i].strip()).group(1)])
prev = i + 1
chunks.append(body[prev:])
body = [ln for c in chunks for ln in c]
out, used = [], set()
for ln in body:
if ln.startswith("__CHART__:"):
want = ln.split(":", 1)[1]
wkey = _norm_dim(want)
idxs = by_title.pop(wkey, [])
if idxs:
out.append("__RAW__" + "".join(
f'<div id="chart-{i}" class="chart"></div>' for i in idxs))
else:
# 同一维度被多次引用(used 已有)或占位符名对不上:这里没有图可放,
# 但不能静默——留 HTML 注释便于排查;该图仍会在下方
# 章节开头(_chart_divs)或文末附录出现,不会丢失
tag = "duplicate" if wkey in used else "unmatched"
out.append(f"__RAW__<!-- chart-placeholder-{tag}: "
+ want.replace("--", "-") + " -->")
used.add(wkey)
else:
out.append(ln)
# 逐段渲染,__RAW__ 段原样输出
seg, buf = [], []
for ln in out:
if ln.startswith("__RAW__"):
if any(x.strip() for x in buf):
seg.append(md_to_html("\n".join(buf)))
buf = []
seg.append(ln[len("__RAW__"):])
else:
buf.append(ln)
if any(x.strip() for x in buf):
seg.append(md_to_html("\n".join(buf)))
# 本章节维度的图表若没被任何占位符消费(含占位符名写错的情况),
# 回退到章节开头,与「无占位符」路径保持一致,避免只剩附录兜底
parts.append(_chart_divs(heading))
parts.extend(seg)
else:
parts.append(_chart_divs(heading))
rest = body
if any(line.strip() for line in rest):
parts.append(md_to_html("\n".join(rest)))
# 未匹配到章节的图表回退到附录
leftover = [i for idxs in by_title.values() for i in idxs]
if leftover:
parts.append("<h2>附录:可视化图表</h2>" + "".join(
f'<div id="chart-{i}" class="chart"></div>' for i in leftover))
body_html = "\n".join(parts)
# 图表数据内联进 <script>:必须走 _json_script(转义 < 并兜底非 JSON 类型),
# 直接 json.dumps 会因标题里的 "</script>" 提前闭合脚本、或因 np.int64 抛 TypeError
chart_js = _json_script(
{f"chart-{i}": all_opts[i] for i in range(len(all_opts))}
)
toc_html = ""
if toc:
toc_html = "<nav class='toc'><div class='toc-title'>目录</div>" + "".join(
f"<a href='#sec-{n}'><span class='n'>{n}</span>{t}</a>" for n, t in toc) + "</nav>"
return (
"<!DOCTYPE html><html lang='zh-CN'><head><meta charset='utf-8'>"
f"<title>{_page_title(md_text)}</title>"
f"<script src='{ECHARTS_CDN}'></script>"
f"<style>{_CSS}</style></head><body>"
+ "<div class='layout'>" + toc_html + "<main class='content'>"
+ body_html
+ f"<div class='footer'>报告生成于 {datetime.now():%Y-%m-%d %H:%M} · 数据来自山西证券 Tushare(T-1)</div>"
+ "</main></div>"
+ f"<script>const CHARTS = {chart_js};{_INIT_JS}</script>"
+ "</body></html>"
)
if __name__ == "__main__":
# 自检:md 转换 + 图表注入的最小可用样例
md = (
"# 测试标的 全景研究报告\n\n"
"> 数据日期:20260904(Tushare 数据为 T-1 日)\n\n"
"## 1. 行情趋势\n"
"近20日涨幅 **5.2%**,年化波动 `12.3%`。\n\n"
"| 指标 | 数值 |\n|---|---|\n| 近20日涨幅 | 5.2% |\n| 年化波动 | 12.3% |\n\n"
"| 口径 | 数值 |\n|---|---|\n| 近20日主力净流入(亿) | -21.47 |\n| 北向近20日净流入(百万) | N/A |\n\n"
"| 指标 | 数值 |\n|---|---|\n| 融资余额(亿) | 173.19 |\n| 近5日融资余额变化% | 0.48 |\n| 两融标的 | 是 |\n\n"
"| 项目 | 内容 |\n|---|---|\n| 股票简称 | 测试标的 |\n| 员工数 | 34,992 |\n| 注册资本 | 12.50亿 |\n\n"
"| 除权除息日 | 每股分红(税前,元) |\n|---|---|\n| 20240619 | 30.88 |\n| 20241220 | 23.88 |\n\n"
"| 区间 | 标的 | 000300.SH |\n|---|---|---|\n| 近20日涨幅% | 5.2% | -6.05 |\n| 年化波动率% | 12.3% | 13.15 |\n\n"
"- 风险信号 1\n- 风险信号 2\n\n"
"---\n"
"*本报告由AI自动生成*"
)
from result_model import DimensionResult
fake = DimensionResult.success(
"行情趋势",
data={
"chart": {
"title": "日线行情(样例)",
"type": "candlestick",
"dates": ["20260901", "20260902", "20260903"],
"ohlc": [[10, 10.5, 9.8, 10.6], [10.5, 10.2, 10.0, 10.8], [10.2, 10.9, 10.1, 11.0]],
"vol": [100, 120, 130],
}
},
)
page = render_html_report(md, {"trend": fake})
assert "<h1>测试标的 全景研究报告</h1>" in page
assert "<table class='col-2'>" in page and "5.2%" in page
# 无中文的数值列(资金面表:数值 + N/A):整列右对齐,缺失值不破坏判定
_mf = page[page.index("-21.47") - 200:]
assert "<td class='r'>-21.47</td>" in _mf
assert "<td class='r'>N/A</td>" in _mf
# 含中文的混合列(两融表:数值 + 「是」):整列统一左对齐,不得逐单元格切换
_mg = page[page.index("173.19") - 200:]
assert "<td>173.19</td>" in _mg and "<td class='r'>173.19</td>" not in _mg
assert "<td>是</td>" in _mg and "<td class='r'>是</td>" not in _mg
# 日期列(除权除息日 20240619)形似数字但属文本,须左对齐
assert "<td>20240619</td>" in page and "<td class='r'>20240619</td>" not in page
assert "<td class='r'>30.88</td>" in page
# 文本列(概况表):形如数字的值也不得单独右对齐
_i = page.index("<td>34,992</td>") if "<td>34,992</td>" in page else -1
assert _i > 0, "概况表文本列应整体左对齐,员工数不得右对齐"
assert "<td class='r'>34,992</td>" not in page
assert "<td class='r'>12.50亿</td>" not in page
assert "<ul><li>风险信号 1</li>" in page
assert "<blockquote>数据日期" in page
assert "echarts@5/dist/echarts.min.js" in page
assert '"type": "candlestick"' in page
assert "<div class='table-wrap'>" in page
assert "<td class='r'>5.2%</td>" in page # 数值列右对齐
assert '<span class="num">1</span>行情趋势' in page
assert "报告生成于" in page
assert page.index('<div id="chart-0"') > page.index('<span class="num">1</span>行情趋势')
# 占位符 `<!--chart:维度名-->`:图表就地插入到该小节,而非章节开头
md_ph = (
"# 占位符测试\n\n## 1. 股东筹码\n"
"**前十大股东**:合计持股 67.62%\n\n<!--chart:股东筹码-->\n\n"
"| 股东名称 | 持股比例% |\n|---|---|\n| 甲公司 | 54.50 |\n\n"
"**股东户数**:296,404\n"
)
fake_ph = DimensionResult.success(
"股东筹码",
data={"chart": {"title": "持股分布", "type": "pie",
"data": [{"name": "甲公司", "value": 54.5}]}},
)
page_ph = render_html_report(md_ph, {"shareholder": fake_ph})
_head = page_ph.index("**前十大股东**") if "**前十大股东**" in page_ph else page_ph.index("前十大股东")
_chart = page_ph.index('<div id="chart-0"')
_holders = page_ph.index("296,404")
assert _head < _chart < _holders, "占位符图表应紧随前十大股东、且在股东户数之前"
assert "<!--chart:" not in page_ph # 占位符本身不应出现在输出中
assert "附录" not in page_ph # 已被占位符消费,不应重复落到附录
with open("_selfcheck_report.html", "w", encoding="utf-8") as f:
f.write(page)
print("self-check OK -> _selfcheck_report.html")
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness. | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |