diff --git a/README.md b/README.md index 3877e06..354a70e 100644 --- a/README.md +++ b/README.md @@ -66,9 +66,19 @@ python -m quant_timing preflight --config configs/combined.yaml | `decision.json` | 含 `use`、`hold_previous` 或 `blocked` 的完整决定。 | | `validation/` | 走步折、泄漏审计和摘要。全样本收益只作描述。 | | `standard/` | 与研究运行契约一致的收益、持仓、目标订单、成本和暴露。 | +| `attribution/daily.csv` | 策略和匹配敞口对照的逐日资产、现金、保证金、期货盈亏及两项模型成本;文件哈希绑定在标准metrics中。 | 持仓文件记录收盘调仓前的实际数量、金额和权重,`return_weight`用于上一笔决策的收益归因。期货和保证金使用各自的估值定义。所有产物验证成功后整体发布;导出失败不会提前发布仓位文件,非空输出目录拒绝覆盖。 +新运行的`standard/metrics.json.return_attribution`给出描述性全区间与每个原生测试折的可加总贡献。 +按每日的期初净资产连接贡献后,资产和现金收益、期货盈亏、基础成本及冲击成本的合计等于净收益。 +每折独立以1为归因期初,沿用既有决策日筛选及次日收益,未另行建仓;重叠折不拼接、不增加独立样本。 +匹配敞口贡献差属于账本分解,不单独证明仓位或风格的因果效应。详见[研究契约](docs/RESEARCH_CONTRACT.md)。 + +`standard/costs.csv.slippage`在新归因契约下仅记录配置bps对应的模型基础成本;非线性冲击单列到 +`market_impact`,费用合计和原收益路径不变。这两项均不是独立成交参考价测得的真实滑点。 +旧运行不补写、不重新解释其旧成本列;新版核验器仍可读取不含归因的旧标准产物。 + ```mermaid flowchart LR prices[指数与风格价格] --> study[quant-timing] diff --git a/docs/RESEARCH_CONTRACT.md b/docs/RESEARCH_CONTRACT.md index d420219..be8e50a 100644 --- a/docs/RESEARCH_CONTRACT.md +++ b/docs/RESEARCH_CONTRACT.md @@ -68,3 +68,28 @@ `standard/`使用研究契约v1的基础列,并在`positions`追加`return_weight`。`run_manifest.json`记录产物哈希及原始价格、完整估值价格快照。订单数量为研究单位下的调仓差额,状态为`target`。 全部文件先写到同一父目录下的临时目录,标准产物验证通过后才生成发布文件,最后一次重命名发布整个运行目录。导出或验证失败不会留下可消费的`position_scale.json`。输出目录必须不存在或为空;已有文件和已完成运行均拒绝覆盖。 + +## 收益归因 + +`quant-timing.return-attribution/v1`直接保留原模拟路径计算的上一决策权重乘当日资产收益, +以及该路径的基础成本和冲击成本,不从净值差额倒推资产收益。策略与匹配敞口对照分别留存。 +现金收益按原配置的零收益、利率或价格代理计算;保证金收益为零;期货只分配盈亏,不把名义本金加入净资产。 + +对每个区间,设上一日净资产为`N[t-1]`、当日分量为`c[k,t]`,贡献为 +`sum(N[t-1] * c[k,t])`。各分量相加等于该区间净收益,负成本也参与连接。 +它不是简单相加每日收益,也不是把各分量单独复利后相加。贡献以区间期初单位本金为分母, +前端显示时乘100,单位为百分点。 + +描述性全区间和每个测试折分别计算。测试折的筛选与`score_folds`相同:按决策日在测试区间内选取 +已经实现的次日收益,期末未发生的下一根收益不补零。每折只为归因把净资产基数重置为1, +并未重新执行账户或重新计算换手;无计分收益的折保留不可用,重叠折不聚合。 + +`attribution/daily.csv`列出日期、决策日、策略/对照、分量、上一决策权重、原生资产收益、 +当日贡献比例、全区间期初净资产及贡献金额。`standard/metrics.json.return_attribution`绑定CSV哈希、 +行数、归因口径和各区间汇总,标准manifest另绑定契约版本。原生核验器重算逐日、全区间与各折, +同时核对标准持仓的收益权重、标准收益和费用金额。文件缺失、重复分量、日期错位、摘要或账本不一致均拒绝。 + +新标准费用列`slippage`承载配置bps的基础成本代理,`market_impact`承载原非线性冲击模型; +两者之和保持原总成本。名称沿用基础标准列,manifest明确其模型性质。未使用独立执行参考价, +不宣称完成真实滑点测量或现金机会成本的因果识别。匹配敞口对照与策略的贡献差仅解释原账本的收益差, +不把重用历史样本的分解当作新的样本外或前向证据。 diff --git a/src/quant_timing/attribution.py b/src/quant_timing/attribution.py new file mode 100644 index 0000000..94b0dba --- /dev/null +++ b/src/quant_timing/attribution.py @@ -0,0 +1,368 @@ +"""Additive, NAV-linked attribution of the native strategy and matched return paths. + +This is an accounting decomposition, not a causal allocation experiment. Each scored +fold is linked independently from unit capital on its existing decision-date mask. +""" + +from __future__ import annotations + +import math +from pathlib import Path + +import numpy as np +import pandas as pd + +from quant_timing.book import FUTURES_COLUMNS +from quant_timing.contract import file_sha256 + +SCHEMA = "quant-timing.return-attribution/v1" +DAILY_PATH = "attribution/daily.csv" +DAILY_COLUMNS = [ + "date", + "decision_date", + "book", + "component", + "kind", + "return_weight", + "asset_return", + "contribution", + "opening_nav", + "pnl", +] +BOOKS = {"strategy": "", "matched": "matched_"} +SEMANTICS = { + "method": "opening_net_nav_times_daily_return_component", + "scope": "descriptive_full_sample_and_individually_rebased_scored_folds", + "unit": "return_fraction_of_each_period_initial_capital", + "cost_semantics": { + "base_cost": "native_turnover_times_configured_bps_proxy", + "impact_cost": "native_configured_nonlinear_impact_model", + "observed_execution_slippage": False, + }, + "folds_are_independent_attribution_windows": True, + "folds_are_separately_executed_accounts": False, + "overlapping_folds_are_not_aggregated": True, +} + + +def _kind(symbol: str) -> str: + if symbol in FUTURES_COLUMNS: + return "futures" + return {"CASH": "cash", "MARGIN": "margin"}.get(symbol, "asset") + + +def _opening_nav(net: pd.Series) -> np.ndarray: + return np.r_[1.0, (1.0 + net.to_numpy(dtype=float)).cumprod()[:-1]] + + +def write_attribution(result, run_dir: Path, returns: pd.DataFrame) -> dict: + realized = result.realized.dropna(subset=["net_return"]) + rows = [] + symbols = list(result.weights.columns) + for book, prefix in BOOKS.items(): + weights = result.weights if book == "strategy" else result.matched_weights + held = weights.shift(1).loc[realized.index] + opening = _opening_nav(realized[f"{prefix}net_return"]) + for offset, (stamp, row) in enumerate(realized.iterrows()): + base = { + "date": str(stamp.date()), + "decision_date": str(pd.Timestamp(row["decision_date"]).date()), + "book": book, + "opening_nav": float(opening[offset]), + } + for symbol in symbols: + contribution = float(row[f"{prefix}contribution:{symbol}"]) + rows.append( + { + **base, + "component": symbol, + "kind": _kind(symbol), + "return_weight": float(held.loc[stamp, symbol]), + "asset_return": row[f"asset_return:{symbol}"], + "contribution": contribution, + "pnl": opening[offset] * contribution, + } + ) + for cost in ("base_cost", "impact_cost"): + contribution = -float(row[f"{prefix}{cost}"]) + rows.append( + { + **base, + "component": cost, + "kind": "modeled_cost", + "return_weight": None, + "asset_return": None, + "contribution": contribution, + "pnl": opening[offset] * contribution, + } + ) + daily = pd.DataFrame(rows, columns=DAILY_COLUMNS) + path = Path(run_dir) / DAILY_PATH + path.parent.mkdir() + daily.to_csv(path, index=False) + payload = { + "schema": SCHEMA, + **SEMANTICS, + "assets": symbols, + "daily": {"path": DAILY_PATH, "sha256": file_sha256(path), "rows": len(daily)}, + "periods": _periods(daily, returns, result.folds.to_dict(orient="records")), + } + return payload + + +def _periods(daily: pd.DataFrame, returns: pd.DataFrame, folds: list[dict]) -> list[dict]: + periods = [_period("descriptive", returns, daily)] + for fold in folds: + selected = returns.loc[ + returns["decision_date"].between(fold["test_start"], fold["test_end"]) + ] + if len(selected) != fold["n_decisions"]: + raise ValueError("attribution fold decision count mismatch") + period = _period(f"fold-{fold['fold']}", selected, daily) + period["test_start"] = fold["test_start"] + period["test_end"] = fold["test_end"] + for key in ( + "net_return", + "matched_net_return", + "benchmark_return", + "excess_return", + "matched_excess_return", + ): + _same(period[key], fold[key], f"fold {fold['fold']} {key}") + periods.append(period) + return periods + + +def _period(name: str, returns: pd.DataFrame, daily: pd.DataFrame) -> dict: + result = { + "id": name, + "n_decisions": len(returns), + "first_return_date": None if returns.empty else returns["date"].iloc[0], + "last_return_date": None if returns.empty else returns["date"].iloc[-1], + "components": [], + } + for key in ("net_return", "matched_net_return", "benchmark_return"): + result[key] = None if returns.empty else float((1.0 + returns[key]).prod() - 1.0) + result["excess_return"] = _gap(result["net_return"], result["benchmark_return"]) + result["matched_excess_return"] = _gap(result["net_return"], result["matched_net_return"]) + result["strategy_residual"] = None + result["matched_residual"] = None + if returns.empty: + return result + linked = {} + for book, prefix in BOOKS.items(): + part = daily.loc[(daily["book"] == book) & daily["date"].isin(returns["date"])] + pivot = part.pivot(index="date", columns=["kind", "component"], values="contribution") + pivot = pivot.reindex(returns["date"]) + if pivot.empty or pivot.isna().any().any(): + raise ValueError("attribution period has incomplete components") + linked[book] = pivot.mul(_opening_nav(returns[f"{prefix}net_return"]), axis=0).sum() + residual = result[f"{prefix}net_return"] - float(linked[book].sum()) + _same(residual, 0.0, f"{name} {book} linked reconciliation") + result[f"{book}_residual"] = residual + if not linked["strategy"].index.equals(linked["matched"].index): + raise ValueError("attribution comparison components mismatch") + for (kind, component), value in linked["strategy"].items(): + matched = float(linked["matched"].loc[(kind, component)]) + result["components"].append( + { + "kind": kind, + "component": component, + "strategy": float(value), + "matched": matched, + "difference": float(value) - matched, + } + ) + _same( + sum(row["difference"] for row in result["components"]), + result["matched_excess_return"], + f"{name} matched difference", + ) + return result + + +def _gap(left, right): + return None if left is None or right is None else left - right + + +def _same(actual, expected, label: str) -> None: + if pd.isna(actual) or pd.isna(expected): + if pd.isna(actual) and pd.isna(expected): + return + raise ValueError(f"attribution {label} missing") + if not math.isfinite(float(actual)) or not math.isclose( + float(actual), float(expected), abs_tol=1e-10, rel_tol=1e-10 + ): + raise ValueError(f"attribution {label} mismatch") + + +def _numeric_equal(actual, expected, label: str) -> None: + left, right = np.asarray(actual, dtype=float), np.asarray(expected, dtype=float) + if left.shape != right.shape or not np.isfinite(left).all() or not np.isfinite(right).all(): + raise ValueError(f"attribution {label} invalid") + if not np.allclose(left, right, atol=1e-10, rtol=1e-10): + raise ValueError(f"attribution {label} mismatch") + + +def _compare(actual, expected, label="periods") -> None: + if isinstance(expected, dict): + if not isinstance(actual, dict) or actual.keys() != expected.keys(): + raise ValueError(f"attribution {label} fields mismatch") + for key in expected: + _compare(actual[key], expected[key], f"{label}.{key}") + elif isinstance(expected, list): + if not isinstance(actual, list) or len(actual) != len(expected): + raise ValueError(f"attribution {label} count mismatch") + for index, (left, right) in enumerate(zip(actual, expected)): + _compare(left, right, f"{label}.{index}") + elif isinstance(expected, (int, float)): + if actual is None or isinstance(actual, bool): + raise ValueError(f"attribution {label} numeric value missing") + _same(actual, expected, label) + elif actual != expected: + raise ValueError(f"attribution {label} mismatch") + + +def validate_attribution(run_dir: Path, metrics: dict) -> dict: + """Verify bound daily evidence and recompute all periods against native standard CSVs.""" + payload = metrics["return_attribution"] + if payload.get("schema") != SCHEMA or payload["daily"]["path"] != DAILY_PATH: + raise ValueError("unsupported timing attribution schema or path") + if any(payload.get(key) != value for key, value in SEMANTICS.items()): + raise ValueError("attribution measurement semantics mismatch") + root = Path(run_dir).resolve() + path = root / DAILY_PATH + if not path.resolve().is_relative_to(root): + raise ValueError("attribution evidence escaped run") + if not path.is_file() or file_sha256(path) != payload["daily"]["sha256"]: + raise ValueError("attribution evidence missing or mutated") + daily = pd.read_csv(path, dtype={"component": str, "date": str, "decision_date": str}) + if list(daily.columns) != DAILY_COLUMNS or len(daily) != payload["daily"]["rows"]: + raise ValueError("attribution daily schema or row count mismatch") + standard = root / "standard" + returns = pd.read_csv(standard / "returns.csv", dtype={"date": str, "decision_date": str}) + costs = pd.read_csv(standard / "costs.csv", dtype={"date": str}).set_index("date") + positions = pd.read_csv(standard / "positions.csv", dtype={"date": str, "symbol": str}) + _validate_daily(daily, returns, costs, positions, payload["assets"]) + fold_path = root / "validation/fold_metrics.csv" + if ( + not fold_path.resolve().is_relative_to(root) + or not fold_path.is_file() + or file_sha256(fold_path) != metrics["fold_metrics_sha256"] + ): + raise ValueError("attribution fold evidence missing or mutated") + fold_frame = pd.read_csv(fold_path) + fold_rows = [ + {key: None if pd.isna(value) else value for key, value in row.items()} + for row in fold_frame.to_dict(orient="records") + ] + _compare(metrics["walk_forward_folds"], fold_rows, "native folds") + periods = _periods(daily, returns, metrics["walk_forward_folds"]) + _compare(payload["periods"], periods) + _same(periods[0]["net_return"], metrics["descriptive_full_sample_net"], "full return") + _same( + periods[0]["benchmark_return"], + metrics["descriptive_full_sample_benchmark"], + "full benchmark", + ) + return payload + + +def _validate_daily(daily, returns, costs, positions, symbols): + dates = returns["date"].tolist() + if ( + not dates + or len(set(dates)) != len(dates) + or dates != sorted(dates) + or returns["strategy"].unique().tolist() != ["timing"] + ): + raise ValueError("attribution requires unique ordered timing dates") + if ( + not symbols + or len(set(symbols)) != len(symbols) + or set(daily["book"]) != set(BOOKS) + or daily.duplicated(["date", "book", "kind", "component"]).any() + ): + raise ValueError("attribution components missing or duplicated") + expected = {(_kind(symbol), symbol) for symbol in symbols} + expected.update(("modeled_cost", name) for name in ("base_cost", "impact_cost")) + for book, prefix in BOOKS.items(): + rows = daily.loc[daily["book"] == book] + if set(zip(rows["kind"], rows["component"])) != expected: + raise ValueError("attribution component set mismatch") + if len(rows) != len(dates) * len(expected): + raise ValueError("attribution daily components incomplete") + opening = _opening_nav(returns[f"{prefix}net_return"]) + pieces = {} + funded = np.zeros(len(dates)) + for kind, component in sorted(expected): + part = rows.loc[(rows["kind"] == kind) & (rows["component"] == component)] + if set(part["date"]) != set(dates): + raise ValueError("attribution date coverage mismatch") + part = part.set_index("date").loc[dates] + if part["decision_date"].tolist() != returns["decision_date"].tolist(): + raise ValueError("attribution decision date mismatch") + _numeric_equal(part["opening_nav"], opening, "opening NAV") + _numeric_equal(part["pnl"], part["contribution"] * opening, "component PnL") + values = part["contribution"].to_numpy(dtype=float) + pieces[(kind, component)] = values + if kind == "modeled_cost": + if ( + part[["return_weight", "asset_return"]].notna().any().any() + or (values > 0).any() + ): + raise ValueError("attribution modeled cost semantics invalid") + _numeric_equal(-values, returns[f"{prefix}{component}"], "cost component") + continue + weight = part["return_weight"].to_numpy(dtype=float) + asset_return = part["asset_return"].to_numpy(dtype=float) + contribution = weight * asset_return + # The native futures path permits unavailable returns only for an idle leg. + idle_missing = (np.abs(weight) <= 1e-12) & np.isnan(asset_return) + if kind == "futures": + contribution[idle_missing] = 0.0 + _numeric_equal(values, contribution, "lagged weight times asset return") + if kind != "futures": + funded += weight + if book == "strategy": + pos = positions.loc[positions["symbol"] == component] + if pos["date"].duplicated().any() or set(pos["date"]) != set(dates): + raise ValueError("attribution position coverage mismatch") + _numeric_equal( + weight, + pos.set_index("date").loc[dates, "return_weight"], + "native position return weight", + ) + _numeric_equal(funded, np.ones(len(dates)), "funded weights") + total = np.sum(list(pieces.values()), axis=0) + gross = np.sum( + [value for (kind, _), value in pieces.items() if kind != "modeled_cost"], axis=0 + ) + _numeric_equal(total, returns[f"{prefix}net_return"], "daily net return") + _numeric_equal(gross, returns[f"{prefix}gross_return"], "daily gross return") + if book == "strategy": + _numeric_equal( + opening * (1 + returns["net_return"].to_numpy()), returns["nav"], "native NAV" + ) + if costs.index.has_duplicates or set(costs.index) != set(dates): + raise ValueError("attribution native cost dates mismatch") + for component, field in (("base_cost", "slippage"), ("impact_cost", "market_impact")): + _numeric_equal( + -pieces[("modeled_cost", component)] * opening, + costs.loc[dates, field], + "native currency cost", + ) + _numeric_equal( + (gross - total) * opening, + costs.loc[dates, "total_cost"], + "native total currency cost", + ) + asset_rows = daily.loc[daily["kind"] != "modeled_cost"] + for symbol in symbols: + observed = asset_rows.loc[asset_rows["component"] == symbol].pivot( + index="date", columns="book", values="asset_return" + ) + if not np.allclose( + observed["strategy"], observed["matched"], equal_nan=True, atol=0, rtol=0 + ): + raise ValueError("attribution books use different asset returns") diff --git a/src/quant_timing/book.py b/src/quant_timing/book.py index 36e1341..59b973b 100644 --- a/src/quant_timing/book.py +++ b/src/quant_timing/book.py @@ -1,5 +1,7 @@ from __future__ import annotations +from dataclasses import dataclass + import numpy as np import pandas as pd @@ -55,6 +57,19 @@ def assemble_weights( FUTURES_COLUMNS = {"FUTURES", "IF", "IC", "IM"} +@dataclass +class _PathResult: + gross: pd.Series + net: pd.Series + cost: pd.Series + base_cost: pd.Series + impact_cost: pd.Series + turnover: pd.Series + trades: pd.DataFrame + contributions: pd.DataFrame + asset_returns: pd.DataFrame + + def _assert_book(weights: pd.DataFrame) -> None: funded = [column for column in weights.columns if column not in _FUTURES_COLUMNS] totals = weights[funded].sum(axis=1) @@ -89,29 +104,40 @@ def simulate( asset[name] = series.reindex(asset.index) if "MARGIN" in weights.columns: asset["MARGIN"] = 0.0 - gross, net, cost, turnover, trades = _path(weights, asset, cost_bps, impact_coef, adv, capital) - matched_gross, matched_net, matched_cost, matched_turnover, _ = _path( - matched, asset, cost_bps, impact_coef, adv, capital - ) + path = _path(weights, asset, cost_bps, impact_coef, adv, capital) + control = _path(matched, asset, cost_bps, impact_coef, adv, capital) frame = pd.DataFrame( { "decision_date": pd.Series(weights.index, index=weights.index).shift(1), - "gross_return": gross, - "net_return": net, - "cost": cost, - "turnover": turnover, + "gross_return": path.gross, + "net_return": path.net, + "cost": path.cost, + "turnover": path.turnover, "benchmark_return": prices[market].pct_change(), - "matched_gross_return": matched_gross, - "matched_net_return": matched_net, - "matched_cost": matched_cost, - "matched_turnover": matched_turnover, + "matched_gross_return": control.gross, + "matched_net_return": control.net, + "matched_cost": control.cost, + "matched_turnover": control.turnover, + "base_cost": path.base_cost, + "impact_cost": path.impact_cost, + "matched_base_cost": control.base_cost, + "matched_impact_cost": control.impact_cost, }, index=weights.index, ) frame.index = frame.index.rename("date") frame["nav"] = _nav(frame["net_return"]) # Decision-date deltas are also the source for research order exports. - return pd.concat([frame, trades.rename_axis("date").add_prefix("trade:")], axis=1) + return pd.concat( + [ + frame, + path.trades.rename_axis("date").add_prefix("trade:"), + path.contributions.rename_axis("date").add_prefix("contribution:"), + control.contributions.rename_axis("date").add_prefix("matched_contribution:"), + path.asset_returns.rename_axis("date").add_prefix("asset_return:"), + ], + axis=1, + ) def _path( @@ -121,7 +147,7 @@ def _path( impact_coef: float = 0.0, adv: pd.Series | None = None, capital: float | None = None, -) -> tuple[pd.Series, pd.Series, pd.Series, pd.Series, pd.DataFrame]: +) -> _PathResult: columns = list(weights.columns) returns = asset.reindex(columns=columns) if "CASH" in returns.columns: @@ -142,6 +168,8 @@ def _path( trades = np.zeros_like(targets) turnover = np.full(len(weights), np.nan) cost = np.full(len(weights), np.nan) + base_cost = np.full(len(weights), np.nan) + impact_cost = np.full(len(weights), np.nan) unit_impact = ( _impact(pd.Series(1.0, index=weights.index), float(impact_coef), adv, capital).to_numpy( dtype=float, na_value=np.nan @@ -154,8 +182,11 @@ def _path( for loc in range(1, len(weights)): turnover[loc] = np.abs(trades[loc - 1]).sum() / 2.0 cost[loc] = turnover[loc] * (cost_bps / 10_000.0) + base_cost[loc] = cost[loc] + impact_cost[loc] = 0.0 if turnover[loc] > 0: - cost[loc] += unit_impact[loc] * turnover[loc] ** 1.5 + impact_cost[loc] = unit_impact[loc] * turnover[loc] ** 1.5 + cost[loc] += impact_cost[loc] growth = 1.0 + float(gross.iloc[loc]) - cost[loc] if not np.isfinite(growth) or growth <= 0: raise ValueError("cannot rebalance a book with non-positive or non-finite NAV") @@ -166,12 +197,16 @@ def _path( before[cash_loc] += cash_flow trades[loc] = targets[loc] - before / growth cost_series = pd.Series(cost, index=weights.index) - return ( - gross, - gross - cost_series, - cost_series, - pd.Series(turnover, index=weights.index), - pd.DataFrame(trades, index=weights.index, columns=columns), + return _PathResult( + gross=gross, + net=gross - cost_series, + cost=cost_series, + base_cost=pd.Series(base_cost, index=weights.index), + impact_cost=pd.Series(impact_cost, index=weights.index), + turnover=pd.Series(turnover, index=weights.index), + trades=pd.DataFrame(trades, index=weights.index, columns=columns), + contributions=gross_parts, + asset_returns=returns, ) diff --git a/src/quant_timing/contract.py b/src/quant_timing/contract.py index 74cee15..75bed3c 100644 --- a/src/quant_timing/contract.py +++ b/src/quant_timing/contract.py @@ -179,10 +179,15 @@ def validate_standard_run(run_dir: Path) -> RunManifest: raise ValueError(f"unsupported schema {manifest.schema_version}") expected = {*ARTIFACT_SCHEMAS, "metrics"} actual = {record.name for record in manifest.artifacts} - if actual != expected: + if actual != expected or len(manifest.artifacts) != len(expected): raise ValueError(f"artifact set mismatch: {actual ^ expected}") for record in manifest.artifacts: + expected_path = "metrics.json" if record.name == "metrics" else f"{record.name}.csv" + if record.path != expected_path: + raise ValueError(f"artifact path must be canonical: {record.name}") path = standard_dir / record.path + if not path.resolve().is_relative_to(Path(run_dir).resolve()): + raise ValueError(f"artifact escaped run: {record.name}") if not path.is_file() or file_sha256(path) != record.sha256: raise ValueError(f"artifact missing or mutated: {path}") if record.name in ARTIFACT_SCHEMAS: @@ -190,4 +195,11 @@ def validate_standard_run(run_dir: Path) -> RunManifest: required = set(ARTIFACT_SCHEMAS[record.name]) if not required.issubset(columns): raise ValueError(f"artifact schema invalid: {record.name}") + metrics = json.loads((standard_dir / "metrics.json").read_text(encoding="utf-8")) + if "return_attribution" in metrics or "return_attribution" in manifest.tags: + from quant_timing.attribution import SCHEMA, validate_attribution + + if manifest.tags.get("return_attribution") != SCHEMA or "return_attribution" not in metrics: + raise ValueError("attribution manifest binding missing") + validate_attribution(run_dir, metrics) return manifest diff --git a/src/quant_timing/export.py b/src/quant_timing/export.py index 839f952..59c9ce9 100644 --- a/src/quant_timing/export.py +++ b/src/quant_timing/export.py @@ -11,6 +11,7 @@ import yaml from quant_timing import __version__ +from quant_timing.attribution import SCHEMA as ATTRIBUTION_SCHEMA, write_attribution from quant_timing.contract import file_sha256, validate_standard_run, write_standard_run from quant_timing.overlay import FUTURES_COLUMNS from quant_timing.study import StudyResult @@ -87,6 +88,8 @@ def _write_staged_run( _write_frame(out_dir / "style_weights.csv", result.weights) metrics = _metrics(result, decision) metrics["fold_metrics_sha256"] = file_sha256(validation / "fold_metrics.csv") + frames = _standard_frames(result, result.valuation_prices) + metrics["return_attribution"] = write_attribution(result, out_dir, frames["returns"]) if input_context is not None: metrics["input_context"] = input_context write_standard_run( @@ -94,7 +97,7 @@ def _write_staged_run( project="quant-timing", run_id=str(result.config["run_id"]), strategy="position_and_style" if result.config["style"] else "position_only", - frames=_standard_frames(result, result.valuation_prices), + frames=frames, metrics=metrics, config=result.raw_config, code_version=__version__, @@ -110,6 +113,9 @@ def _write_staged_run( "position_return_weight": "previous_decision_weight_for_return_attribution", "cost_unit": "currency", "futures_market_value": "signed_notional_excluded_from_funded_nav", + "return_attribution": ATTRIBUTION_SCHEMA, + "slippage_semantics": "configured_bps_proxy_not_observed_execution_slippage", + "market_impact_semantics": "configured_nonlinear_model", }, ) validate_standard_run(out_dir) @@ -250,6 +256,18 @@ def _standard_frames(result: StudyResult, prices: pd.DataFrame) -> dict[str, pd. "net_return": float(realized["net_return"]), "nav": nav_value, "benchmark_return": float(realized["benchmark_return"]), + "decision_date": _day(realized["decision_date"]), + **{ + key: float(realized[key]) + for key in ( + "base_cost", + "impact_cost", + "matched_gross_return", + "matched_net_return", + "matched_base_cost", + "matched_impact_cost", + ) + }, } ) start_nav = ( @@ -263,8 +281,8 @@ def _standard_frames(result: StudyResult, prices: pd.DataFrame) -> dict[str, pd. "strategy": STRATEGY, "symbol": "BOOK", "commission": 0.0, - "slippage": money, - "market_impact": 0.0, + "slippage": float(realized["base_cost"]) * start_nav, + "market_impact": float(realized["impact_cost"]) * start_nav, "borrow_cost": 0.0, "total_cost": money, } diff --git a/tests/test_attribution.py b/tests/test_attribution.py new file mode 100644 index 0000000..09263e8 --- /dev/null +++ b/tests/test_attribution.py @@ -0,0 +1,198 @@ +import json +from types import SimpleNamespace + +import pandas as pd +import pytest + +from quant_timing.attribution import write_attribution +from quant_timing.book import simulate +from quant_timing.contract import file_sha256, validate_standard_run +from quant_timing.export import _standard_frames, write_run +from quant_timing.study import run_study +from quant_timing.walkforward import iter_folds, score_folds + + +def _manual(weights, matched, prices, *, cash=None, extras=None, bps=100, impact=0.2): + realized = simulate(weights, matched, prices, "A", bps, cash, impact, extras) + folds = score_folds( + realized, iter_folds(prices.index, train_size=1, test_size=2, step_size=1, embargo=0) + ) + return SimpleNamespace(weights=weights, matched_weights=matched, realized=realized, folds=folds) + + +def test_linked_asset_cash_and_cost_contributions_match_hand_calculation(tmp_path): + dates = pd.bdate_range("2026-01-01", periods=3) + prices = pd.DataFrame({"A": [100, 110, 99]}, index=dates) + weights = pd.DataFrame({"A": 0.5, "CASH": 0.5}, index=dates) + matched = pd.DataFrame({"A": 0.75, "CASH": 0.25}, index=dates) + result = _manual(weights, matched, prices, cash=pd.Series([0, 0.02, 0.01], index=dates)) + frames = _standard_frames(result, prices) + payload = write_attribution(result, tmp_path, frames["returns"]) + full = payload["periods"][0] + components = {row["component"]: row for row in full["components"]} + turnover = 0.55 / 1.06 - 0.5 + base_cost = turnover * 0.01 + impact_cost = 0.2 * turnover**1.5 + assert components["A"]["strategy"] == pytest.approx(0.05 - 1.06 * 0.05) + assert components["CASH"]["strategy"] == pytest.approx(0.01 + 1.06 * 0.005) + assert components["base_cost"]["strategy"] == pytest.approx(-1.06 * base_cost) + assert components["impact_cost"]["strategy"] == pytest.approx(-1.06 * impact_cost) + expected = 1.06 * (1 - 0.045 - base_cost - impact_cost) - 1 + assert full["net_return"] == pytest.approx(expected) + assert sum(row["strategy"] for row in full["components"]) == pytest.approx(expected) + assert sum(row["difference"] for row in full["components"]) == pytest.approx( + full["matched_excess_return"] + ) + # The last decision has no following return, and the fold starts from its own unit NAV. + fold = payload["periods"][1] + assert fold["n_decisions"] == 1 + assert fold["first_return_date"] == str(dates[-1].date()) + assert fold["net_return"] == pytest.approx(-0.045 - base_cost - impact_cost) + assert frames["costs"].iloc[-1]["market_impact"] == pytest.approx(1.06 * impact_cost) + assert frames["costs"].iloc[-1]["slippage"] == pytest.approx(1.06 * base_cost) + + +def test_futures_pnl_cash_and_margin_are_separate_without_funded_notional(tmp_path): + dates = pd.bdate_range("2026-01-01", periods=3) + prices = pd.DataFrame({"A": 100.0, "IF": [100, 110, 110]}, index=dates) + weights = pd.DataFrame({"A": 0.9, "IF": -0.5, "CASH": 0.05, "MARGIN": 0.05}, index=dates) + result = _manual( + weights, + weights, + prices, + bps=0, + impact=0, + cash=pd.Series([0, 0.02, 0], index=dates), + extras={"IF": prices["IF"].pct_change()}, + ) + full = write_attribution(result, tmp_path, _standard_frames(result, prices)["returns"])[ + "periods" + ][0] + components = {row["component"]: row for row in full["components"]} + assert components["IF"]["strategy"] == pytest.approx(-0.05) + assert components["IF"]["kind"] == "futures" + assert components["CASH"]["strategy"] == pytest.approx(0.001) + assert components["MARGIN"]["strategy"] == 0 + assert full["net_return"] == pytest.approx(-0.049) + + +def _export(tmp_path, *, overlap=False): + dates = pd.bdate_range("2026-01-01", periods=12) + prices = pd.DataFrame( + {"A": [100, 110, 90, 99, 108, 100, 95, 105, 100, 102, 99, 103]}, index=dates + ) + raw = { + "market": "A", + "position": {"model": "tsmom", "return_window": 1, "floor": 0.5, "cap": 0.5}, + "costs": {"bps": 20, "impact_coef": 0.1}, + "validation": { + "train_size": 2, + "test_size": 3, + "step_size": 1 if overlap else 3, + "embargo": 1, + }, + } + result = run_study(prices, raw) + out = tmp_path / "run" + write_run(result, prices, out) + return out, result + + +def _refresh_metrics(out, metrics): + path = out / "standard/metrics.json" + path.write_text(json.dumps(metrics), encoding="utf-8") + manifest_path = out / "standard/run_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + for record in manifest["artifacts"]: + if record["name"] == "metrics": + record["sha256"] = file_sha256(path) + manifest_path.write_text(json.dumps(manifest), encoding="utf-8") + + +def test_overlapping_folds_are_individually_rebased_not_aggregated(tmp_path): + out, result = _export(tmp_path, overlap=True) + validate_standard_run(out) + metrics = json.loads((out / "standard/metrics.json").read_text(encoding="utf-8")) + attribution = metrics["return_attribution"] + assert attribution["overlapping_folds_are_not_aggregated"] is True + assert attribution["folds_are_separately_executed_accounts"] is False + assert len(attribution["periods"]) == len(result.folds) + 1 + for period, fold in zip(attribution["periods"][1:], result.folds.to_dict(orient="records")): + assert period["net_return"] == pytest.approx(fold["net_return"]) + assert sum(row["strategy"] for row in period["components"]) == pytest.approx( + fold["net_return"] + ) + assert period["first_return_date"] > fold["test_start"] + + +@pytest.mark.parametrize( + "change", + [ + "missing", + "mutated", + "weight", + "pnl", + "decision", + "duplicate", + "cost", + "summary", + "semantics", + ], +) +def test_missing_corrupt_and_internally_inconsistent_attribution_is_rejected(tmp_path, change): + out, _ = _export(tmp_path) + path = out / "attribution/daily.csv" + metrics = json.loads((out / "standard/metrics.json").read_text(encoding="utf-8")) + if change == "missing": + path.unlink() + elif change == "mutated": + path.write_bytes(path.read_bytes() + b"\n") + elif change == "summary": + metrics["return_attribution"]["periods"][0]["components"][0]["strategy"] += 0.01 + _refresh_metrics(out, metrics) + elif change == "semantics": + metrics["return_attribution"]["cost_semantics"]["observed_execution_slippage"] = True + _refresh_metrics(out, metrics) + else: + frame = pd.read_csv(path) + if change == "weight": + frame.loc[0, "return_weight"] += 0.1 + elif change == "pnl": + frame.loc[0, "pnl"] += 0.1 + elif change == "decision": + frame.loc[0, "decision_date"] = frame.loc[0, "date"] + elif change == "duplicate": + frame = pd.concat([frame, frame.iloc[[0]]], ignore_index=True) + elif change == "cost": + loc = frame.index[frame["kind"] == "modeled_cost"][-1] + frame.loc[loc, "contribution"] = 0.1 + frame.loc[loc, "pnl"] = 0.1 * frame.loc[loc, "opening_nav"] + frame.to_csv(path, index=False) + metrics["return_attribution"]["daily"]["sha256"] = file_sha256(path) + metrics["return_attribution"]["daily"]["rows"] = len(frame) + _refresh_metrics(out, metrics) + with pytest.raises(ValueError, match="attribution"): + validate_standard_run(out) + + +def test_export_rejects_unreconciled_native_components_without_publishing(tmp_path): + out, result = _export(tmp_path) + result.realized.loc[result.realized.index[2], "contribution:A"] += 0.01 + with pytest.raises(ValueError, match="attribution"): + write_run(result, result.valuation_prices, tmp_path / "bad") + assert not (tmp_path / "bad").exists() + validate_standard_run(out) + + +def test_existing_runs_without_attribution_remain_readable_but_new_binding_is_required(tmp_path): + out, _ = _export(tmp_path) + metrics = json.loads((out / "standard/metrics.json").read_text(encoding="utf-8")) + del metrics["return_attribution"] + _refresh_metrics(out, metrics) + with pytest.raises(ValueError, match="binding"): + validate_standard_run(out) + path = out / "standard/run_manifest.json" + manifest = json.loads(path.read_text(encoding="utf-8")) + del manifest["tags"]["return_attribution"] + path.write_text(json.dumps(manifest), encoding="utf-8") + validate_standard_run(out)