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 @@ -39,6 +39,8 @@ python -m ruff check src tests
| `validation/` | 走步折、泄漏审计和摘要。全样本收益只作描述。 |
| `standard/` | 与研究运行契约一致的收益、持仓、目标订单、成本和暴露。 |

持仓文件记录收盘调仓前的实际数量、金额和权重,`return_weight`用于上一笔决策的收益归因。期货和保证金使用各自的估值定义。所有产物验证成功后整体发布;导出失败不会提前发布仓位文件,非空输出目录拒绝覆盖。

```mermaid
flowchart LR
prices[指数与风格价格] --> study[quant-timing]
Expand Down
12 changes: 9 additions & 3 deletions docs/RESEARCH_CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

价格用到决策日收盘为止。`t` 日权重赚取 `t` 到下一交易日的简单收益。从上一权重调到当日权重的成本,按单边换手乘以 `costs.bps`,记在同一根已经实现的下一交易日收益上。

单边换手是 `0.5 * sum(abs(Δweight))`。市场和现金对调一遍,换手是 1,不是 0.5。
单边换手是`0.5 * sum(abs(目标权重 - 调仓前权重))`。调仓前权重先按上一笔决策持仓和当日收益更新,并除以扣除已记账费用后的净资产。费用从现金扣除,期货盈亏结算到现金;期货名义本金不作为已投入资本。目标权重不变也可能需要再平衡。成本、参与率估计和订单导出使用同一组交易差额。市场和现金对调一遍,换手是1。

第一天是建仓日记账,换手记 0,没有实现收益。之后的调仓才计费。满仓市场基准在每一期都是市场本身的简单收益,不把策略的调仓费重复扣到基准上。

Expand All @@ -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。未持有、未交易的缺失合约价格不生成虚构估值,活跃持仓或订单缺少有效价格则导出失败。

## 补充的仓位和风格

Expand All @@ -44,6 +46,8 @@

风格对照是同一条仓位路径下的组内等权。它和策略的差额只来自倾斜,不来自总仓位变化。

回撤控制的风格收益使用上一笔决策的风格权重。风格信号首次就绪当天,已经实现的收益仍来自前一日市场袖套;切换当天的新风格权重只影响下一期。该控制沿用未叠加期货、未扣交易成本的仓位收益路径。

## 宏观

接受 `quant-regime` 宏观上下文的 `complete`、`values`、`unavailable`。不完整时必须显式选择:
Expand All @@ -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`。输出目录必须不存在或为空;已有文件和已完成运行均拒绝覆盖。
55 changes: 43 additions & 12 deletions src/quant_timing/book.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import numpy as np
import pandas as pd

from quant_timing.style import style_sleeves
Expand Down Expand Up @@ -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(
Expand All @@ -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(
Expand All @@ -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:
Expand All @@ -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(
Expand Down
11 changes: 7 additions & 4 deletions src/quant_timing/constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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


Expand Down
4 changes: 3 additions & 1 deletion src/quant_timing/contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
94 changes: 72 additions & 22 deletions src/quant_timing/export.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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)
Expand All @@ -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


Expand Down Expand Up @@ -123,29 +149,39 @@ 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"
if weight_value > 1e-12
else "short"
if weight_value < -1e-12
else "flat",
"return_weight": float(held.loc[stamp, symbol]),
}
)
exposure_rows.append(
Expand All @@ -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]
Expand All @@ -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(
Expand All @@ -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),
Expand All @@ -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()
Expand Down
4 changes: 3 additions & 1 deletion src/quant_timing/position.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading