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'"
+ 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:
需要处理
{blockers or "- 环境检查通过;请继续核验数据和研究条件。
"}
最近研究
-| 模板 | 状态 | 时间 | 净值 |
+| 模板 | 状态 | 文件更新 | 净值 |
{_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}
+请先确认原进程已结束。保留当前记录与账本;已有账户先核验并恢复投影,
+不要用初始化覆盖账户。部分产物不能作为完整结果。
+
+新记录重新读取输入;本次配置、结果与账本继续保留。
+配置与执行命令
+{_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: