diff --git a/.github/workflows/upstream-integration.yml b/.github/workflows/upstream-integration.yml index 1f6cf5a..1df2909 100644 --- a/.github/workflows/upstream-integration.yml +++ b/.github/workflows/upstream-integration.yml @@ -15,11 +15,11 @@ jobs: matrix: os: [ubuntu-24.04, windows-latest] upstream: - - {repo: quant-paper-sim, ref: 0ff46a10f21c5df64a6cd77b7e941a506240dffe, test: paper} - - {repo: quant-hk-equity, ref: 37a9314e63038b8a89afcbbec2f5936953c0c62b, test: hk} + - {repo: quant-paper-sim, ref: 55cfa0f8f12cc5419dfad664a644c5c29233ab23, test: paper} + - {repo: quant-hk-equity, ref: 18cfe93a757e93e0c89875ceff9612350f989359, test: hk} - {repo: a-share-multifactor, ref: 3c48cd28d056b6dad36fbc0041408c010912a20d, test: ashare} - {repo: quant-pipeline, ref: b1fce90b85651248e9e60ae857b88fe4d170319e, test: account} - - {repo: quant-fund, ref: c7be45bdce66aee49762430ba93d2fc361e3c4b5, test: fund} + - {repo: quant-fund, ref: ad7cffe867ae319ab546acb06f0aa32ded9e6542, test: fund} - {repo: quant-futures-spread, ref: f01d6afd87ca0556d6e2f44e522cfecbf00cad56, test: futures} - {repo: quant-crypto-basis, ref: 02acfeb6227d8f61243b908846592af4e5b70365, test: crypto} steps: diff --git a/README.md b/README.md index e6e6fe1..1a081fe 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,15 @@ # quant-studio +基金与模拟盘的新运行在命令结束后调用原生只读账本核验。通过时结果页显示 +“账本重放校验通过”与原始明细;核验失败时保留产物和错误,显示诊断页,不展示成功净值。 +旧运行没有新核验记录时保持原有证据,不追认为本次核验通过。 + +新运行在执行前原子写入未完成状态,结果JSON通过同目录临时文件、刷盘和原子替换更新。 +执行/预检中断,以及旧结果缺失、JSON损坏时,记录仍能在列表与诊断页查看。 +未完成状态也可能表示进程仍在运行;确认原进程结束后,可按保存参数创建新记录重新预检。 +这不会续写旧记录或重置旧账本;账户恢复使用模拟盘原生`verify/status/backup/restore`命令。 + + quant-studio 是只在本机回环地址运行的量化研究模板台。它让用户修改少量已声明参数,先检查生成的配置与参数列表,再选择是否运行上游工具。它不实现因子、撮合、账本或通用绘图,也不会自动安装外部研究仓库。 外部模板只会在设置 `QUANT_WORKSPACE_ROOT` 且对应上游仓库目录存在时执行。合成样例使用仓库内固定收益率,仅用于验证操作流程;合成样例不是市场收益。所有内容均为研究用途,不构成投资建议。 @@ -43,6 +53,10 @@ python -m venv .venv A股、港股和模拟盘模板均提供独立“数据预检”,分别调用所选环境的`a_share_multifactor.preflight`、`quant-hk preflight`和`quant-paper preflight`,校验同一配置及已有输入,不执行策略。预检记录保存配置、命令、原始输出与上游证据;通过后可“使用相同参数运行”,保留参数、因子和快照选择。实际运行仍重新校验输入,预检不是数据锁定或投资适用性认证。 +结果表格使用中文列名、数值右对齐和交替底色。金额与数量显示千位分隔并省略小数尾零,保留所有非零小数;权重长小数以`…`缩写,极小非零权重仍保留首个有效数字。悬停可查看原值,完整CSV下载保持原始字节和精度。证券代码、订单ID、日期及事件时间不按数值格式化。每张表说明展示行数,更多记录通过完整CSV查看。 + +总览、回测及结果列表的“文件更新”是运行结果文件的修改时间,包含服务所在机器本地时区的UTC偏移,不代表行情截止、成交或账户观察时刻。排序保留文件时间的小数秒,避免同一秒内较新的记录被排到旧记录后面;事件时间及账本计算继续由上游契约决定。 + A股只读加载缓存、检查历史时点、因子可计算性及全收益基准,不下载缺失数据或创建快照。模拟盘检查信号、证券身份、费用及保存状态前置条件,不回放成交或改写账户;Studio仍为每次运行使用独立状态。所选上游环境需要支持对应预检命令,旧版本不支持时保留失败日志,不回退到完整回测或可写的status命令。 ```powershell diff --git a/integration/test_asset_upstream.py b/integration/test_asset_upstream.py index 5938da6..0372f8e 100644 --- a/integration/test_asset_upstream.py +++ b/integration/test_asset_upstream.py @@ -86,6 +86,13 @@ def test_native_asset_cli(name, tmp_path, monkeypatch): ) assert result.status == "succeeded", diagnostics(result) assert result.evidence_kind == "synthetic" + if fund: + assert result.verification_status == "pass" + evidence = json.loads( + (result.run_dir / "verification.json").read_text(encoding="utf-8") + ) + assert evidence["verified_ledger_days"] > 60 + assert "账本重放校验通过" in render_run(result.run_dir) assert fingerprint(source) == before assert (checked.run_dir / "config.json").read_bytes() == ( result.run_dir / "config.json" diff --git a/integration/test_upstream.py b/integration/test_upstream.py index 4ac955f..058ff6f 100644 --- a/integration/test_upstream.py +++ b/integration/test_upstream.py @@ -50,6 +50,8 @@ def test_paper_cli(tmp_path, monkeypatch): result = run("paper-sim", execute=True, runs_root=tmp_path, timeout=90) assert result.status == "succeeded", diagnostics(result) assert result.returncode == 0 + assert result.verification_status == "pass" + assert "账本重放校验通过" in render_run(result.run_dir) nav = parse_nav_csv(result.run_dir / "nav.csv") assert len(nav.rows) == 1 and nav.period_return is None assert (result.run_dir / "strategy-output" / "execution_log.json").is_file() diff --git a/src/quant_studio/desk.py b/src/quant_studio/desk.py index 85a809b..4d02e37 100644 --- a/src/quant_studio/desk.py +++ b/src/quant_studio/desk.py @@ -3,13 +3,14 @@ import json import os from dataclasses import dataclass -from datetime import datetime -from html import escape +from datetime import UTC, datetime from pathlib import Path from quant_studio import QuantStudioError +from quant_studio.run_record import load_run_result from quant_studio.runner import safe_run_file from quant_studio.settings import setting +from quant_studio.table_view import html_table as html_table DATA_ROOTS = ( ("A股", "a-share-multifactor", "data"), @@ -93,68 +94,50 @@ def list_runs(runs_root: Path) -> list[dict[str, str]]: records = [] for directory in runs_root.iterdir(): result_path = directory / "result.json" - if not directory.is_dir() or not result_path.is_file(): + request_path = directory / "request.json" + if not directory.is_dir() or not request_path.is_file(): continue try: - result = json.loads(result_path.read_text(encoding="utf-8")) - request = json.loads( - (directory / "request.json").read_text(encoding="utf-8") - ) + request = json.loads(request_path.read_text(encoding="utf-8")) + if not isinstance(request, dict): + continue except (OSError, json.JSONDecodeError): continue + result = load_run_result(directory) + results_available = ( + result["status"] == "succeeded" + and result.get("verification_status") != "failed" + ) report_name = str(result.get("report") or "") try: has_report = ( - bool(report_name) + results_available + and bool(report_name) and safe_run_file(directory, report_name, {".html"}).is_file() ) except QuantStudioError: has_report = False - stamp = result_path.stat().st_mtime + stamp = (result_path if result_path.is_file() else request_path).stat().st_mtime records.append( { "run_id": directory.name, "template_id": str(request.get("template_id", "")), "status": str(result.get("status", "")), - "has_nav": "1" if (directory / "nav.csv").is_file() else "0", + "has_nav": "1" + if results_available and (directory / "nav.csv").is_file() + else "0", "has_report": "1" if has_report else "0", "when": _format_time(stamp), - "mtime": str(int(stamp)), + "mtime": str(stamp), } ) - records.sort(key=lambda item: item["mtime"], reverse=True) + records.sort(key=lambda item: float(item["mtime"]), reverse=True) return records[:40] def _format_time(stamp: float) -> str: - return datetime.fromtimestamp(stamp).strftime("%Y-%m-%d %H:%M") - - -def html_table( - path: Path, title: str, limit: int = 12, *, column_labels: dict | None = None -) -> str: - import csv - - with path.open(newline="", encoding="utf-8") as stream: - reader = csv.reader(stream) - rows = [] - for index, row in enumerate(reader): - if index > limit: - break - rows.append(row) - if not rows: - return "" - labels = column_labels or {} - head = "".join( - f'{escape(labels.get(cell, cell))}' - for cell in rows[0] - ) - body = [] - for row in rows[1:]: - cells = "".join(f"{escape(cell)}" for cell in row) - body.append(f"{cells}") return ( - f'

{escape(title)}

' - '
' - f"{head}{''.join(body)}
" + datetime.fromtimestamp(stamp, UTC) + .astimezone() + .isoformat(sep=" ", timespec="seconds") ) diff --git a/src/quant_studio/run_record.py b/src/quant_studio/run_record.py new file mode 100644 index 0000000..6fb49c8 --- /dev/null +++ b/src/quant_studio/run_record.py @@ -0,0 +1,22 @@ +"""Inspect completion records without repairing or executing historical runs.""" + +import json +from pathlib import Path + + +def load_run_result(directory: Path) -> dict: + try: + result = json.loads((directory / "result.json").read_text(encoding="utf-8")) + if ( + isinstance(result, dict) + and isinstance(result.get("status"), str) + and result["status"] + and isinstance(result.get("argv", []), list) + ): + return result + detail = "结果记录的结构无效" + except FileNotFoundError: + detail = "尚未写入结果记录" + except (OSError, ValueError) as exc: + detail = f"无法读取完整结果记录:{exc}" + return {"status": "incomplete", "argv": [], "message": detail} diff --git a/src/quant_studio/runner.py b/src/quant_studio/runner.py index 01c5349..43412b2 100644 --- a/src/quant_studio/runner.py +++ b/src/quant_studio/runner.py @@ -7,6 +7,7 @@ import shutil import subprocess import sys +import tempfile import uuid from dataclasses import asdict, dataclass from pathlib import Path @@ -122,6 +123,8 @@ class RunResult: message: str | None = None evidence_kind: str | None = None research_view_sha256: str | None = None + verification_status: str = "not_requested" + verification_sha256: str | None = None def as_json(self) -> dict[str, Any]: data = asdict(self) @@ -222,6 +225,10 @@ def run( ) _write_json(run_dir / "command.json", {"argv": argv}) + _write_json( + run_dir / "result.json", + RunResult("running", identifier, run_dir, argv).as_json(), + ) if loaded.kind == "synthetic": from quant_studio.synthetic import execute_synthetic @@ -289,6 +296,30 @@ def run( research_view_sha256 = None report_name = loaded.report_name family_report_verified = False + verification_status = "not_requested" + verification_sha256 = None + if succeeded and loaded.metadata.get("verification_argv"): + try: + verification_sha256 = _verify_account_output( + loaded, + rendered.values, + run_dir, + config_path, + selected_snapshot, + cwd, + timeout, + ) + verification_status = "pass" + except ( + OSError, + ValueError, + TypeError, + QuantStudioError, + subprocess.SubprocessError, + ) as exc: + succeeded = False + verification_status = "failed" + message = f"账本核验未通过:{exc}" if loaded.metadata.get("counterfactual_view"): try: if returncode not in {0, 2}: @@ -376,11 +407,53 @@ def run( message, evidence_kind, research_view_sha256, + verification_status, + verification_sha256, ) _write_json(run_dir / "result.json", result.as_json()) return result +def _verify_account_output( + template, values, run_dir, config_path, snapshot, cwd, timeout +): + argv = _render_argv( + template.metadata["verification_argv"], + values, + run_dir, + config_path, + snapshot, + python=configured_python(template.workspace_repo), + ) + _write_json(run_dir / "verification-command.json", {"argv": argv}) + completed = subprocess.run( + argv, + cwd=cwd, + shell=False, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + env=subprocess_environment(), + timeout=timeout, + check=False, + ) + (run_dir / "verification-stdout.txt").write_text(completed.stdout, encoding="utf-8") + (run_dir / "verification-stderr.txt").write_text(completed.stderr, encoding="utf-8") + if completed.returncode: + raise QuantStudioError(completed.stderr.strip()[-1600:] or "上游账本核验失败") + evidence = json.loads(completed.stdout) + contract = template.metadata["verification_contract"] + if not isinstance(evidence, dict) or any( + type(evidence.get(key)) is not type(expected) or evidence.get(key) != expected + for key, expected in contract.items() + ): + raise QuantStudioError("上游未返回完整的账本重放通过证据") + path = run_dir / "verification.json" + _write_json(path, evidence) + return hashlib.sha256(path.read_bytes()).hexdigest() + + def preflight( template: str | Template, knobs: dict[str, Any] | None = None, @@ -415,6 +488,8 @@ def preflight( if argv[0] != ready.executable: raise QuantStudioError("运行环境配置在预检期间改变,请重新预览") cwd = Path(setting("QUANT_WORKSPACE_ROOT")).resolve() / loaded.workspace_repo + result.status = "checking" + _write_json(prepared.run_dir / "result.json", result.as_json()) try: completed = subprocess.run( argv, @@ -725,10 +800,16 @@ def _write_config(path: Path, config_format: str, config: dict[str, Any]) -> Non def _write_json(path: Path, value: Any) -> None: - path.write_text( - json.dumps(value, ensure_ascii=False, indent=2) + "\n", - encoding="utf-8", - ) + data = (json.dumps(value, ensure_ascii=False, indent=2) + "\n").encode("utf-8") + descriptor, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) + try: + with os.fdopen(descriptor, "wb") as handle: + handle.write(data) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, path) + finally: + Path(temporary).unlink(missing_ok=True) def _text(value: str | bytes | None) -> str: diff --git a/src/quant_studio/server.py b/src/quant_studio/server.py index bba35b3..eee3bed 100644 --- a/src/quant_studio/server.py +++ b/src/quant_studio/server.py @@ -1,5 +1,6 @@ from __future__ import annotations +import hashlib import json import math import secrets @@ -19,7 +20,6 @@ from quant_studio.desk import ( FETCH_BY_REPO, FETCH_COMMANDS, - html_table, list_runs, scan_datasets, workspace_root, @@ -33,10 +33,12 @@ validate_comparison, ) from quant_studio.research_panel import load_timing_view, timing_panel +from quant_studio.run_record import load_run_result from quant_studio.runner import preflight, run, safe_run_file, template_readiness from quant_studio.settings import setting, use_settings from quant_studio.setup import SettingsStore, profile_from_form from quant_studio.setup_view import setup_body +from quant_studio.table_view import html_table from quant_studio.templates import load_template, template_ids @@ -148,9 +150,9 @@ def render_overview(runs_root: Path) -> str:

需要处理

最近研究

- + {_run_rows(records[:6], "/runs/") or ''} -
模板状态时间净值
模板状态文件更新净值
还没有研究记录
+{_FILE_TIME_NOTE}

前向账户

{account_links or '

尚未连接账户。查看连接方法

'}

这里只读取明确配置的账户,不登记、观察或封存账户。

""" @@ -332,9 +334,9 @@ def render_backtest(runs_root: Path) -> str:

从策略页提交。打开一条记录可看命令;失败时能看到输出。

- + {rows or ""} -
模板状态时间净值
模板状态文件更新净值
还没有运行
""" +{_FILE_TIME_NOTE}""" return _layout("回测", body, "backtest") @@ -352,9 +354,9 @@ def render_results(runs_root: Path) -> str: 打开后可看曲线、回撤和持仓成交表。

- + {rows or ""} -
模板状态时间净值
模板状态文件更新净值
还没有带净值或报告的结果
""" +{_FILE_TIME_NOTE}""" return _layout("结果", body, "results") @@ -435,9 +437,28 @@ def render_template_page( def render_run(run_dir: str | Path, *, csrf_token: str = "") -> str: directory = Path(run_dir) - result = json.loads((directory / "result.json").read_text(encoding="utf-8")) + result = load_run_result(directory) request = json.loads((directory / "request.json").read_text(encoding="utf-8")) template = load_template(request["template_id"]) + if result.get("verification_status") == "failed": + result = {**result, "status": "verification_failed"} + if result["status"] in {"running", "checking", "incomplete", "verification_failed"}: + return _render_unfinished_run(directory, request, result, template, csrf_token) + verified_evidence = None + if result.get("verification_status") == "pass": + try: + content = (directory / "verification.json").read_bytes() + if hashlib.sha256(content).hexdigest() != result.get("verification_sha256"): + raise QuantStudioError("账本核验记录已改变") + verified_evidence = json.loads(content) + except (OSError, ValueError, QuantStudioError) as exc: + return _render_unfinished_run( + directory, + request, + {**result, "status": "verification_failed", "message": str(exc)}, + template, + csrf_token, + ) family_view = ( load_counterfactual_view(directory, result) if template.metadata.get("counterfactual_view") @@ -448,9 +469,9 @@ def render_run(run_dir: str | Path, *, csrf_token: str = "") -> str: if template.metadata.get("timing_view") else None ) - argv = " ".join(escape(str(item)) for item in result["argv"]) + argv = " ".join(escape(str(item)) for item in result.get("argv", [])) report_html = "" - if result.get("report") and not family_view: + if result["status"] == "succeeded" and result.get("report") and not family_view: report_name = result["report"] declared = (template.metadata.get("result_files") or {}).get("report.html") if report_name == "report.html" and declared: @@ -469,9 +490,7 @@ def render_run(run_dir: str | Path, *, csrf_token: str = "") -> str: chart = "" nav_path = directory / "nav.csv" series = None - if nav_path.is_file() and not ( - template.metadata.get("timing_view") and result["status"] != "succeeded" - ): + if result["status"] == "succeeded" and nav_path.is_file(): opening_key = template.metadata.get("nav_initial_value_key") opening = template.metadata.get("nav_initial_value") if opening_key: @@ -492,6 +511,14 @@ def render_run(run_dir: str | Path, *, csrf_token: str = "") -> str: title="策略净值 · 描述性全区间" if timing_view else "净值曲线", ) notices = [] + if verified_evidence is not None: + notices.append( + '

账本重放校验通过

' + "

已从原始账本重新回放并核对保存结果。

" + "
核验明细
"
+            + escape(json.dumps(verified_evidence, ensure_ascii=False, indent=2))
+            + "
" + ) if template.metadata.get("result_notice"): notices.append( f'

{escape(template.metadata["result_notice"])}

' @@ -536,14 +563,14 @@ def render_run(run_dir: str | Path, *, csrf_token: str = "") -> str: table_labels = dict(template.metadata.get("result_column_labels") or {}) if timing_view and timing_view.get("return_attribution"): table_labels.update(slippage="模型基础成本", market_impact="模型冲击成本") - tables = _artifact_tables( - directory, - native=bool(template.metadata.get("standard_view")), - table_titles=template.metadata.get("result_table_titles"), - column_labels=table_labels, - ) - if template.metadata.get("timing_view") and result["status"] != "succeeded": - tables = "" + tables = "" + if result["status"] == "succeeded": + tables = _artifact_tables( + directory, + native=bool(template.metadata.get("standard_view")), + table_titles=template.metadata.get("result_table_titles"), + column_labels=table_labels, + ) benchmark = '

未提供基准净值。

' if chart else "" drawdown = "" if series is not None: @@ -680,6 +707,57 @@ def render_run(run_dir: str | Path, *, csrf_token: str = "") -> str: return _layout("运行结果", body, "results") +def _render_unfinished_run(directory, request, result, template, csrf_token): + has_preflight = bool(template.metadata.get("preflight_argv")) + retry_label = "按相同参数重新预检" if has_preflight else "按相同参数创建新记录" + fields = [ + ("_csrf_token", csrf_token), + ("action", "check" if has_preflight else "execute"), + ] + fields.extend( + (str(key), str(value)) for key, value in request.get("knobs", {}).items() + ) + if request.get("snapshot"): + fields.append(("snapshot", request["snapshot"])) + if request.get("factors") is not None: + fields.append(("factor_form", "1")) + fields.extend(("factor", factor) for factor in request["factors"]) + inputs = "".join( + f'' + for key, value in fields + ) + logs = "".join( + f"

{title}

{escape(path.read_text(encoding='utf-8')[-8000:])}
" + for name, title in ( + ("stdout.txt", "标准输出"), + ("stderr.txt", "错误输出"), + ("verification-stderr.txt", "账本核验错误"), + ) + if (path := directory / name).is_file() + ) + argv = " ".join(escape(str(item)) for item in result.get("argv", [])) + message = escape( + result.get("message") or "进程可能仍在运行,也可能已中断;尚无完成证据。" + ) + label = ( + "账本核验未通过" + if result["status"] == "verification_failed" + else "记录尚未完成" + ) + body = f"""

{escape(template.title)}

+

{label}

+

检查与恢复

+

{message}

+

请先确认原进程已结束。保留当前记录与账本;已有账户先核验并恢复投影, +不要用初始化覆盖账户。部分产物不能作为完整结果。

+
{inputs} +
+

新记录重新读取输入;本次配置、结果与账本继续保留。

+
配置与执行命令 +{_saved_config(directory)}
{argv}
{logs}
""" + return _layout("未完成运行", body, "results") + + def render_environment() -> str: root = setting("QUANT_WORKSPACE_ROOT") or "未设置" rows = [] @@ -1114,6 +1192,9 @@ def _parse_form_knobs( } _STATUS = { + "running": "运行尚未完成", + "checking": "预检尚未完成", + "incomplete": "记录未完成", "checked": "预检通过", "check_failed": "预检未通过", "previewed": "仅预览", @@ -1346,7 +1427,14 @@ def _artifact_tables( "cash_ledger.csv": "现金账本", } labels = { - "event_time": "事件时间(UTC)", + "event_time": "事件时间(UTC)" if native else "事件时间(原时区)", + "date": "日期", + "timestamp": "时间(原时区)", + "strategy": "策略", + "symbol": "标的", + "weight": "持仓权重(比例)", + "target_weight": "目标权重(比例)", + "requested_quantity": "申请数量", "account_id": "账户", "base_currency": "基础币种", "currency": "币种", @@ -1379,13 +1467,47 @@ def _artifact_tables( "ledger_account": "账本科目", "quantity_delta": "数量变动", } - labels = (labels if native else {}) | (column_labels or {}) + labels = labels | (column_labels or {}) + numeric_columns = { + "nav", + "cash_value", + "market_value", + "unrealized_pnl", + "realized_pnl", + "margin_used", + "quantity", + "mark_price", + "price", + "initial_margin", + "maintenance_margin", + "amount", + "limit_price", + "stop_price", + "filled_quantity", + "requested_quantity", + "quantity_delta", + "weight", + "target_weight", + "commission", + "slippage", + "market_impact", + "cash", + "notional", + } parts = [] for name, title in titles.items(): title = (table_titles or {}).get(name, title) path = directory / name if path.is_file(): - parts.append(html_table(path, title, column_labels=labels)) + parts.append( + html_table( + path, + title, + column_labels=labels, + numeric_columns=numeric_columns, + fraction_digits={"weight": 4, "target_weight": 4}, + ) + ) parts.append( f'

' f"下载完整{escape(title)}CSV

" @@ -1462,6 +1584,11 @@ def _layout(title: str, body: str, active: str = "strategy") -> str: """ +_FILE_TIME_NOTE = ( + '

文件更新时间按服务所在机器的本地时区显示,包含UTC偏移;' + "不代表行情截止或策略成交时刻。

" +) + _CSS = """ :root { --ink: #101828; @@ -1579,6 +1706,12 @@ def _layout(title: str, body: str, active: str = "strategy") -> str: table { width: 100%; border-collapse: collapse; } .table-scroll { max-width: 100%; overflow-x: auto; } .table-scroll td, .table-scroll th { padding-right: 16px; white-space: nowrap; } +.table-scroll thead { background: #f8fafc; } +.table-scroll tbody tr:nth-child(even) { background: #f8fafc; } +.table-scroll tbody tr:hover { background: #edf4ff; } +.table-scroll td, .table-scroll th { padding-left: 12px; } +.table-scroll .numeric { text-align: right; font-variant-numeric: tabular-nums; } +.table-scroll:focus-visible { outline: 3px solid #8bb8ff; outline-offset: 2px; } .environment-table { table-layout: fixed; } .environment-table td, .environment-table th { overflow-wrap: anywhere; padding: 12px 16px 12px 0; vertical-align: top; @@ -1762,6 +1895,9 @@ def _layout(title: str, body: str, active: str = "strategy") -> str: font-size: 13px; } .status.failed, .status.blocked { background: #fdecec; color: #b42318; } +.status.incomplete, .status.running, .status.checking { + background: #fff2d5; color: #835300; +} .command { margin-bottom: 16px; } .command h2 { margin: 0 0 10px; font-size: 16px; } pre { diff --git a/src/quant_studio/table_view.py b/src/quant_studio/table_view.py new file mode 100644 index 0000000..4973b3d --- /dev/null +++ b/src/quant_studio/table_view.py @@ -0,0 +1,82 @@ +from __future__ import annotations + +import csv +import re +from collections.abc import Collection, Mapping +from html import escape +from itertools import islice +from pathlib import Path + + +def _numeric_text(raw: str, fraction_digits: int | None = None) -> str: + """Compact an explicit decimal field without rounding or float conversion.""" + if not re.fullmatch(r"[+-]?[0-9]+(?:\.[0-9]+)?", raw): + return raw + whole, _, fraction = raw.partition(".") + whole = re.sub(r"(?<=[0-9])(?=(?:[0-9]{3})+$)", ",", whole) + fraction = fraction.rstrip("0") + if fraction_digits is not None: + # Preserve at least the first nonzero digit of a small ratio. + first_nonzero = len(fraction) - len(fraction.lstrip("0")) + 1 + kept = max(fraction_digits, first_nonzero) + if len(fraction) > kept: + fraction = fraction[:kept] + "…" + return whole + ("." + fraction if fraction else "") + + +def html_table( + path: Path, + title: str, + limit: int = 12, + *, + column_labels: dict | None = None, + numeric_columns: Collection[str] = (), + fraction_digits: Mapping[str, int] | None = None, +) -> str: + if limit < 1: + raise ValueError("表格预览行数必须大于0") + digits = fraction_digits or {} + if any(value < 1 for value in digits.values()): + raise ValueError("小数预览位数必须大于0") + with path.open(newline="", encoding="utf-8") as stream: + reader = csv.reader(stream) + columns = next(reader, None) + if not columns: + return "" + rows = list(islice(reader, limit + 1)) + labels = column_labels or {} + head = "".join( + '{escape(labels.get(name, name))}' + for name in columns + ) + body = [] + for row in rows[:limit]: + cells = [] + for index, cell in enumerate(row): + numeric = index < len(columns) and columns[index] in numeric_columns + cells.append( + f'' + f"{escape(_numeric_text(cell, digits.get(columns[index])))}" + if numeric + else f"{escape(cell)}" + ) + body.append(f"{''.join(cells)}") + note = ( + f"显示前{limit}行,更多记录请下载完整CSV。" + if len(rows) > limit + else f"共{len(rows)}行。" + ) + if any(name in numeric_columns for name in columns): + note += "数值添加千位分隔并省略小数尾零;悬停可看原值,CSV保留原始精度。" + if any(name in digits and name in numeric_columns for name in columns): + note += "权重长小数以…缩写,完整值可悬停查看或下载CSV。" + return ( + f'

{escape(title)}

' + f'

{note}

' + f'
' + f"{head}" + f"{''.join(body)}
" + ) diff --git a/src/quant_studio/templates/fund-fof/template.json b/src/quant_studio/templates/fund-fof/template.json index 9aabba3..ac8d258 100644 --- a/src/quant_studio/templates/fund-fof/template.json +++ b/src/quant_studio/templates/fund-fof/template.json @@ -4,7 +4,7 @@ "summary": "使用已有净值、条款和日历,检查输入后运行申赎账本与组合监控。", "kind": "external", "workspace_repo": "quant-fund", - "upstream_ref": "c7be45bdce66aee49762430ba93d2fc361e3c4b5", + "upstream_ref": "ad7cffe867ae319ab546acb06f0aa32ded9e6542", "base_config": "base.json", "config_format": "json", "requires_snapshot": true, @@ -20,6 +20,8 @@ ], "argv": ["python", "-m", "quant_fund.cli", "run", "--dataset", "{snapshot}", "--config", "{config}", "--out", "{output}"], "preflight_argv": ["python", "-m", "quant_fund.cli", "preflight", "--dataset", "{snapshot}", "--config", "{config}"], + "verification_argv": ["python", "-m", "quant_fund.cli", "verify-run", "{output}"], + "verification_contract": {"ledger_replay": "pass"}, "preflight_summary": "只读校验数据、条款、日历和静态账户前置条件;不配置权重、不回放申赎,不保证各日共同历史或优化可行性。", "output_dirs": ["{output}"], "result_files": {"nav.csv": "nav.csv", "report.html": "report.html", "orders.csv": "orders.csv", "trades.csv": "trades.csv", "holdings.csv": "holdings.csv"}, diff --git a/src/quant_studio/templates/paper-sim/template.json b/src/quant_studio/templates/paper-sim/template.json index cbaf991..444843c 100644 --- a/src/quant_studio/templates/paper-sim/template.json +++ b/src/quant_studio/templates/paper-sim/template.json @@ -4,7 +4,7 @@ "summary": "使用固定信号驱动上游模拟盘单步运行。", "kind": "external", "workspace_repo": "quant-paper-sim", - "upstream_ref": "0ff46a10f21c5df64a6cd77b7e941a506240dffe", + "upstream_ref": "55cfa0f8f12cc5419dfad664a644c5c29233ab23", "base_config": "base.yaml", "config_format": "yaml", "knobs": [ @@ -12,6 +12,8 @@ ], "argv": ["quant-paper", "step", "--config", "{config}"], "preflight_argv": ["quant-paper", "preflight", "--config", "{config}"], + "verification_argv": ["quant-paper", "verify", "--config", "{config}"], + "verification_contract": {"replay_verified": true, "projection_status": "complete"}, "preflight_summary": "检查模拟信号、证券身份、费用及账户前置条件;不回放成交或改写账户。", "output_dirs": ["state"], "input_paths": ["signals.path", "regime.path"], diff --git a/tests/test_account_verification.py b/tests/test_account_verification.py new file mode 100644 index 0000000..763d837 --- /dev/null +++ b/tests/test_account_verification.py @@ -0,0 +1,101 @@ +import json +import subprocess +import sys +from pathlib import Path + +import pytest + +from quant_studio import QuantStudioError +from quant_studio.desk import list_runs +from quant_studio.runner import run +from quant_studio.server import render_run +from quant_studio.templates import load_template + + +@pytest.mark.parametrize( + "mode", ["pass", "nonzero", "invalid_json", "missing", "wrong_type"] +) +def test_native_verification_controls_success_and_chart_visibility( + tmp_path, monkeypatch, mode +): + workspace = tmp_path / "workspace" + (workspace / "quant-paper-sim").mkdir(parents=True) + monkeypatch.setenv("QUANT_WORKSPACE_ROOT", str(workspace)) + template = load_template("paper-sim") + template.metadata["argv"] = [sys.executable, "-c", "strategy", "{config}"] + template.metadata["verification_argv"] = [sys.executable, "-c", "verify"] + calls = [] + + def execute(argv, **kwargs): + calls.append(argv[2]) + if argv[2] == "strategy": + directory = Path(argv[3]).parent + (directory / "nav.csv").write_text( + "date,nav\n2025-01-01,100000\n2025-01-02,100100\n" + ) + return subprocess.CompletedProcess(argv, 0, "completed", "") + assert calls == ["strategy", "verify"] + evidence = {"replay_verified": True, "projection_status": "complete"} + if mode == "nonzero": + return subprocess.CompletedProcess( + argv, 2, "", "cash reconciliation failed" + ) + if mode == "missing": + evidence.pop("replay_verified") + elif mode == "wrong_type": + evidence["replay_verified"] = 1 + stdout = "{unfinished" if mode == "invalid_json" else json.dumps(evidence) + return subprocess.CompletedProcess(argv, 0, stdout, "") + + monkeypatch.setattr("quant_studio.runner.subprocess.run", execute) + result = run(template, execute=True, runs_root=tmp_path / "runs") + page = render_run(result.run_dir) + if mode == "pass": + assert result.status == "succeeded" and result.verification_status == "pass" + assert "账本重放校验通过" in page and "净值曲线" in page + (result.run_dir / "verification.json").write_text("{}") + damaged = render_run(result.run_dir) + assert "账本核验未通过" in damaged and "净值曲线" not in damaged + else: + assert result.status == "failed" and result.verification_status == "failed" + assert "账本核验未通过" in page and "净值曲线" not in page + assert list_runs(tmp_path / "runs")[0]["has_nav"] == "0" + assert (result.run_dir / "nav.csv").is_file() + + +@pytest.mark.parametrize("failure", ["process", "collection"]) +@pytest.mark.parametrize("nav", ["date,nav\n2025-01-01,100000\n", "unfinished CSV"]) +def test_failed_run_keeps_partial_artifacts_without_presenting_results( + tmp_path, monkeypatch, failure, nav +): + workspace = tmp_path / "workspace" + (workspace / "quant-paper-sim").mkdir(parents=True) + monkeypatch.setenv("QUANT_WORKSPACE_ROOT", str(workspace)) + template = load_template("paper-sim") + template.metadata["argv"] = [sys.executable, "-c", "strategy", "{config}"] + template.metadata.pop("verification_argv") + + def execute(argv, **kwargs): + directory = Path(argv[3]).parent + (directory / "nav.csv").write_text(nav, encoding="utf-8") + (directory / "orders.csv").write_text("order_id\npartial-order\n") + return subprocess.CompletedProcess( + argv, 8 if failure == "process" else 0, "", "strategy interrupted" + ) + + def collect(*args, **kwargs): + raise QuantStudioError("incomplete output") + + monkeypatch.setattr("quant_studio.runner.subprocess.run", execute) + monkeypatch.setattr("quant_studio.runner.collect_outputs", collect) + result = run(template, execute=True, runs_root=tmp_path / "runs") + assert result.status == "failed" + before = (result.run_dir / "nav.csv").read_bytes() + page = render_run(result.run_dir) + assert "failed" in page + assert ( + "strategy interrupted" if failure == "process" else "incomplete output" + ) in page + assert "净值曲线" not in page and "partial-order" not in page + assert list_runs(tmp_path / "runs")[0]["has_nav"] == "0" + assert (result.run_dir / "nav.csv").read_bytes() == before diff --git a/tests/test_desk_display.py b/tests/test_desk_display.py new file mode 100644 index 0000000..1ad76c0 --- /dev/null +++ b/tests/test_desk_display.py @@ -0,0 +1,102 @@ +import json +import os +from datetime import datetime +from decimal import localcontext +from pathlib import Path + +from quant_studio.desk import html_table, list_runs, scan_datasets +from quant_studio.server import _artifact_tables, render_backtest + + +def test_recent_runs_keep_subsecond_file_order(tmp_path, monkeypatch): + folders = [] + for name, stamp in (("older", 1791259000.1), ("newer", 1791259000.9)): + folder = tmp_path / name + folder.mkdir() + (folder / "request.json").write_text( + json.dumps({"template_id": "synthetic-demo"}), encoding="utf-8" + ) + result = folder / "result.json" + result.write_text(json.dumps({"status": "preview"}), encoding="utf-8") + os.utime(result, (stamp, stamp)) + folders.append(folder) + original_iterdir = Path.iterdir + monkeypatch.setattr( + Path, + "iterdir", + lambda path: iter(folders) if path == tmp_path else original_iterdir(path), + ) + + records = list_runs(tmp_path) + assert [row["run_id"] for row in records] == ["newer", "older"] + assert float(records[0]["mtime"]) > float(records[1]["mtime"]) + + +def test_file_times_have_an_explicit_offset_and_file_meaning(tmp_path): + data = tmp_path / "quant-hk-equity" / "data" + data.mkdir(parents=True) + (data / "prices.csv").write_text("date,close\n2026-01-01,10\n") + shown = scan_datasets(tmp_path)[0].newest + assert datetime.fromisoformat(shown).utcoffset() is not None + page = render_backtest(tmp_path) + assert "文件更新" in page and "本地时区" in page + assert "行情截止" in page and "成交时刻" in page + + +def test_table_formats_declared_amounts_without_rounding_or_rewriting(tmp_path): + path = tmp_path / "cash_ledger.csv" + original = ( + b"instrument_id,amount,quantity,event_time\n" + b"000001,1234567890123456.1234567800,0.000000001," + b"2026-10-06T09:30:00+08:00\n" + b"00123,-1000.01000000,-0.000000001,2026-10-06T01:30:00Z\n" + ) + path.write_bytes(original) + with localcontext() as context: + context.prec = 2 + page = html_table(path, "现金账本", numeric_columns={"amount", "quantity"}) + assert "1,234,567,890,123,456.12345678" in page + assert "-1,000.01" in page and "-0.000000001" in page + assert "0.000000001" in page and "000001" in page + assert "00123" in page + assert 'title="1234567890123456.1234567800"' in page + assert "2026-10-06T09:30:00+08:00" in page + assert path.read_bytes() == original + + +def test_table_preview_explains_truncation_and_escapes_cells(tmp_path): + path = tmp_path / "orders.csv" + path.write_text("order_id,amount\n