diff --git a/README.md b/README.md index b816e2a..a58313c 100644 --- a/README.md +++ b/README.md @@ -84,6 +84,8 @@ skfolio、OptimalPortfolios和qis已通过真实库调用测试。AKShare适配 所有研究导出路径必须是新路径。`verify-run`检查已列文件的SHA-256、输入数据摘要和每日资金对账,不是数字签名,也不能证明金融模型正确。历史运行目录中的`code/src/quant_fund`、`code/pyproject.toml`和`code/requirements.lock`可在独立环境安装后重跑。精确复现还依赖同一Python/依赖版本和求解器环境。 +外部确认单与赎回到账流水可使用`reconcile-observations`只读对账,输入列、退出码和真实性边界见[外部凭证对账契约](docs/OBSERVATION_RECONCILIATION.md)。 + 可选公募采集: ```powershell diff --git a/docs/INTEGRATION.md b/docs/INTEGRATION.md index 6ed2e9b..a53fb99 100644 --- a/docs/INTEGRATION.md +++ b/docs/INTEGRATION.md @@ -94,3 +94,7 @@ payload = platform_snapshot(result, data) 使用`quant-lab validate --run-dir <研究目录>`核验后,可扫描到独立实验索引,由Report Hub按索引位置重新验证产物并展示。索引是可重建缓存;来源损坏时应显示不可用,不能使用旧缓存指标。`research`视图中的汇总NAV不能承担完整QExec现金分录、订单和成交链路的精确归因。 v2的`metrics.json`保留原报告的全部指标,并添加数据分类、估值口径和`backtest_stats`展示行。完整估值区间使用首末已知估值及完整路径回撤,年化与Sharpe留空;完整月末收益样本另行展示收益、月末回撤和按12期年化的指标,两行不能混合使用。陈旧估值可能低估风险;没有新增基金基准或将低频净值插值成日收益。`config.json`的`study_config`保留原回测配置。 +## 外部凭证对账补充 + +`reconcile-observations`提供独立于平台快照的只读对账CLI,schema为`quant-fund.observation-reconciliation/v1`。完整输入、输出与限制见[外部凭证对账契约](OBSERVATION_RECONCILIATION.md)。该结果不提升standard/v2的investable、rankable或真实业务认证等级。 + diff --git a/docs/OBSERVATION_RECONCILIATION.md b/docs/OBSERVATION_RECONCILIATION.md new file mode 100644 index 0000000..5cffcb1 --- /dev/null +++ b/docs/OBSERVATION_RECONCILIATION.md @@ -0,0 +1,58 @@ +# 外部申赎确认与赎回到账对账 + +`verify-run`核验保存的模型账本。`reconcile-observations`先执行同一核验,再只读比较独立提供的确认单和赎回到账记录;不会更改持仓或现金,也不会发送交易。 + +```powershell +python -m quant_fund.cli reconcile-observations --run artifacts/my-run --confirmations data/private/confirmations.csv --receipts data/private/receipts.csv +``` + +结果输出到标准输出;重定向保存时请使用私有目录中的新文件名,不要覆盖输入。真实原始文件、账户信息和对账差异不得提交Git。输入表必须由独立凭证整理,不能从模型输出复制后声称完成真实验收。 + +## 输入契约 + +UTF-8 CSV(允许BOM),必须有且仅有下述列;列顺序可变。空表仍需表头。每一行所有字段非空;每张表的`order_id`及`evidence_id`各自唯一。支持一笔订单对应一条完整确认和一条完整赎回收款;拆分确认、分期到账、退款冲销及多币种尚不支持,不能自行合并后声称覆盖这些业务。 + +确认表表头: + +```csv +evidence_id,order_id,fund_id,side,deal_date,confirmed,unit_nav,shares,gross,fee,currency,source_ref +``` + +到账表表头: + +```csv +evidence_id,order_id,fund_id,received,amount,currency,source_ref +``` + +|字段|含义与要求| +|---|---| +|evidence_id|输入凭证唯一编号;不要放完整银行账号| +|order_id|人工核对后映射到运行中的正整数订单ID,不按金额猜配| +|fund_id / side|准确的基金份额类别代码;BUY或SELL| +|deal_date / confirmed|确认凭证上的交易日期、实际确认日期,YYYY-MM-DD;确认不能早于交易| +|unit_nav / shares|成交单位净值、确认份额,有限正数| +|gross / fee|申购gross为含申购费的申请金额;赎回gross为扣赎回费前金额;fee为该笔交易费用,有限非负数| +|received / amount|银行或销售机构的实际赎回到账日及净收款金额,不能用预计日期和应收款代替| +|currency|当前仅允许CNY| +|source_ref|可定位原始凭证的本地引用或脱敏索引;程序不打开引用,也不认证其真实性| + +程序要求完整覆盖运行中的所有已确认交易。赎回预期到账按已核验输入的账户日历、银行用途日历和实际模型确认日计算,不早于计划结算日或确认日。运行截止日尚未到账的订单列入`pending_redemption_order_ids`;不向未来延长回放。输入的额外订单或超出预期范围的收款会报告`unexpected`,不会自动入账。 + +## 输出契约 + +schema为`quant-fund.observation-reconciliation/v1`: + +- `status=matched`:有已确认交易,且本次比较无差异;退出码0。 +- `status=differences`:存在missing、unexpected或字段mismatch;退出码2。 +- `status=no_trades`:无可对比已确认交易;退出码2,不能当成验收通过。 +- 非法输入、重复身份、损坏运行等抛出异常并返回非零退出码。 +- `read_only=true`、`real_business_certified=false`始终保留;`classification`继承原始运行,合成样本不会升级为真实。 +- 输出期末日期、确认/收款数量、待到账订单、差异及运行manifest和两张输入表的SHA-256。 + +金额绝对容差为0.000001元,净值和份额为0.00000001,不采用相对容差。日期和身份必须精确相同。这是数值比较容差,不代表实际业务舍入规则;若销售机构采用分位/份额舍入,应根据真实条款明确建模并重新验收,不能放宽容差隐藏差异。 + +## 真实验收仍需要的资料 + +以同一基金份额类别的一次申购、持有和赎回为最小闭环,提供历史有效招募说明书/费率及适用销售渠道规则、申请与确认凭证、对应净值披露、交易与银行日历、赎回实际到账流水。每项保留来源、适用期、真实获知时间及原始文件摘要;材料缺失时留空并阻断对应认证,不反推历史获知时间。 + +此入口覆盖已确认交易和赎回收款的对比,不核验申购银行扣款、分红实收、期初期末银行余额、未确认申请、凭证真伪及完整业务模型。公开净值与最新招募说明书不能替代这些资料。测试中的外部表由合成模型生成,仅验证软件路径,并通过修改金额、份额、费用和日期验证差异检出。 diff --git a/src/quant_fund/cli.py b/src/quant_fund/cli.py index 552da79..a1213f5 100644 --- a/src/quant_fund/cli.py +++ b/src/quant_fund/cli.py @@ -45,6 +45,10 @@ def main(): export.add_argument("--out", required=True) verify = commands.add_parser("verify-run") verify.add_argument("directory") + reconcile = commands.add_parser("reconcile-observations", help="只读对比外部确认与赎回到账记录") + reconcile.add_argument("--run", required=True) + reconcile.add_argument("--confirmations", required=True) + reconcile.add_argument("--receipts", required=True) fetch = commands.add_parser("fetch-public") fetch.add_argument("--code", required=True) fetch.add_argument("--out", required=True) @@ -77,6 +81,13 @@ def main(): print(f"已导出{len(frame)}条历史版本") elif args.command == "verify-run": print(json.dumps(verify_run(args.directory), ensure_ascii=False)) + elif args.command == "reconcile-observations": + from .observations import reconcile_observations + + result = reconcile_observations(args.run, args.confirmations, args.receipts) + print(json.dumps(result, ensure_ascii=False, allow_nan=False)) + if result["status"] != "matched": + raise SystemExit(2) elif args.command == "fetch-public": from .providers import fetch_akshare diff --git a/src/quant_fund/observations.py b/src/quant_fund/observations.py new file mode 100644 index 0000000..196bc4b --- /dev/null +++ b/src/quant_fund/observations.py @@ -0,0 +1,227 @@ +"""Read-only comparison of modeled trades with separately supplied observations.""" + +import csv +import hashlib +import json +from decimal import Decimal, InvalidOperation +from io import StringIO +from pathlib import Path + +from .data import Dataset, day +from .report import verify_run + +CONFIRMATION_COLUMNS = ( + "evidence_id", + "order_id", + "fund_id", + "side", + "deal_date", + "confirmed", + "unit_nav", + "shares", + "gross", + "fee", + "currency", + "source_ref", +) +RECEIPT_COLUMNS = ( + "evidence_id", + "order_id", + "fund_id", + "received", + "amount", + "currency", + "source_ref", +) +TOLERANCES = { + "unit_nav": Decimal("0.00000001"), + "shares": Decimal("0.00000001"), + "gross": Decimal("0.000001"), + "fee": Decimal("0.000001"), + "amount": Decimal("0.000001"), +} + + +def _number(value, field): + try: + number = Decimal(value) + except (InvalidOperation, TypeError) as exc: + raise ValueError(f"Invalid observation number: {field}") from exc + if not number.is_finite() or number < 0 or (field in {"shares", "unit_nav"} and number == 0): + raise ValueError(f"Invalid observation number: {field}") + return number + + +def _order_id(value): + if not value.isascii() or not value.isdigit() or int(value) < 1: + raise ValueError("Observation order_id must be a positive integer") + return str(int(value)) + + +def _read(path, columns): + raw = Path(path).read_bytes() + reader = csv.DictReader(StringIO(raw.decode("utf-8-sig"))) + if reader.fieldnames is None or len(set(reader.fieldnames)) != len(reader.fieldnames): + raise ValueError("Observation CSV must have unique headers") + if set(reader.fieldnames) != set(columns): + raise ValueError(f"Observation CSV requires exactly these columns: {','.join(columns)}") + rows, ids, evidence = {}, set(), set() + for row in reader: + if None in row or any(not isinstance(v, str) or not v.strip() for v in row.values()): + raise ValueError("Observation CSV contains empty or malformed fields") + row = {key: value.strip() for key, value in row.items()} + key = _order_id(row["order_id"]) + if key in ids or row["evidence_id"] in evidence: + raise ValueError("Duplicate order or evidence identity in observations") + ids.add(key) + evidence.add(row["evidence_id"]) + row["order_id"] = key + if row["currency"] != "CNY": + raise ValueError("Only explicit CNY observations are supported") + for field in set(row).intersection(TOLERANCES): + _number(row[field], field) + for field in set(row).intersection({"deal_date", "confirmed", "received"}): + row[field] = str(day(row[field]).date()) + if "side" in row: + if row["side"] not in {"BUY", "SELL"}: + raise ValueError("Observation side must be BUY or SELL") + if row["confirmed"] < row["deal_date"]: + raise ValueError("Confirmation cannot precede dealing date") + rows[key] = row + return rows, hashlib.sha256(raw).hexdigest() + + +def _compare(expected, observed, fields, kind): + differences = [] + for key in sorted(set(expected) | set(observed), key=int): + left, right = expected.get(key), observed.get(key) + if left is None or right is None: + differences.append( + { + "kind": kind, + "order_id": key, + "issue": "unexpected" if left is None else "missing", + } + ) + continue + for field in fields: + a, b = left[field], right[field] + if field in TOLERANCES: + delta = _number(b, field) - _number(a, field) + equal = abs(delta) <= TOLERANCES[field] + else: + equal = a == b + if not equal: + differences.append( + { + "kind": kind, + "order_id": key, + "issue": "mismatch", + "field": field, + "expected": a, + "observed": b, + } + ) + return differences + + +def _redemption_date(dataset, trade, as_of): + if not trade["settle_date"]: + return None + earliest = max(day(trade["settle_date"]), day(trade["confirmed"])) + for date in dataset.account_calendar: + if date < earliest or date > day(as_of): + continue + if dataset.purpose_calendars is not None: + calendar, at = dataset.purpose_calendar("banking", date, date) + if not calendar.is_open(date, at=at, purpose="banking"): + continue + return str(date.date()) + return None + + +def reconcile_observations(directory, confirmations, receipts): + """Compare supplied records; never book cash, alter a run, or certify authenticity.""" + root = Path(directory) + paths = [ + root / "manifest.json", + root / "trades.csv", + root / "nav.csv", + Path(confirmations), + Path(receipts), + ] + before = {str(p.resolve()): hashlib.sha256(p.read_bytes()).hexdigest() for p in paths} + verified = verify_run(root) + dataset = Dataset.load(root / "inputs") + manifest = json.loads((root / "manifest.json").read_text(encoding="utf-8")) + actual, confirmation_hash = _read(confirmations, CONFIRMATION_COLUMNS) + cash, receipt_hash = _read(receipts, RECEIPT_COLUMNS) + trades = list(csv.DictReader(StringIO((root / "trades.csv").read_text(encoding="utf-8")))) + nav = list(csv.DictReader(StringIO((root / "nav.csv").read_text(encoding="utf-8")))) + # Use the actual verified run interval, not a requested end outside the calendar. + as_of = str(day(nav[-1]["date"]).date()) + expected, arrivals = {}, {} + pending = [] + for trade in trades: + key = _order_id(trade["order_id"]) + expected[key] = { + field: trade[field] + for field in ( + "fund_id", + "side", + "deal_date", + "confirmed", + "unit_nav", + "shares", + "gross", + "fee", + ) + } + for field in ("deal_date", "confirmed"): + expected[key][field] = str(day(expected[key][field]).date()) + if trade["side"] != "SELL": + continue + planned = _redemption_date(dataset, trade, as_of) + if planned is None: + pending.append(key) + continue + arrivals[key] = { + "fund_id": trade["fund_id"], + "received": planned, + "amount": str(_number(trade["gross"], "gross") - _number(trade["fee"], "fee")), + } + fields = ("fund_id", "side", "deal_date", "confirmed", "unit_nav", "shares", "gross", "fee") + differences = _compare(expected, actual, fields, "confirmation") + differences += _compare(arrivals, cash, ("fund_id", "received", "amount"), "redemption_receipt") + if before != {str(p.resolve()): hashlib.sha256(p.read_bytes()).hexdigest() for p in paths}: + raise ValueError("Inputs changed during observation reconciliation") + return { + "schema": "quant-fund.observation-reconciliation/v1", + "status": "matched" + if not differences and expected + else "differences" + if differences + else "no_trades", + "read_only": True, + "real_business_certified": False, + "classification": manifest["classification"], + "as_of": as_of, + "verified_ledger_orders": verified["verified_ledger_orders"], + "expected_confirmations": len(expected), + "supplied_confirmations": len(actual), + "expected_redemption_receipts": len(arrivals), + "supplied_redemption_receipts": len(cash), + "pending_redemption_order_ids": pending, + "differences": differences, + "run_manifest_sha256": before[str((root / "manifest.json").resolve())], + "confirmation_sha256": confirmation_hash, + "receipt_sha256": receipt_hash, + "absolute_tolerances": {k: str(v) for k, v in TOLERANCES.items()}, + "limitations": [ + "Supplied observations and source references are not independently authenticated", + "Only confirmed modeled trades and calendar-based redemption arrivals are compared", + "No certification of bank debits, dividend receipts, bank balances or pending orders", + "No rounding policy inferred; discrepancies require source and model review", + "No account mutation or extension of the verified run interval", + ], + } diff --git a/tests/test_observations.py b/tests/test_observations.py new file mode 100644 index 0000000..46fc78e --- /dev/null +++ b/tests/test_observations.py @@ -0,0 +1,188 @@ +import csv +import hashlib +import json +import sys +from decimal import Decimal +from types import SimpleNamespace + +import pandas as pd +import pytest + +from quant_fund.cli import main +from quant_fund.data import Dataset +from quant_fund.engine import BacktestConfig, run_backtest +from quant_fund.observations import ( + CONFIRMATION_COLUMNS, + RECEIPT_COLUMNS, + _read, + _redemption_date, + reconcile_observations, +) +from quant_fund.report import export_run + + +def write_csv(path, columns, rows): + with path.open("w", encoding="utf-8", newline="") as stream: + writer = csv.DictWriter(stream, fieldnames=columns) + writer.writeheader() + writer.writerows(rows) + return path + + +@pytest.fixture(scope="module") +def modeled_run(demo_directory, tmp_path_factory): + dataset = Dataset.load(demo_directory) + result = run_backtest( + dataset, BacktestConfig(start="2024-01-02", end="2024-05-31", strategy="equal") + ) + root = export_run(result, dataset, demo_directory, tmp_path_factory.mktemp("run") / "report") + return root + + +@pytest.fixture +def observations(modeled_run, tmp_path): + # These are deliberately model-derived synthetic records, never real evidence. + with (modeled_run / "trades.csv").open(encoding="utf-8") as stream: + trades = list(csv.DictReader(stream)) + confirmations, receipts = [], [] + for trade in trades: + confirmations.append( + { + **{k: trade[k] for k in CONFIRMATION_COLUMNS if k in trade}, + "evidence_id": f"synthetic-confirm-{trade['order_id']}", + "currency": "CNY", + "source_ref": "synthetic:test-confirmation", + } + ) + if trade["side"] == "SELL" and trade["settle_date"] <= "2024-05-31": + receipts.append( + { + "evidence_id": f"synthetic-receipt-{trade['order_id']}", + "order_id": trade["order_id"], + "fund_id": trade["fund_id"], + "received": trade["settle_date"], + "amount": str(Decimal(trade["gross"]) - Decimal(trade["fee"])), + "currency": "CNY", + "source_ref": "synthetic:test-receipt", + } + ) + assert receipts, "Fixture must exercise redemption as well as subscription" + return confirmations, receipts, tmp_path / "confirm.csv", tmp_path / "receipts.csv" + + +def compare(root, observations): + confirmations, receipts, cpath, rpath = observations + write_csv(cpath, CONFIRMATION_COLUMNS, confirmations) + write_csv(rpath, RECEIPT_COLUMNS, receipts) + return reconcile_observations(root, cpath, rpath) + + +def test_matched_records_never_certify_real_business_or_mutate_run(modeled_run, observations): + before = { + p: hashlib.sha256(p.read_bytes()).hexdigest() for p in modeled_run.rglob("*") if p.is_file() + } + result = compare(modeled_run, observations) + assert result["status"] == "matched" + assert result["expected_redemption_receipts"] > 0 + assert result["read_only"] and not result["real_business_certified"] + assert result["classification"] == "synthetic" + assert before == {p: hashlib.sha256(p.read_bytes()).hexdigest() for p in before} + + +@pytest.mark.parametrize( + "change,kind,issue,field", + [ + ("fee", "confirmation", "mismatch", "fee"), + ("shares", "confirmation", "mismatch", "shares"), + ("cash", "redemption_receipt", "mismatch", "amount"), + ("late", "redemption_receipt", "mismatch", "received"), + ("missing", "confirmation", "missing", None), + ("extra", "redemption_receipt", "unexpected", None), + ], +) +def test_independent_discrepancies(modeled_run, observations, change, kind, issue, field): + confirmations, receipts, _, _ = observations + if change in {"fee", "shares"}: + confirmations[0][change] = str(Decimal(confirmations[0][change]) + 1) + elif change == "cash": + receipts[0]["amount"] = str(Decimal(receipts[0]["amount"]) - 1) + elif change == "late": + receipts[0]["received"] = "2024-06-03" + elif change == "missing": + confirmations.pop() + else: + receipts.append({**receipts[0], "order_id": "99999", "evidence_id": "extra"}) + result = compare(modeled_run, observations) + assert result["status"] == "differences" + assert any( + d["kind"] == kind and d["issue"] == issue and d.get("field") == field + for d in result["differences"] + ) + + +@pytest.mark.parametrize( + "field,value", + [ + ("shares", "NaN"), + ("fee", "Infinity"), + ("gross", "-1"), + ("unit_nav", "0"), + ("currency", "USD"), + ("source_ref", " "), + ("confirmed", "2024-01-01"), + ("order_id", "1.5"), + ], +) +def test_malformed_evidence_is_rejected(observations, field, value): + confirmations, _, cpath, _ = observations + confirmations[0][field] = value + write_csv(cpath, CONFIRMATION_COLUMNS, confirmations) + with pytest.raises(ValueError): + _read(cpath, CONFIRMATION_COLUMNS) + + +def test_duplicate_identity_and_extra_column_rejected(observations): + confirmations, _, cpath, _ = observations + write_csv(cpath, CONFIRMATION_COLUMNS, confirmations + confirmations[:1]) + with pytest.raises(ValueError, match="Duplicate"): + _read(cpath, CONFIRMATION_COLUMNS) + write_csv(cpath, (*CONFIRMATION_COLUMNS, "extra"), confirmations) + with pytest.raises(ValueError, match="exactly"): + _read(cpath, CONFIRMATION_COLUMNS) + + +def test_arrival_respects_confirmation_bank_calendar_and_run_cutoff(): + closed = pd.Timestamp("2024-01-05") + bank = SimpleNamespace(is_open=lambda date, **kwargs: date != closed) + dataset = SimpleNamespace( + account_calendar=pd.bdate_range("2024-01-02", "2024-01-10"), + purpose_calendars=True, + purpose_calendar=lambda *args: (bank, args[1]), + ) + trade = {"settle_date": "2024-01-04", "confirmed": "2024-01-05"} + assert _redemption_date(dataset, trade, "2024-01-08") == "2024-01-08" + assert _redemption_date(dataset, trade, "2024-01-05") is None + assert _redemption_date(dataset, {**trade, "settle_date": ""}, "2024-01-10") is None + + +def test_cli_exit_code_reports_difference(modeled_run, observations, monkeypatch, capsys): + observations[1].pop() + compare(modeled_run, observations) + monkeypatch.setattr( + sys, + "argv", + [ + "quant-fund", + "reconcile-observations", + "--run", + str(modeled_run), + "--confirmations", + str(observations[2]), + "--receipts", + str(observations[3]), + ], + ) + with pytest.raises(SystemExit) as exc: + main() + assert exc.value.code == 2 + assert json.loads(capsys.readouterr().out)["status"] == "differences"