From 74755de2166d1d9c318531089329a578d3c09aba Mon Sep 17 00:00:00 2001 From: PureSaber <88314620+PureSaber@users.noreply.github.com> Date: Thu, 1 Oct 2026 23:28:28 +0800 Subject: [PATCH] fix: align timing accounting and exports --- README.md | 2 + docs/RESEARCH_CONTRACT.md | 12 ++- src/quant_timing/book.py | 55 +++++++--- src/quant_timing/constraints.py | 11 +- src/quant_timing/contract.py | 4 +- src/quant_timing/export.py | 94 +++++++++++++---- src/quant_timing/position.py | 4 +- src/quant_timing/study.py | 5 + tests/test_accounting_regressions.py | 125 +++++++++++++++++++++++ tests/test_export_accounting.py | 145 +++++++++++++++++++++++++++ tests/test_macro.py | 4 +- 11 files changed, 417 insertions(+), 44 deletions(-) create mode 100644 tests/test_accounting_regressions.py create mode 100644 tests/test_export_accounting.py diff --git a/README.md b/README.md index 7e00c56..8792285 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,8 @@ python -m ruff check src tests | `validation/` | 走步折、泄漏审计和摘要。全样本收益只作描述。 | | `standard/` | 与研究运行契约一致的收益、持仓、目标订单、成本和暴露。 | +持仓文件记录收盘调仓前的实际数量、金额和权重,`return_weight`用于上一笔决策的收益归因。期货和保证金使用各自的估值定义。所有产物验证成功后整体发布;导出失败不会提前发布仓位文件,非空输出目录拒绝覆盖。 + ```mermaid flowchart LR prices[指数与风格价格] --> study[quant-timing] diff --git a/docs/RESEARCH_CONTRACT.md b/docs/RESEARCH_CONTRACT.md index a8c81a9..d420219 100644 --- a/docs/RESEARCH_CONTRACT.md +++ b/docs/RESEARCH_CONTRACT.md @@ -4,7 +4,7 @@ 价格用到决策日收盘为止。`t` 日权重赚取 `t` 到下一交易日的简单收益。从上一权重调到当日权重的成本,按单边换手乘以 `costs.bps`,记在同一根已经实现的下一交易日收益上。 -单边换手是 `0.5 * sum(abs(Δweight))`。市场和现金对调一遍,换手是 1,不是 0.5。 +单边换手是`0.5 * sum(abs(目标权重 - 调仓前权重))`。调仓前权重先按上一笔决策持仓和当日收益更新,并除以扣除已记账费用后的净资产。费用从现金扣除,期货盈亏结算到现金;期货名义本金不作为已投入资本。目标权重不变也可能需要再平衡。成本、参与率估计和订单导出使用同一组交易差额。市场和现金对调一遍,换手是1。 第一天是建仓日记账,换手记 0,没有实现收益。之后的调仓才计费。满仓市场基准在每一期都是市场本身的简单收益,不把策略的调仓费重复扣到基准上。 @@ -18,7 +18,9 @@ 对应测试是 `tests/test_book.py`。 -`style_weights.csv` 和 `position_history.csv` 按决策日记录目标。`standard/positions.csv` 与 `standard/returns.csv` 使用同一天时,持仓是赚取当天收益的上一笔决策,不能用当天的新目标解释当天收益。标准订单仍记在决策日,状态是 `target`。 +`style_weights.csv`和`position_history.csv`按决策日记录目标。`standard/positions.csv`记录当日收盘、扣除已记账费用后的调仓前持仓:`weight`、`market_value`、`quantity`均从同一实际账本计算。新增`return_weight`单独记录赚取当日收益的上一笔决策权重,用于收益归因。把持仓数量加上同日订单的有符号数量,应得到目标持仓数量。订单仍记在决策日,状态是`target`。 + +期货估值使用研究过程实际采用的合约行情,支持独立行情文件和同表行情列。期货`market_value`是有符号名义金额,不加入已投入资本的净值求和;`CASH`和`MARGIN`以账户货币计量,单位价格为1。未持有、未交易的缺失合约价格不生成虚构估值,活跃持仓或订单缺少有效价格则导出失败。 ## 补充的仓位和风格 @@ -44,6 +46,8 @@ 风格对照是同一条仓位路径下的组内等权。它和策略的差额只来自倾斜,不来自总仓位变化。 +回撤控制的风格收益使用上一笔决策的风格权重。风格信号首次就绪当天,已经实现的收益仍来自前一日市场袖套;切换当天的新风格权重只影响下一期。该控制沿用未叠加期货、未扣交易成本的仓位收益路径。 + ## 宏观 接受 `quant-regime` 宏观上下文的 `complete`、`values`、`unavailable`。不完整时必须显式选择: @@ -61,4 +65,6 @@ ## 标准产物 -`standard/` 使用研究契约 v1 的列:`returns`、`positions`、`orders`、`costs`、`exposures`、`metrics`,并在 `run_manifest.json` 里记录哈希。订单状态是 `target`,数量是研究目标,不是已路由委托。目录一旦写成就拒绝覆盖。 +`standard/`使用研究契约v1的基础列,并在`positions`追加`return_weight`。`run_manifest.json`记录产物哈希及原始价格、完整估值价格快照。订单数量为研究单位下的调仓差额,状态为`target`。 + +全部文件先写到同一父目录下的临时目录,标准产物验证通过后才生成发布文件,最后一次重命名发布整个运行目录。导出或验证失败不会留下可消费的`position_scale.json`。输出目录必须不存在或为空;已有文件和已完成运行均拒绝覆盖。 diff --git a/src/quant_timing/book.py b/src/quant_timing/book.py index 455778d..36e1341 100644 --- a/src/quant_timing/book.py +++ b/src/quant_timing/book.py @@ -1,5 +1,6 @@ from __future__ import annotations +import numpy as np import pandas as pd from quant_timing.style import style_sleeves @@ -88,8 +89,8 @@ def simulate( asset[name] = series.reindex(asset.index) if "MARGIN" in weights.columns: asset["MARGIN"] = 0.0 - gross, net, cost, turnover = _path(weights, asset, cost_bps, impact_coef, adv, capital) - matched_gross, matched_net, matched_cost, matched_turnover = _path( + 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 ) frame = pd.DataFrame( @@ -107,9 +108,10 @@ def simulate( }, index=weights.index, ) - frame.index.name = "date" + frame.index = frame.index.rename("date") frame["nav"] = _nav(frame["net_return"]) - return frame + # Decision-date deltas are also the source for research order exports. + return pd.concat([frame, trades.rename_axis("date").add_prefix("trade:")], axis=1) def _path( @@ -119,7 +121,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]: +) -> tuple[pd.Series, pd.Series, pd.Series, pd.Series, pd.DataFrame]: columns = list(weights.columns) returns = asset.reindex(columns=columns) if "CASH" in returns.columns: @@ -135,13 +137,42 @@ def _path( raise ValueError(f"missing futures return while holding {column}") gross_parts.loc[idle, column] = gross_parts.loc[idle, column].fillna(0.0) gross = gross_parts.sum(axis=1, min_count=len(columns)) - traded = weights.diff().abs().sum(axis=1) / 2.0 - traded.iloc[0] = 0.0 - turnover = traded.shift(1) - cost = turnover * (cost_bps / 10_000.0) - if impact_coef: - cost = cost + _impact(turnover, float(impact_coef), adv, capital) - return gross, gross - cost, cost, turnover + targets = weights.to_numpy(dtype=float) + parts = gross_parts.to_numpy(dtype=float) + trades = np.zeros_like(targets) + turnover = np.full(len(weights), np.nan) + 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 + ) + if impact_coef + else np.zeros(len(weights)) + ) + cash_loc = columns.index("CASH") if "CASH" in columns else None + futures_locs = [columns.index(name) for name in columns if name in _FUTURES_COLUMNS] + 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) + if turnover[loc] > 0: + cost[loc] += unit_impact[loc] * turnover[loc] ** 1.5 + 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") + before = targets[loc - 1] + parts[loc] + # Futures are notionals; variation margin is cash, not funded principal. + cash_flow = parts[loc, futures_locs].sum() - cost[loc] + if cash_loc is not None: + 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), + ) def _impact( diff --git a/src/quant_timing/constraints.py b/src/quant_timing/constraints.py index 47bbd0e..db30389 100644 --- a/src/quant_timing/constraints.py +++ b/src/quant_timing/constraints.py @@ -48,13 +48,14 @@ def full_equity_return( market: str, internal: pd.DataFrame | None, ) -> pd.Series: - """Return of a fully invested sleeve mix. The position scale is applied later.""" + """Return earned by the previous decision's sleeve mix, before position scaling.""" returns = prices.pct_change() if internal is None: return returns[market] sleeves = list(internal.columns) - mix = (internal.fillna(0.0) * returns[sleeves]).sum(axis=1, min_count=len(sleeves)) - ready = internal.notna().all(axis=1) + held = internal.shift(1) + mix = (held.fillna(0.0) * returns[sleeves]).sum(axis=1, min_count=len(sleeves)) + ready = held.notna().all(axis=1) equity = returns[market].copy() equity.loc[ready] = mix.loc[ready] return equity @@ -77,7 +78,9 @@ def apply_earnings_yield_cap( percentile = earnings_yield.rolling(lookback).apply(_last_percent_rank, raw=True) capped = scale.astype(float).copy() expensive = percentile.notna() & percentile.lt(expensive_percentile) - capped.loc[expensive] = np.minimum(capped.loc[expensive].to_numpy(dtype=float), float(scale_cap)) + capped.loc[expensive] = np.minimum( + capped.loc[expensive].to_numpy(dtype=float), float(scale_cap) + ) return capped diff --git a/src/quant_timing/contract.py b/src/quant_timing/contract.py index 143cb65..74cee15 100644 --- a/src/quant_timing/contract.py +++ b/src/quant_timing/contract.py @@ -125,7 +125,9 @@ def write_standard_run( if list(frame.columns)[: len(columns)] != list(columns): raise ValueError(f"artifact columns drifted: {name}") metrics_path = standard_dir / "metrics.json" - metrics_path.write_text(json.dumps(metrics, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") + metrics_path.write_text( + json.dumps(metrics, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" + ) records.append( ArtifactRecord( name="metrics", diff --git a/src/quant_timing/export.py b/src/quant_timing/export.py index b3bf779..2894bce 100644 --- a/src/quant_timing/export.py +++ b/src/quant_timing/export.py @@ -2,14 +2,17 @@ import hashlib import json +import math from pathlib import Path +from tempfile import TemporaryDirectory from typing import Any import pandas as pd import yaml from quant_timing import __version__ -from quant_timing.contract import write_standard_run +from quant_timing.contract import validate_standard_run, write_standard_run +from quant_timing.overlay import FUTURES_COLUMNS from quant_timing.study import StudyResult STRATEGY = "timing" @@ -47,12 +50,27 @@ def exit_code(summary: dict[str, Any], decision: dict[str, Any]) -> int: def write_run(result: StudyResult, prices: pd.DataFrame, out_dir: Path) -> dict[str, Any]: + """Validate a complete staged run, then publish it with one directory rename.""" + out_dir = Path(out_dir) + _require_empty_destination(out_dir) + out_dir.parent.mkdir(parents=True, exist_ok=True) + with TemporaryDirectory(prefix=f".{out_dir.name}-", dir=out_dir.parent) as directory: + staged = Path(directory) + decision = _write_staged_run(result, prices, staged) + _require_empty_destination(out_dir) + if out_dir.exists(): + out_dir.rmdir() # Removes only an empty destination; never existing run contents. + staged.rename(out_dir) + return decision + + +def _require_empty_destination(path: Path) -> None: + if path.exists() and (not path.is_dir() or any(path.iterdir())): + raise FileExistsError(f"refusing to overwrite a nonempty run destination: {path}") + + +def _write_staged_run(result: StudyResult, prices: pd.DataFrame, out_dir: Path) -> dict[str, Any]: decision = gate_decision(result.latest, result.summary) - standard_dir = out_dir / "standard" - if standard_dir.exists(): - raise FileExistsError(f"standard run already exists: {standard_dir}") - if decision["action"] != "use" and (out_dir / "position_scale.json").exists(): - raise FileExistsError("refusing to leave a stale position_scale.json beside a blocked decision") out_dir.mkdir(parents=True, exist_ok=True) validation = out_dir / "validation" validation.mkdir(exist_ok=True) @@ -61,27 +79,35 @@ def write_run(result: StudyResult, prices: pd.DataFrame, out_dir: Path) -> dict[ _write_json(validation / "leakage_audit.json", result.leakage) _write_frame(out_dir / "position_history.csv", result.position) _write_frame(out_dir / "style_weights.csv", result.weights) - _write_json(out_dir / "decision.json", decision) - if decision["action"] == "use": - _write_json(out_dir / "position_scale.json", _paper_sim_payload(decision)) - _write_overlay(out_dir / "portfolio_overlay.yaml", decision) metrics = _metrics(result, decision) write_standard_run( out_dir, 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, prices), + frames=_standard_frames(result, result.valuation_prices), metrics=metrics, config=result.raw_config, code_version=__version__, - dataset_snapshots={"prices": _prices_sha256(prices)}, + dataset_snapshots={ + "prices": _prices_sha256(prices), + "valuation_prices": _prices_sha256(result.valuation_prices), + }, tags={ "orders": "research_target_not_routed", "asset_class": "index_style", "acceptance": "walk_forward_folds", + "positions": "close_pretrade_after_costs", + "position_return_weight": "previous_decision_weight_for_return_attribution", + "cost_unit": "currency", + "futures_market_value": "signed_notional_excluded_from_funded_nav", }, ) + validate_standard_run(out_dir) + _write_json(out_dir / "decision.json", decision) + if decision["action"] == "use": + _write_overlay(out_dir / "portfolio_overlay.yaml", decision) + _write_json(out_dir / "position_scale.json", _paper_sim_payload(decision)) return decision @@ -123,22 +149,31 @@ def _standard_frames(result: StudyResult, prices: pd.DataFrame) -> dict[str, pd. exposure_rows = [] previous_nav = nav.shift(1) held = result.weights.shift(1) - held_scale = result.position["position_scale"].shift(1) - for stamp, weight_row in held.iterrows(): - if weight_row.isna().any(): - continue + trades = result.realized[[f"trade:{s}" for s in result.weights.columns]].copy() + trades.columns = result.weights.columns + before = result.weights - trades + equity_columns = [ + symbol + for symbol in result.weights.columns + if symbol not in FUTURES_COLUMNS | {"CASH", "MARGIN"} + ] + for stamp, weight_row in before.iloc[1:].iterrows(): day = _day(stamp) nav_value = float(nav.loc[stamp]) for symbol, weight in weight_row.items(): weight_value = float(weight) - price = 1.0 if symbol == "CASH" else float(prices.loc[stamp, symbol]) market_value = weight_value * nav_value + quantity = ( + market_value / _valuation_price(prices, stamp, symbol) + if abs(weight_value) > 1e-12 + else 0.0 + ) position_rows.append( { "date": day, "strategy": STRATEGY, "symbol": symbol, - "quantity": market_value / price, + "quantity": quantity, "market_value": market_value, "weight": weight_value, "side": "long" @@ -146,6 +181,7 @@ def _standard_frames(result: StudyResult, prices: pd.DataFrame) -> dict[str, pd. else "short" if weight_value < -1e-12 else "flat", + "return_weight": float(held.loc[stamp, symbol]), } ) exposure_rows.append( @@ -163,7 +199,7 @@ def _standard_frames(result: StudyResult, prices: pd.DataFrame) -> dict[str, pd. "strategy": STRATEGY, "exposure_type": "gross", "name": "equity", - "value": float(held_scale.loc[stamp]), + "value": float(weight_row[equity_columns].abs().sum()), } ) realized = result.realized.loc[stamp] @@ -178,7 +214,9 @@ def _standard_frames(result: StudyResult, prices: pd.DataFrame) -> dict[str, pd. "benchmark_return": float(realized["benchmark_return"]), } ) - start_nav = float(previous_nav.loc[stamp]) if pd.notna(previous_nav.loc[stamp]) else nav_value + start_nav = ( + float(previous_nav.loc[stamp]) if pd.notna(previous_nav.loc[stamp]) else nav_value + ) fraction = 0.0 if pd.isna(realized["cost"]) else float(realized["cost"]) money = fraction * start_nav cost_rows.append( @@ -195,13 +233,13 @@ def _standard_frames(result: StudyResult, prices: pd.DataFrame) -> dict[str, pd. ) for loc in range(1, len(result.weights)): stamp = result.weights.index[loc] - delta = result.weights.iloc[loc] - result.weights.iloc[loc - 1] + delta = trades.loc[stamp] nav_value = float(nav.loc[stamp]) for symbol, change in delta.items(): change_value = float(change) if abs(change_value) <= 1e-12: continue - price = 1.0 if symbol == "CASH" else float(prices.loc[stamp, symbol]) + price = _valuation_price(prices, stamp, symbol) order_rows.append( { "timestamp": _day(stamp), @@ -223,6 +261,18 @@ def _standard_frames(result: StudyResult, prices: pd.DataFrame) -> dict[str, pd. } +def _valuation_price(prices: pd.DataFrame, stamp: object, symbol: str) -> float: + # CASH and MARGIN are denominated in account currency, not traded price indices. + if symbol in {"CASH", "MARGIN"}: + return 1.0 + if symbol not in prices.columns: + raise ValueError(f"missing valuation price for {symbol}") + price = float(prices.loc[stamp, symbol]) + if not math.isfinite(price) or price <= 0: + raise ValueError(f"invalid valuation price for {symbol} at {stamp}") + return price + + def _prices_sha256(prices: pd.DataFrame) -> str: payload = prices.to_csv(date_format="%Y-%m-%d").encode("utf-8") return hashlib.sha256(payload).hexdigest() diff --git a/src/quant_timing/position.py b/src/quant_timing/position.py index b04f8f1..4b3b212 100644 --- a/src/quant_timing/position.py +++ b/src/quant_timing/position.py @@ -18,7 +18,9 @@ def _finite(value: object) -> float: return number -def classify_position(vol_percentile: object, window_return: object, rules: dict) -> tuple[str, float]: +def classify_position( + vol_percentile: object, window_return: object, rules: dict +) -> tuple[str, float]: """Map features known on the decision date to a long-only scale. High volatility takes priority over a negative window return. Incomplete features stay in diff --git a/src/quant_timing/study.py b/src/quant_timing/study.py index 53523bb..642b6d4 100644 --- a/src/quant_timing/study.py +++ b/src/quant_timing/study.py @@ -35,6 +35,7 @@ class StudyResult: summary: dict[str, Any] leakage: dict[str, Any] latest: dict[str, Any] + valuation_prices: pd.DataFrame def run_study( @@ -86,10 +87,13 @@ def run_study( drawdown_floor=float(constraints["drawdown_floor"]), ) weights, matched = assemble_weights(prices, position, style, internal, config["market"]) + valuation_prices = prices.copy() extra_returns = None overlay = config["overlay"] if overlay["mode"] == "futures": futures = _futures_frame(futures_prices, futures_price, prices.index, overlay["contracts"]) + for name in futures.columns: + valuation_prices[name] = futures[name] betas, fallback, available = _hedge_inputs( prices, futures, list(weights.columns), int(overlay["beta_window"]) ) @@ -167,6 +171,7 @@ def run_study( summary=summary, leakage=leakage, latest=latest, + valuation_prices=valuation_prices, ) diff --git a/tests/test_accounting_regressions.py b/tests/test_accounting_regressions.py new file mode 100644 index 0000000..d16f21a --- /dev/null +++ b/tests/test_accounting_regressions.py @@ -0,0 +1,125 @@ +from types import SimpleNamespace + +import pandas as pd +import pytest + +from quant_timing.book import simulate +from quant_timing.constraints import full_equity_return +from quant_timing.export import _standard_frames +from quant_timing.study import run_study + + +def test_style_return_uses_previous_mix_including_first_ready_day(): + dates = pd.bdate_range("2026-09-01", periods=4) + prices = pd.DataFrame( + {"market": [100, 90, 90, 90], "A": [100, 100, 80, 80], "B": 100}, index=dates + ) + internal = pd.DataFrame( + {"A": [float("nan"), 0.7, 0.3, 0.3], "B": [float("nan"), 0.3, 0.7, 0.7]}, index=dates + ) + result = full_equity_return(prices, "market", internal) + assert result.iloc[1:].tolist() == pytest.approx([-0.1, -0.14, 0.0]) + + +def test_style_switch_cuts_exposure_on_realized_drawdown(): + dates = pd.bdate_range("2026-09-01", periods=12) + prices = pd.DataFrame( + {"market": range(100, 112), "A": [100.0] * 3 + [80.0] * 9, "B": 100.0}, index=dates + ) + signals = pd.DataFrame({"rotation": [1.0] * 3 + [-1.0] * 9}, index=dates) + config = { + "market": "market", + "position": {"model": "tsmom", "return_window": 1, "floor": 1.0, "cap": 1.0}, + "style": { + "return_window": 1, + "tilt": 0.7, + "threshold": 0.0, + "pairs": [ + { + "name": "rotation", + "left": "A", + "right": "B", + "group_weight": 1.0, + "signal": "revision", + } + ], + }, + "constraints": {"drawdown_line": 0.1, "drawdown_floor": 0.2}, + "costs": {"bps": 0.0}, + "validation": {"train_size": 2, "test_size": 2, "step_size": 2, "embargo": 0}, + } + result = run_study(prices, config, signal_panel=signals, audit=True) + assert result.realized["net_return"].iloc[3] == pytest.approx(-0.14) + assert result.position["position_scale"].iloc[3] == pytest.approx(0.2) + assert result.weights["CASH"].iloc[3] == pytest.approx(0.8) + assert result.leakage["passed"] + assert result.summary["status"] == "complete" + + +def test_drift_cost_orders_and_fee_funded_cash_share_one_trade_path(): + dates = pd.bdate_range("2026-09-01", periods=4) + prices = pd.DataFrame({"A": [100.0, 110.0, 110.0, 110.0], "B": 100.0}, index=dates) + weights = pd.DataFrame({"A": 0.5, "B": 0.5, "CASH": 0.0}, index=dates) + ledger = simulate(weights, weights, prices, "A", cost_bps=100.0) + assert prices.index.name is None + assert weights.index.name is None + assert ledger.index.name == "date" + traded = 0.5 * (abs(0.5 - 0.55 / 1.05) + abs(0.5 - 0.5 / 1.05)) + assert ledger["turnover"].iloc[2] == pytest.approx(traded) + assert ledger["cost"].iloc[2] == pytest.approx(traded * 0.01) + assert ledger["matched_cost"].iloc[2] == pytest.approx(traded * 0.01) + # Fees leave a cash debit; the following rebalance funds it by selling assets. + cost = traded * 0.01 + assert ledger["turnover"].iloc[3] == pytest.approx(cost / (1 - cost)) + frames = _standard_frames( + SimpleNamespace( + weights=weights, + realized=ledger, + position=pd.DataFrame({"position_scale": 1.0}, index=dates), + ), + prices, + ) + orders = frames["orders"] + day = orders[orders["timestamp"] == "2026-09-02"].set_index("symbol") + assert day.loc["A", "side"] == "sell" + assert day.loc["B", "side"] == "buy" + assert day.loc["A", "quantity"] * 110 == pytest.approx(0.025) + assert day.loc["B", "quantity"] * 100 == pytest.approx(0.025) + + +def test_futures_pnl_settles_to_cash_before_rebalancing(): + dates = pd.bdate_range("2026-09-01", periods=3) + prices = pd.DataFrame({"A": 100.0}, index=dates) + weights = pd.DataFrame({"A": 0.9, "IF": -0.5, "CASH": 0.05, "MARGIN": 0.05}, index=dates) + ledger = simulate( + weights, + weights, + prices, + "A", + 0.0, + extra_returns={"IF": pd.Series([float("nan"), 0.1, 0.0], index=dates)}, + ) + # NAV falls to .95; futures settle -.05 into cash, margin remains .05. + before = [0.9 / 0.95, -0.55 / 0.95, 0.0, 0.05 / 0.95] + expected = sum(abs(a - b) for a, b in zip(weights.iloc[1], before)) / 2 + assert ledger["turnover"].iloc[2] == pytest.approx(expected) + + +def test_cash_yield_drift_and_impact_use_decision_day_activity(): + dates = pd.bdate_range("2026-09-01", periods=3) + prices = pd.DataFrame({"A": 100.0}, index=dates) + weights = pd.DataFrame({"A": 0.5, "CASH": 0.5}, index=dates) + ledger = simulate( + weights, + weights, + prices, + "A", + 0.0, + cash_returns=pd.Series([0.0, 0.1, 0.0], index=dates), + impact_coef=0.2, + adv=pd.Series([100.0, 100.0, 10000.0], index=dates), + capital=50.0, + ) + traded = 0.5 - 0.5 / 1.05 + assert ledger["turnover"].iloc[2] == pytest.approx(traded) + assert ledger["cost"].iloc[2] == pytest.approx(0.2 * traded * (traded * 50 / 100) ** 0.5) diff --git a/tests/test_export_accounting.py b/tests/test_export_accounting.py new file mode 100644 index 0000000..7cd2198 --- /dev/null +++ b/tests/test_export_accounting.py @@ -0,0 +1,145 @@ +from types import SimpleNamespace + +import pandas as pd +import pytest +import yaml + +from quant_timing import export +from quant_timing.book import simulate +from quant_timing.cli import main +from quant_timing.contract import validate_standard_run +from quant_timing.study import run_study + + +def config(): + return { + "market": "market", + "position": {"model": "tsmom", "return_window": 1, "floor": 0.5, "cap": 0.5}, + "overlay": {"mode": "futures", "contracts": ["IF"], "margin_rate": 0.1, "beta_window": 2}, + "costs": {"bps": 10.0}, + "validation": {"train_size": 2, "test_size": 2, "step_size": 2, "embargo": 0}, + } + + +@pytest.mark.parametrize("separate_futures", [False, True]) +def test_futures_cli_exports_complete_valued_book_before_publishing(tmp_path, separate_futures): + dates = pd.bdate_range("2026-09-01", periods=12) + prices = pd.DataFrame({"date": dates, "market": range(100, 112)}) + raw = config() + if separate_futures: + future_path = tmp_path / "futures.csv" + pd.DataFrame({"date": dates, "IF": range(100, 112)}).to_csv(future_path, index=False) + raw["futures"] = {"path": str(future_path)} + else: + prices["IF"] = range(100, 112) + price_path = tmp_path / "prices.csv" + prices.to_csv(price_path, index=False) + raw["input"] = {"path": str(price_path)} + cfg = tmp_path / "config.yaml" + cfg.write_text(yaml.safe_dump(raw)) + out = tmp_path / "run" + assert main(["run", "--config", str(cfg), "--out", str(out)]) == 0 + manifest = validate_standard_run(out) + assert "valuation_prices" in manifest.dataset_snapshots + assert manifest.tags["cost_unit"] == "currency" + assert (out / "position_scale.json").is_file() + positions = pd.read_csv(out / "standard/positions.csv") + active = positions[positions["symbol"] == "IF"] + assert active["quantity"].lt(0).any() + margin = positions[positions["symbol"] == "MARGIN"] + assert margin["quantity"].equals(margin["market_value"]) + assert positions[["quantity", "market_value", "weight"]].notna().all().all() + funded = ( + positions[~positions.symbol.isin(["IF", "IC", "IM"])].groupby("date").market_value.sum() + ) + nav = pd.read_csv(out / "standard/returns.csv").set_index("date").nav + assert funded.tolist() == pytest.approx(nav.loc[funded.index].tolist()) + + +@pytest.mark.parametrize("failure_stage", ["write_standard_run", "validate_standard_run"]) +def test_failed_validation_publishes_no_run_or_scale(tmp_path, monkeypatch, failure_stage): + dates = pd.bdate_range("2026-09-01", periods=12) + prices = pd.DataFrame({"market": range(100, 112)}, index=dates) + raw = config() + raw.pop("overlay") + result = run_study(prices, raw) + out = tmp_path / "run" + + def reject(*args, **kwargs): + assert not (out / "position_scale.json").exists() + raise ValueError("injected artifact validation failure") + + monkeypatch.setattr(export, failure_stage, reject) + with pytest.raises(ValueError, match="artifact validation failure"): + export.write_run(result, prices, out) + assert not out.exists() + + +def test_export_preserves_existing_files_when_destination_changes_during_staging( + tmp_path, monkeypatch +): + dates = pd.bdate_range("2026-09-01", periods=12) + prices = pd.DataFrame({"market": range(100, 112)}, index=dates) + raw = config() + raw.pop("overlay") + result = run_study(prices, raw) + out = tmp_path / "run" + out.mkdir() + original_validate = export.validate_standard_run + + def occupy(staged): + original_validate(staged) + (out / "existing.txt").write_text("preserve me") + + monkeypatch.setattr(export, "validate_standard_run", occupy) + with pytest.raises(FileExistsError, match="nonempty"): + export.write_run(result, prices, out) + assert (out / "existing.txt").read_text() == "preserve me" + assert not (out / "position_scale.json").exists() + assert not (out / "standard").exists() + + +def test_missing_active_valuation_fails_before_publication(tmp_path): + dates = pd.bdate_range("2026-09-01", periods=12) + prices = pd.DataFrame({"market": range(100, 112)}, index=dates) + futures = pd.DataFrame({"IF": range(100, 112)}, index=dates) + result = run_study(prices, config(), futures_prices=futures) + result.valuation_prices.loc[dates[2], "IF"] = float("nan") + with pytest.raises(ValueError, match="valuation price for IF"): + export.write_run(result, prices, tmp_path / "run") + assert not (tmp_path / "run").exists() + + +@pytest.mark.parametrize("bps", [0.0, 100.0]) +def test_pretrade_positions_and_orders_conserve_units_through_full_exit(bps): + dates = pd.bdate_range("2026-09-01", periods=4) + prices = pd.DataFrame({"A": [100.0, 110.0, 110.0, 110.0], "B": 100.0}, index=dates) + weights = pd.DataFrame( + {"A": [0.5, 0.0, 0.0, 0.5], "B": [0.5, 1.0, 1.0, 0.5], "CASH": 0.0}, index=dates + ) + ledger = simulate(weights, weights, prices, "A", bps) + frames = export._standard_frames( + SimpleNamespace( + weights=weights, + realized=ledger, + position=pd.DataFrame({"position_scale": 1.0}, index=dates), + ), + prices, + ) + pos = frames["positions"].set_index(["date", "symbol"]) + assert pos.loc[("2026-09-02", "A"), "quantity"] == pytest.approx(0.005) + assert pos.loc[("2026-09-02", "A"), "market_value"] == pytest.approx(0.55) + assert pos.loc[("2026-09-02", "A"), "return_weight"] == 0.5 + assert pos.loc[("2026-09-02", "A"), "weight"] == pytest.approx(0.55 / 1.05) + for date in dates[1:]: + day = str(date.date()) + orders = frames["orders"].query("timestamp == @day") + for symbol in weights.columns: + previous = pos.loc[(day, symbol), "quantity"] + changes = orders[orders.symbol == symbol] + delta = sum( + row.quantity * (1 if row.side == "buy" else -1) for row in changes.itertuples() + ) + price = 1.0 if symbol == "CASH" else prices.loc[date, symbol] + target = weights.loc[date, symbol] * ledger.loc[date, "nav"] / price + assert previous + delta == pytest.approx(target, abs=1e-12) diff --git a/tests/test_macro.py b/tests/test_macro.py index a0ccc76..596372d 100644 --- a/tests/test_macro.py +++ b/tests/test_macro.py @@ -30,7 +30,9 @@ def test_explicit_rule_can_only_cap_scale() -> None: def test_incomplete_macro_requires_a_policy_and_never_zero_fills() -> None: - context = normalize_macro({"complete": False, "unavailable": {"CPI": "missing_or_stale"}, "values": {}}) + context = normalize_macro( + {"complete": False, "unavailable": {"CPI": "missing_or_stale"}, "values": {}} + ) with pytest.raises(ValueError, match="incomplete_policy"): apply_macro(1.0, context, {"incomplete_policy": None, "rules": []}) scale, policy = apply_macro(