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
76 changes: 76 additions & 0 deletions src/quant_studio/decision_summary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
"""Read evidence status without converting successful runs into research gates."""

import json
from html import escape

from quant_studio import QuantStudioError
from quant_studio.result_integrity import verify_result
from quant_studio.run_record import load_run_result
from quant_studio.runner import safe_run_file

OBJECTIVE_LABELS = {
"meets_objective": "目标点估计满足",
"failed": "目标未满足",
"insufficient_evidence": "目标证据不足",
}


def evidence_summary(directory):
result = load_run_result(directory)
if result.get("status") != "succeeded":
return ["未完成或失败的实验;不计入验收"], []
try:
verify_result(directory, result)
objectives, provisional = [], False
for name in sorted(result["output_hashes"]):
if not name.endswith("/result.json"):
continue
value = json.loads(safe_run_file(directory, name).read_text("utf-8"))
if value.get("schema_version") != "quant.research-result/v1":
continue
provisional |= value.get("evidence_state") == "provisional"
provisional |= value.get("provisional") is True
evaluation = value.get("objective_evaluation") or {}
label = OBJECTIVE_LABELS.get(evaluation.get("status"), "目标未评审")
objectives.append(f"{value.get('candidate', name)}:{label}")
provisional |= result.get("evidence_state") == "provisional"
provisional |= result.get("provisional") is True
label = (
"临时证据(provisional);不计入 A/B/C 验收"
if provisional
else "产物完整性已核验;经济有效性及未来门槛另行评审"
)
return [label], objectives
except (OSError, ValueError, TypeError, AttributeError, QuantStudioError):
return ["证据未核验;不计入验收"], []


def gate_a_summary(account, daily):
if not account:
return "未关联模拟账户"
if not daily or not daily.get("operations"):
return "当前原生运行状态未核实"
native = daily.get("account") or {}
if any(
native.get(key) != account.get(key)
for key in ("account_id", "definition_sha256")
):
return "当前运行账户与决策所关联的定义不一致"
acceptance = daily["operations"].get("acceptance") or {}
count = acceptance.get("longest_consecutive")
if type(count) is not int or count < 0:
return "自然交易日凭证未核实"
checked = daily.get("checked_at") or "时间未提供"
return f"最长连续自然成功 {count}/6;核验时间 {checked};不代表策略有效"


def summary_body(root, record, daily):
review = record.get("next_review_date") or "尚未安排"
body = f"<p>下次复核:{escape(review)}</p>"
body += f"<p>Gate A:{escape(gate_a_summary(record.get('account'), daily))}</p>"
for ref in record["evidence"]:
labels, objectives = evidence_summary(root / ref["run_id"])
text = ";".join(labels + (objectives or ["未提供原生目标评审结果"]))
body += f"<p>实验 {escape(ref['run_id'])}:{escape(text)}</p>"
body += "<p>Gate B/C 不由运行成功或点估计满足自动判定。</p>"
return body
12 changes: 12 additions & 0 deletions src/quant_studio/findings.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from html import escape

from quant_studio import QuantStudioError
from quant_studio.decision_summary import summary_body
from quant_studio.projects import ProjectStore
from quant_studio.research_cards import ACTIONS, ROLES, VERDICTS, DecisionStore

Expand All @@ -23,6 +24,7 @@ def findings_body(root, query):
<select name="action">{options}</select></label><button class="btn">筛选</button>
</form></section>"""
projects, decisions = ProjectStore(root), DecisionStore(root)
daily, daily_read = None, False
count = 0
for current in projects.list():
records = decisions.list(current["id"])
Expand All @@ -44,13 +46,23 @@ def findings_body(root, query):
for ref in record["evidence"]
)
href = f"/projects/{project['id']}?revision={project['revision']}"
if record.get("account") and not daily_read:
from quant_studio.etf_daily import inspect_daily

daily_read = True
try:
daily = inspect_daily()
except (QuantStudioError, OSError, ValueError):
daily = None
summary = summary_body(projects.runs_root, record, daily)
body += f'''<section class="panel"><h2><a href="{href}">
{escape(project["name"])}</a></h2>
<p class="badge">{VERDICTS[record["verdict"]]} · {ACTIONS[record["action"]]}</p>
<p>假设:{escape(card["mechanism"])}</p>
<p>{ROLES[card["sample_role"]]} · {escape(card["start"])} 至 {escape(card["end"])}</p>
<p>否定条件:{escape(card["rejection_rule"])}</p>
<p>结论依据:{escape(record["rationale"])}</p>
{summary}
<p>记录时间:{escape(record["recorded_at"])}</p><ul>{evidence}</ul></section>'''
if not count:
body += '<section class="panel"><p>尚无符合条件的研究结论。</p></section>'
Expand Down
2 changes: 2 additions & 0 deletions src/quant_studio/research_card_web.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ def card_body(root, token, project, section="all"):
<label>结论<select name="verdict">{options(VERDICTS, "inconclusive")}</select></label>
<label>下一步<select name="action">{options(ACTIONS)}</select></label>
<label>理由<textarea name="rationale" maxlength="8000" required></textarea></label>
<label>下次复核日期(可选)<input type="date" name="next_review_date"></label>
<label>提名的已完成原生候选(仅提名时必选)
<select name="candidate">{candidate_options}</select></label>
<label>已配置的模拟账户ID(可选)<input name="account_id"></label><p>引用实验:</p>'''
Expand Down Expand Up @@ -116,6 +117,7 @@ def card_post(root, identifier, revision, action, data):
values.update(
candidate=field(data, "candidate", ""),
account_id=field(data, "account_id", ""),
next_review_date=field(data, "next_review_date", ""),
evidence=data.pop("evidence", []),
)
if data:
Expand Down
11 changes: 11 additions & 0 deletions src/quant_studio/research_cards.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ def append(
evidence,
candidate="",
account_id="",
next_review_date="",
):
project = self.projects.get(project_id)
if project["revision"] != revision:
Expand All @@ -95,6 +96,15 @@ def append(
raise QuantStudioError("请先登记研究卡")
if verdict not in VERDICTS or action not in ACTIONS:
raise QuantStudioError("研究结论或后续行动无效")
if not isinstance(next_review_date, str):
raise QuantStudioError("下次复核日期须为 YYYY-MM-DD")
if next_review_date:
try:
parsed = date.fromisoformat(next_review_date)
if parsed.isoformat() != next_review_date:
raise ValueError("noncanonical date")
except (ValueError, TypeError) as exc:
raise QuantStudioError("下次复核日期须为 YYYY-MM-DD") from exc
if (
not isinstance(rationale, str)
or not rationale.strip()
Expand Down Expand Up @@ -173,6 +183,7 @@ def append(
"evidence": refs,
"candidate": candidate,
"account": account,
"next_review_date": next_review_date,
}
record["sha256"] = digest(record)
directory = self.root / project_id / "decisions"
Expand Down
57 changes: 57 additions & 0 deletions tests/test_decision_summary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import hashlib
import json

import pytest

from quant_studio.decision_summary import evidence_summary, gate_a_summary


@pytest.mark.parametrize("provisional", [True, False])
def test_native_point_estimate_never_grants_research_acceptance(tmp_path, provisional):
path = tmp_path / "strategy-output/family/base/result.json"
path.parent.mkdir(parents=True)
path.write_text(
json.dumps(
{
"schema_version": "quant.research-result/v1",
"candidate": "base",
"provisional": provisional,
"objective_evaluation": {"status": "meets_objective"},
}
)
)
record = {
"status": "succeeded",
"output_hashes": {
path.relative_to(tmp_path).as_posix(): hashlib.sha256(
path.read_bytes()
).hexdigest()
},
}
(tmp_path / "result.json").write_text(json.dumps(record))
labels, objectives = evidence_summary(tmp_path)
assert objectives == ["base:目标点估计满足"]
assert ("provisional" in labels[0]) == provisional
assert "不计入" in labels[0] if provisional else "另行评审" in labels[0]
path.write_text(path.read_text() + " ")
assert evidence_summary(tmp_path) == (["证据未核验;不计入验收"], [])


def test_unverified_success_does_not_become_validated_evidence(tmp_path):
(tmp_path / "result.json").write_text(json.dumps({"status": "succeeded"}))
assert evidence_summary(tmp_path) == (["证据未核验;不计入验收"], [])


def test_gate_a_is_bound_to_account_definition_and_native_counter():
account = {"account_id": "old", "definition_sha256": "frozen"}
native = {
"account": dict(account),
"checked_at": "2026-10-22T12:00:00+08:00",
"operations": {"acceptance": {"longest_consecutive": 0}},
}
assert "0/6" in gate_a_summary(account, native)
native["operations"]["acceptance"]["longest_consecutive"] = True
assert "未核实" in gate_a_summary(account, native)
native["account"]["definition_sha256"] = "replacement"
assert "不一致" in gate_a_summary(account, native)
assert "未核实" in gate_a_summary(account, None)
3 changes: 3 additions & 0 deletions tests/test_findings.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ def test_findings_retain_rejected_hypothesis_revision_and_check_evidence(tmp_pat
action="stop_research",
rationale="negative evidence",
evidence=[result.run_id],
next_review_date="2026-10-29",
)
store.save(
"new title",
Expand All @@ -45,6 +46,8 @@ def test_findings_retain_rejected_hypothesis_revision_and_check_evidence(tmp_pat
assert "old hypothesis" in page and "new hypothesis" not in page
assert "&lt;study&gt;" in page and "<study>" not in page
assert result.run_id in page and project["revision"] in page
assert "下次复核:2026-10-29" in page and "Gate A:未关联模拟账户" in page
assert "未提供原生目标评审结果" in page
assert "negative evidence" not in findings_body(
tmp_path, {"action": ["revise_hypothesis"]}
)
Expand Down
Loading