From d14f06a17108c6a2db663efd80dc2c46f5840e88 Mon Sep 17 00:00:00 2001 From: PureSaber <88314620+PureSaber@users.noreply.github.com> Date: Tue, 6 Oct 2026 12:12:45 +0800 Subject: [PATCH 1/4] Improve ledger previews and low-frequency runtime compatibility --- .github/workflows/upstream-integration.yml | 4 +- README.md | 4 + src/quant_studio/desk.py | 40 ++------ src/quant_studio/server.py | 72 +++++++++++++-- src/quant_studio/table_view.py | 82 +++++++++++++++++ tests/test_desk_display.py | 102 +++++++++++++++++++++ 6 files changed, 259 insertions(+), 45 deletions(-) create mode 100644 src/quant_studio/table_view.py create mode 100644 tests/test_desk_display.py diff --git a/.github/workflows/upstream-integration.yml b/.github/workflows/upstream-integration.yml index 1f6cf5a..2f0d5eb 100644 --- a/.github/workflows/upstream-integration.yml +++ b/.github/workflows/upstream-integration.yml @@ -16,10 +16,10 @@ jobs: 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-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: cbdfb5e353bf9ab372499d5ddca3e50bb03270d0, 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..ff3e6e7 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,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/src/quant_studio/desk.py b/src/quant_studio/desk.py index 85a809b..f05c1f2 100644 --- a/src/quant_studio/desk.py +++ b/src/quant_studio/desk.py @@ -3,13 +3,13 @@ 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.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"), @@ -119,42 +119,16 @@ def list_runs(runs_root: Path) -> list[dict[str, str]]: "has_nav": "1" if (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/server.py b/src/quant_studio/server.py index bba35b3..223af59 100644 --- a/src/quant_studio/server.py +++ b/src/quant_studio/server.py @@ -19,7 +19,6 @@ from quant_studio.desk import ( FETCH_BY_REPO, FETCH_COMMANDS, - html_table, list_runs, scan_datasets, workspace_root, @@ -37,6 +36,7 @@ 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 +148,9 @@ def render_overview(runs_root: Path) -> str:

需要处理

最近研究

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

前向账户

{account_links or '

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

'}

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

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

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

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

- + {rows or ""} -
模板状态时间净值
模板状态文件更新净值
还没有带净值或报告的结果
""" +{_FILE_TIME_NOTE}""" return _layout("结果", body, "results") @@ -1346,7 +1346,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 +1386,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 +1503,11 @@ def _layout(title: str, body: str, active: str = "strategy") -> str: """ +_FILE_TIME_NOTE = ( + '

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

" +) + _CSS = """ :root { --ink: #101828; @@ -1579,6 +1625,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; 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/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