Coverage for execution/cost_models.py: 100%
55 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Composable trading-cost models (V6.6.5, #345): what one trade costs, in basis points of its notional.
3Each model answers one question, `cost_bps(trade_value, adv_usd=..., daily_vol=...)`, and models add up in a
4`CompositeCostModel`. The square-root impact term is `evaluation.impact_model.compute_sqrt_impact_bps`, and the presets use
5the fees the live path charges (`evaluation.target_weights_engine.coinbase_taker_bps`, the IB equity terms), so a research
6cost and a live cost are the same numbers.
8 model = CompositeCostModel((LinearCostModel(commission_bps=1.5, half_spread_bps=2.0), SquareRootImpactModel(eta=0.5)))
9 model.cost_bps(50_000.0, adv_usd=20e6, daily_vol=0.02)
10"""
12from __future__ import annotations
14import math
15from collections.abc import Sequence
16from dataclasses import dataclass, field
17from typing import Protocol, runtime_checkable
19from evaluation.impact_model import compute_sqrt_impact_bps
21__all__ = [
22 "CostModel", "LinearCostModel", "SquareRootImpactModel", "CompositeCostModel", "cost_usd", "coinbase_model", "ib_equity_model",
23]
26def _finite_non_negative(value: float | None) -> float | None:
27 if value is None:
28 return None
29 try:
30 number = float(value)
31 except (TypeError, ValueError):
32 return None
33 return number if math.isfinite(number) and number >= 0.0 else None
36@runtime_checkable
37class CostModel(Protocol):
38 """Anything with `cost_bps(trade_value, *, adv_usd, daily_vol) -> float` (never negative, never NaN)."""
40 def cost_bps(self, trade_value: float, *, adv_usd: float | None = None, daily_vol: float | None = None) -> float: ...
43@dataclass(frozen=True)
44class LinearCostModel:
45 """A commission and half the quoted spread, both per side in bps, plus an optional dollar minimum per trade."""
47 commission_bps: float = 0.0
48 half_spread_bps: float = 0.0
49 min_fee_usd: float = 0.0
51 def cost_bps(self, trade_value: float, *, adv_usd: float | None = None, daily_vol: float | None = None) -> float:
52 notional = _finite_non_negative(abs(float(trade_value))) if trade_value is not None else None
53 if not notional:
54 return 0.0
55 bps = (_finite_non_negative(self.commission_bps) or 0.0) + (_finite_non_negative(self.half_spread_bps) or 0.0)
56 minimum = _finite_non_negative(self.min_fee_usd) or 0.0
57 floor_bps = minimum / notional * 1e4 if minimum > 0.0 else 0.0
58 # the minimum is charged up to the whole notional, so a dust trade costs at most itself and never inf bps
59 return max(bps, min(floor_bps, 1e4) if math.isfinite(floor_bps) else 1e4)
62@dataclass(frozen=True)
63class SquareRootImpactModel:
64 """Temporary impact `eta * daily_vol * sqrt(trade / ADV)`, in bps. Zero when ADV or volatility is unknown, so an
65 unknown is visible as a missing input rather than a guessed cost."""
67 eta: float = 0.5
69 def cost_bps(self, trade_value: float, *, adv_usd: float | None = None, daily_vol: float | None = None) -> float:
70 notional = _finite_non_negative(abs(float(trade_value))) if trade_value is not None else None
71 adv, vol, eta = _finite_non_negative(adv_usd), _finite_non_negative(daily_vol), _finite_non_negative(self.eta)
72 if not notional or not adv or not vol or eta is None:
73 return 0.0
74 value = compute_sqrt_impact_bps(trade_size_fraction=1.0, daily_volatility=vol, avg_daily_dollar_volume=adv, portfolio_value=notional, eta=eta)
75 return value if math.isfinite(value) and value >= 0.0 else 0.0
78@dataclass(frozen=True)
79class CompositeCostModel:
80 """The sum of its parts."""
82 models: Sequence[CostModel] = field(default_factory=tuple)
84 def cost_bps(self, trade_value: float, *, adv_usd: float | None = None, daily_vol: float | None = None) -> float:
85 return float(sum(model.cost_bps(trade_value, adv_usd=adv_usd, daily_vol=daily_vol) for model in self.models))
88def cost_usd(model: CostModel, trade_value: float, *, adv_usd: float | None = None, daily_vol: float | None = None) -> float:
89 """The model's cost of one trade in dollars."""
90 notional = abs(float(trade_value)) if trade_value is not None and math.isfinite(float(trade_value)) else 0.0
91 return notional * model.cost_bps(notional, adv_usd=adv_usd, daily_vol=daily_vol) / 1e4
94def coinbase_model(date: str = "2026-01-01", *, slippage_bps: float = 10.0) -> LinearCostModel:
95 """Coinbase market orders as the live path and its simulator charge them: the date-effective taker fee plus the
96 crypto slippage the target-weights simulator assumes (`portfolio.target_weights.DEFAULT_SLIPPAGE_BPS`)."""
97 from evaluation.target_weights_engine import coinbase_taker_bps
99 return LinearCostModel(commission_bps=coinbase_taker_bps(date), half_spread_bps=slippage_bps)
102def ib_equity_model(*, commission_bps: float = 1.5, min_fee_usd: float = 1.0, slippage_bps: float = 3.0, eta: float | None = 0.5) -> CostModel:
103 """US equities through IB as the target-weights path charges them (bps commission with a $1 floor, 3 bps slippage),
104 with square-root impact on top unless `eta` is None."""
105 linear = LinearCostModel(commission_bps=commission_bps, half_spread_bps=slippage_bps, min_fee_usd=min_fee_usd)
106 return linear if eta is None else CompositeCostModel((linear, SquareRootImpactModel(eta=eta)))