Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .github/workflows/upstream-integration.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
# quant-studio

基金与模拟盘的新运行在命令结束后调用原生只读账本核验。通过时结果页显示
“账本重放校验通过”与原始明细;核验失败时保留产物和错误,显示诊断页,不展示成功净值。
旧运行没有新核验记录时保持原有证据,不追认为本次核验通过。

新运行在执行前原子写入未完成状态,结果JSON通过同目录临时文件、刷盘和原子替换更新。
执行/预检中断,以及旧结果缺失、JSON损坏时,记录仍能在列表与诊断页查看。
未完成状态也可能表示进程仍在运行;确认原进程结束后,可按保存参数创建新记录重新预检。
这不会续写旧记录或重置旧账本;账户恢复使用模拟盘原生`verify/status/backup/restore`命令。


quant-studio 是只在本机回环地址运行的量化研究模板台。它让用户修改少量已声明参数,先检查生成的配置与参数列表,再选择是否运行上游工具。它不实现因子、撮合、账本或通用绘图,也不会自动安装外部研究仓库。

外部模板只会在设置 `QUANT_WORKSPACE_ROOT` 且对应上游仓库目录存在时执行。合成样例使用仓库内固定收益率,仅用于验证操作流程;合成样例不是市场收益。所有内容均为研究用途,不构成投资建议。
Expand Down Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions integration/test_asset_upstream.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
2 changes: 2 additions & 0 deletions integration/test_upstream.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
65 changes: 24 additions & 41 deletions src/quant_studio/desk.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down Expand Up @@ -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'<th title="{escape(cell)}">{escape(labels.get(cell, cell))}</th>'
for cell in rows[0]
)
body = []
for row in rows[1:]:
cells = "".join(f"<td>{escape(cell)}</td>" for cell in row)
body.append(f"<tr>{cells}</tr>")
return (
f'<section class="panel"><h2>{escape(title)}</h2>'
'<div class="table-scroll" tabindex="0">'
f"<table><tr>{head}</tr>{''.join(body)}</table></div></section>"
datetime.fromtimestamp(stamp, UTC)
.astimezone()
.isoformat(sep=" ", timespec="seconds")
)
22 changes: 22 additions & 0 deletions src/quant_studio/run_record.py
Original file line number Diff line number Diff line change
@@ -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}
89 changes: 85 additions & 4 deletions src/quant_studio/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import shutil
import subprocess
import sys
import tempfile
import uuid
from dataclasses import asdict, dataclass
from pathlib import Path
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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}:
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand Down
Loading