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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions docs/INTEGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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或真实业务认证等级。

58 changes: 58 additions & 0 deletions docs/OBSERVATION_RECONCILIATION.md
Original file line number Diff line number Diff line change
@@ -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,不采用相对容差。日期和身份必须精确相同。这是数值比较容差,不代表实际业务舍入规则;若销售机构采用分位/份额舍入,应根据真实条款明确建模并重新验收,不能放宽容差隐藏差异。

## 真实验收仍需要的资料

以同一基金份额类别的一次申购、持有和赎回为最小闭环,提供历史有效招募说明书/费率及适用销售渠道规则、申请与确认凭证、对应净值披露、交易与银行日历、赎回实际到账流水。每项保留来源、适用期、真实获知时间及原始文件摘要;材料缺失时留空并阻断对应认证,不反推历史获知时间。

此入口覆盖已确认交易和赎回收款的对比,不核验申购银行扣款、分红实收、期初期末银行余额、未确认申请、凭证真伪及完整业务模型。公开净值与最新招募说明书不能替代这些资料。测试中的外部表由合成模型生成,仅验证软件路径,并通过修改金额、份额、费用和日期验证差异检出。
11 changes: 11 additions & 0 deletions src/quant_fund/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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

Expand Down
227 changes: 227 additions & 0 deletions src/quant_fund/observations.py
Original file line number Diff line number Diff line change
@@ -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",
],
}
Loading