From 887aed80e0b0e7c4e1e73e0903e12d2f1f74f6d8 Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:44:08 +0800 Subject: [PATCH 1/2] feat(risk): add config-driven bucket ladder and merged sizing --- src/quant_platform_kit/risk/__init__.py | 24 + .../risk/bucket_capital_ladder.py | 453 ++++++++++++++++++ tests/test_bucket_capital_ladder.py | 161 +++++++ 3 files changed, 638 insertions(+) create mode 100644 src/quant_platform_kit/risk/bucket_capital_ladder.py create mode 100644 tests/test_bucket_capital_ladder.py diff --git a/src/quant_platform_kit/risk/__init__.py b/src/quant_platform_kit/risk/__init__.py index 6d46a383..ed0bcd00 100644 --- a/src/quant_platform_kit/risk/__init__.py +++ b/src/quant_platform_kit/risk/__init__.py @@ -101,6 +101,19 @@ evaluate_matched_cashflow_dca_benchmark, evaluate_sma_hysteresis_regime, ) +from quant_platform_kit.risk.bucket_capital_ladder import ( + TIER_1, + TIER_2, + TIER_3, + TIER_BELOW, + BucketAllocationPlan, + BucketLadderConfig, + MergedWholeSharePlan, + classify_capital_tier, + compute_merged_whole_share_orders, + evaluate_bucket_allocation, + modeled_ibkr_tiered_fee, +) from quant_platform_kit.risk.policy_v0_sizing import ( BETA_SOXL, DEFAULT_SLEEVE_BETA_SHARES, @@ -295,4 +308,15 @@ "SmaHysteresisRegimeDecision", "evaluate_matched_cashflow_dca_benchmark", "evaluate_sma_hysteresis_regime", + "TIER_BELOW", + "TIER_1", + "TIER_2", + "TIER_3", + "BucketAllocationPlan", + "BucketLadderConfig", + "MergedWholeSharePlan", + "classify_capital_tier", + "compute_merged_whole_share_orders", + "evaluate_bucket_allocation", + "modeled_ibkr_tiered_fee", ] diff --git a/src/quant_platform_kit/risk/bucket_capital_ladder.py b/src/quant_platform_kit/risk/bucket_capital_ladder.py new file mode 100644 index 00000000..6aefb8da --- /dev/null +++ b/src/quant_platform_kit/risk/bucket_capital_ladder.py @@ -0,0 +1,453 @@ +"""Config-driven four-slot bucket allocation, capital-ladder tiering, and merged whole-share sizing. + +Pure offline portfolio-orchestration library (zero broker I/O, zero order side effects). +Implements the frozen Layer 1 skeleton: +- Half-open capital tiers: BELOW_TIER1 (< $1.5k), TIER1 [$1.5k, $15k), TIER2 [$15k, $50k), TIER3 (>= $50k) +- Four-slot allocation over Layer 1 investable NAV (after Layer 0 emergency cash): + Bucket A (remainder, default 70%), Bucket B (25%–35%, default 30%), Bucket C (0% read-only), + Bucket D (0% default; eligible only at TIER3 AND NAV >= $50k with explicit Owner approval, cap <= 20%) +- Config-driven per-bucket broker routing (zero hardcoded broker logic) +- Cross-sleeve duplicate-ticker merging before whole-share flooring, halted-symbol preservation, + passive-breach add-blocking (allowing explicit trims/exits), and exact modeled IBKR Pro Tiered fees. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from decimal import Decimal +import math + +from quant_platform_kit.risk.policy_v0_sizing import estimate_ibkr_commission_usd + + +TIER_BELOW = "BELOW_TIER1" +TIER_1 = "TIER1" +TIER_2 = "TIER2" +TIER_3 = "TIER3" +BUCKET_D_HARD_MIN_NAV_USD = 50_000.0 +_TIER_RANK: dict[str, int] = { + TIER_BELOW: 0, + TIER_1: 1, + TIER_2: 2, + TIER_3: 3, +} + + +def _finite_number(value: object, label: str, *, allow_zero: bool = True, allow_negative: bool = False) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ValueError(f"{label} must be a finite number") + num = float(value) + if not math.isfinite(num): + raise ValueError(f"{label} must be finite") + if not allow_negative and num < 0.0: + raise ValueError(f"{label} must be non-negative") + if not allow_zero and num <= 0.0: + raise ValueError(f"{label} must be strictly positive") + return num + + +def _to_dec(value: float) -> Decimal: + return Decimal(str(value)) + + +def modeled_ibkr_tiered_fee(shares: int, trade_usd: float) -> float: + """Modeled IBKR Pro Tiered US ETF/equity commission reusing canonical ``policy_v0_sizing`` logic.""" + if isinstance(shares, bool) or not isinstance(shares, int) or shares < 0: + raise ValueError("shares must be a non-negative integer") + notional = _finite_number(trade_usd, "trade_usd") + if shares == 0 or notional == 0.0: + return 0.0 + return float(estimate_ibkr_commission_usd(shares, notional / float(shares))) + + +@dataclass(frozen=True) +class BucketLadderConfig: + """Configuration for the four-slot Layer 1 capital ladder and broker routing.""" + + tier1_min_usd: float = 1_500.0 + tier2_min_usd: float = 15_000.0 + tier3_min_usd: float = 50_000.0 + bucket_b_weight: float = 0.30 + bucket_d_weight: float = 0.0 + bucket_d_single_stock_cap: float = 0.02 + broker_routes: Mapping[str, str] = field( + default_factory=lambda: {"A": "ibkr", "B": "ibkr", "D": "ibkr"} + ) + + def __post_init__(self) -> None: + t1 = _finite_number(self.tier1_min_usd, "tier1_min_usd", allow_zero=False) + t2 = _finite_number(self.tier2_min_usd, "tier2_min_usd", allow_zero=False) + t3 = _finite_number(self.tier3_min_usd, "tier3_min_usd", allow_zero=False) + if not (t1 < t2 < t3): + raise ValueError("tier thresholds must satisfy 0 < tier1_min_usd < tier2_min_usd < tier3_min_usd") + + wb = _finite_number(self.bucket_b_weight, "bucket_b_weight") + wd = _finite_number(self.bucket_d_weight, "bucket_d_weight") + cap_d = _finite_number(self.bucket_d_single_stock_cap, "bucket_d_single_stock_cap", allow_zero=False) + if not (0.25 <= wb <= 0.35): + raise ValueError("bucket_b_weight must lie in [0.25, 0.35]") + if not (0.0 <= wd <= 0.20): + raise ValueError("bucket_d_weight must lie in [0.0, 0.20]") + if not (0.0 < cap_d <= 0.02): + raise ValueError("bucket_d_single_stock_cap must lie in (0.0, 0.02]") + + normalized_routes: dict[str, str] = {} + for slot in ("A", "B", "D"): + raw = self.broker_routes.get(slot, "") + venue = str(raw).strip().lower() + if not venue: + raise ValueError(f"broker_routes must specify a non-empty venue for bucket {slot!r}") + normalized_routes[slot] = venue + object.__setattr__(self, "broker_routes", normalized_routes) + + +@dataclass(frozen=True) +class BucketAllocationPlan: + """Result of evaluating Layer 1 capital tier, bucket weights, budgets, and console prompts.""" + + investable_nav_usd: float + capital_tier: str + bucket_weights: dict[str, float] + bucket_budgets_usd: dict[str, float] + bucket_d_single_stock_max_usd: float + broker_routes: dict[str, str] + bucket_d_eligible: bool + bucket_d_active: bool + bucket_d_reason: str + expansion_paused: bool + owner_decision_prompts: tuple[str, ...] + + +@dataclass(frozen=True) +class MergedWholeSharePlan: + """Merged whole-share target plan across sleeves with halt and passive-breach guards.""" + + target_shares: dict[str, int] + delta_shares: dict[str, int] + estimated_fees_usd: float + idle_cash_usd: float + idle_cash_ratio: float + zero_share_target_symbols: tuple[str, ...] + halted_retained_symbols: tuple[str, ...] + passive_breach_blocked_adds: tuple[str, ...] + + +def classify_capital_tier( + investable_nav_usd: float, + config: BucketLadderConfig | None = None, +) -> str: + """Classify Layer 1 investable NAV into half-open capital tiers.""" + cfg = config or BucketLadderConfig() + nav = _finite_number(investable_nav_usd, "investable_nav_usd") + if nav < cfg.tier1_min_usd: + return TIER_BELOW + if nav < cfg.tier2_min_usd: + return TIER_1 + if nav < cfg.tier3_min_usd: + return TIER_2 + return TIER_3 + + +def evaluate_bucket_allocation( + *, + investable_nav_usd: float, + bucket_d_approved: bool = False, + prior_tier: str | None = None, + config: BucketLadderConfig | None = None, +) -> BucketAllocationPlan: + """Compute config-driven Layer 1 A/B/C/D weights, budgets, and Owner decision prompts.""" + cfg = config or BucketLadderConfig() + if not isinstance(bucket_d_approved, bool): + raise ValueError("bucket_d_approved must be a boolean") + if prior_tier is not None and prior_tier not in _TIER_RANK: + raise ValueError(f"unknown prior_tier: {prior_tier!r}") + + nav = _finite_number(investable_nav_usd, "investable_nav_usd") + tier = classify_capital_tier(nav, cfg) + expansion_paused = prior_tier is not None and _TIER_RANK[tier] < _TIER_RANK[prior_tier] + + # Hard $50k floor on Bucket D cannot be bypassed by lowering tier3_min_usd + d_eligible = tier == TIER_3 and nav >= BUCKET_D_HARD_MIN_NAV_USD + prompts: list[str] = [] + if tier == TIER_2 and prior_tier in (None, TIER_BELOW, TIER_1): + prompts.append("TIER2_ELIGIBLE_OPTIONAL_MULTI_BROKER_SPLIT_REVIEW") + if d_eligible and not bucket_d_approved: + prompts.append("TIER3_ELIGIBLE_BUCKET_D_FORWARD_EVALUATION_REVIEW") + if expansion_paused: + prompts.append("TIER_REGRESSED_EXPANSION_PAUSED_HOLD_EXISTING") + + wb_dec = _to_dec(cfg.bucket_b_weight) + req_wd_dec = _to_dec(cfg.bucket_d_weight) + + if not d_eligible: + wd_dec = Decimal("0") + d_active = False + d_reason = "BELOW_TIER3_THRESHOLD" + elif not bucket_d_approved: + wd_dec = Decimal("0") + d_active = False + d_reason = "AWAITING_OWNER_APPROVAL_AND_12M_OOS" + elif req_wd_dec <= 0: + wd_dec = Decimal("0") + d_active = False + d_reason = "CONFIGURED_EMPTY_DEFAULT_ZERO" + else: + wd_dec = req_wd_dec + d_active = True + d_reason = "ACTIVE_APPROVED" + + wa_dec = Decimal("1") - wb_dec - wd_dec + nav_dec = _to_dec(nav) + weights = { + "A": float(wa_dec), + "B": float(wb_dec), + "C": 0.0, + "D": float(wd_dec), + } + budgets = { + "A": float(nav_dec * wa_dec), + "B": float(nav_dec * wb_dec), + "C": 0.0, + "D": float(nav_dec * wd_dec), + } + d_single_max = float(nav_dec * _to_dec(cfg.bucket_d_single_stock_cap)) + routes = { + "A": cfg.broker_routes["A"], + "B": cfg.broker_routes["B"], + "C": "read_only", + "D": cfg.broker_routes["D"], + } + return BucketAllocationPlan( + investable_nav_usd=nav, + capital_tier=tier, + bucket_weights=weights, + bucket_budgets_usd=budgets, + bucket_d_single_stock_max_usd=d_single_max, + broker_routes=routes, + bucket_d_eligible=d_eligible, + bucket_d_active=d_active, + bucket_d_reason=d_reason, + expansion_paused=expansion_paused, + owner_decision_prompts=tuple(prompts), + ) + + +def _normalize_unique_mapping( + raw_map: Mapping[str, object] | None, + label: str, +) -> dict[str, object]: + out: dict[str, object] = {} + if not raw_map: + return out + for raw_k, val in raw_map.items(): + sym = str(raw_k).strip().upper() + if not sym: + raise ValueError(f"{label} must not contain empty symbol") + if sym in out: + raise ValueError(f"duplicate normalized symbol {sym!r} in {label}") + out[sym] = val + return out + + +def _normalize_allocations( + target_dollar_allocations: Mapping[str, float] | Sequence[tuple[str, float]], +) -> dict[str, Decimal]: + items = ( + list(target_dollar_allocations.items()) + if isinstance(target_dollar_allocations, Mapping) + else list(target_dollar_allocations) + ) + merged: dict[str, Decimal] = {} + for raw_s, raw_d in items: + sym = str(raw_s).strip().upper() + if not sym: + raise ValueError("target_dollar_allocations must not contain empty symbol") + amt = _finite_number(raw_d, f"target_dollar_allocations[{sym}]") + merged[sym] = merged.get(sym, Decimal("0")) + _to_dec(amt) + return merged + + +def _normalize_order_inputs( + *, + target_dollar_allocations: Mapping[str, float] | Sequence[tuple[str, float]], + prices_usd: Mapping[str, float], + current_shares: Mapping[str, int] | None, + halted_symbols: Sequence[str], + single_symbol_max_usd: Mapping[str, float] | None, +) -> tuple[dict[str, Decimal], dict[str, Decimal], dict[str, int], set[str], dict[str, Decimal]]: + if isinstance(halted_symbols, (str, bytes)): + raise ValueError("halted_symbols must be a sequence of symbol strings, not a bare string") + halted = {str(s).strip().upper() for s in halted_symbols if str(s).strip()} + + merged_dollars = _normalize_allocations(target_dollar_allocations) + + cur: dict[str, int] = {} + for sym, raw_q in _normalize_unique_mapping(current_shares, "current_shares").items(): + if isinstance(raw_q, bool) or not isinstance(raw_q, int) or raw_q < 0: + raise ValueError(f"current_shares[{sym!r}] must be a non-negative integer") + cur[sym] = raw_q + + caps: dict[str, Decimal] = {} + for sym, raw_c in _normalize_unique_mapping(single_symbol_max_usd, "single_symbol_max_usd").items(): + caps[sym] = _to_dec(_finite_number(raw_c, f"single_symbol_max_usd[{sym}]", allow_zero=False)) + + norm_prices = _normalize_unique_mapping(prices_usd, "prices_usd") + px_map: dict[str, Decimal] = {} + for sym in sorted(set(merged_dollars) | set(cur)): + if sym not in norm_prices: + raise ValueError(f"missing price for symbol {sym!r}") + px_map[sym] = _to_dec(_finite_number(norm_prices[sym], f"prices_usd[{sym}]", allow_zero=False)) + + return merged_dollars, px_map, cur, halted, caps + + +def _compute_desired_shares( + *, + all_syms: list[str], + merged_dollars: dict[str, Decimal], + px_map: dict[str, Decimal], + cur: dict[str, int], + halted: set[str], + caps: dict[str, Decimal], + slip_dec: Decimal, +) -> tuple[dict[str, int], list[str], list[str], list[str]]: + desired: dict[str, int] = {} + halted_retained: list[str] = [] + passive_breached: list[str] = [] + zero_share_targets: list[str] = [] + + for sym in all_syms: + held_q = cur.get(sym, 0) + tgt_usd = merged_dollars.get(sym, Decimal("0")) + px = px_map[sym] + if sym in halted: + desired[sym] = held_q + if held_q > 0 or tgt_usd > 0: + halted_retained.append(sym) + continue + + # Target shares evaluated at current reference price (no spurious sells from buy slippage) + base_tgt_q = int(tgt_usd // px) if tgt_usd > 0 else 0 + if sym in caps and Decimal(held_q) * px > caps[sym]: + # Passive breach: block adds, but allow explicit trims or full exit + passive_breached.append(sym) + desired[sym] = min(held_q, base_tgt_q) + continue + + effective_usd = min(tgt_usd, caps[sym]) if sym in caps else tgt_usd + if effective_usd <= 0: + desired[sym] = 0 + continue + + held_val = Decimal(held_q) * px + if effective_usd <= held_val: + q = int(effective_usd // px) + else: + # Apply buy slippage only to incremental buy dollars above current holdings + inc_usd = effective_usd - held_val + buy_px = px * (Decimal("1") + slip_dec) + add_q = int(inc_usd // buy_px) + q = held_q + add_q + if q == 0: + zero_share_targets.append(sym) + desired[sym] = q + + return desired, halted_retained, passive_breached, zero_share_targets + + +def compute_merged_whole_share_orders( + *, + target_dollar_allocations: Mapping[str, float] | Sequence[tuple[str, float]], + total_available_nav_usd: float, + prices_usd: Mapping[str, float], + current_shares: Mapping[str, int] | None = None, + halted_symbols: Sequence[str] = (), + single_symbol_max_usd: Mapping[str, float] | None = None, + slippage_bps: float = 10.0, +) -> MergedWholeSharePlan: + """Merge target dollars per ticker and solve exact affordable whole-share targets.""" + nav = _finite_number(total_available_nav_usd, "total_available_nav_usd") + slip_bps = _finite_number(slippage_bps, "slippage_bps") + if slip_bps >= 5_000.0: + raise ValueError("slippage_bps must be < 5000") + slip_dec = _to_dec(slip_bps) / Decimal("10000") + + merged_dollars, px_map, cur, halted, caps = _normalize_order_inputs( + target_dollar_allocations=target_dollar_allocations, + prices_usd=prices_usd, + current_shares=current_shares, + halted_symbols=halted_symbols, + single_symbol_max_usd=single_symbol_max_usd, + ) + all_syms = sorted(set(merged_dollars) | set(cur)) + + held_val = sum((Decimal(cur.get(s, 0)) * px_map[s] for s in all_syms), Decimal("0")) + nav_dec = _to_dec(nav) + if held_val > nav_dec + Decimal("1e-6"): + raise ValueError("current holdings market value exceeds total_available_nav_usd") + cash = max(Decimal("0"), nav_dec - held_val) + + desired, halted_retained, passive_breached, zero_share_targets = _compute_desired_shares( + all_syms=all_syms, + merged_dollars=merged_dollars, + px_map=px_map, + cur=cur, + halted=halted, + caps=caps, + slip_dec=slip_dec, + ) + + final_shares = dict(cur) + total_fees = Decimal("0") + + # Execute SELLs first (skip if net proceeds would drive cash negative) + for sym in all_syms: + if sym in halted: + continue + delta = desired[sym] - final_shares.get(sym, 0) + if delta < 0: + sell_q = -delta + gross = Decimal(sell_q) * px_map[sym] * (Decimal("1") - slip_dec) + fee = _to_dec(modeled_ibkr_tiered_fee(sell_q, float(gross))) + if cash + gross - fee < Decimal("0"): + continue + cash = cash + gross - fee + total_fees += fee + final_shares[sym] = final_shares.get(sym, 0) - sell_q + + # Execute BUYs in descending dollar shortfall using exact Decimal affordability + buy_candidates = sorted( + [(s, desired[s] - final_shares.get(s, 0)) for s in all_syms if s not in halted and desired[s] > final_shares.get(s, 0)], + key=lambda item: Decimal(item[1]) * px_map[item[0]], + reverse=True, + ) + for sym, need_q in buy_candidates: + buy_px = px_map[sym] * (Decimal("1") + slip_dec) + max_by_px = int(cash // buy_px) if cash > 0 else 0 + qty = min(need_q, max_by_px) + while qty > 0: + notional = Decimal(qty) * buy_px + fee = _to_dec(modeled_ibkr_tiered_fee(qty, float(notional))) + if notional + fee <= cash: + cash -= notional + fee + total_fees += fee + final_shares[sym] = final_shares.get(sym, 0) + qty + break + qty -= 1 + + target_out = {s: final_shares.get(s, 0) for s in all_syms} + delta_out = {s: target_out[s] - cur.get(s, 0) for s in all_syms if target_out[s] != cur.get(s, 0)} + ending_eq = cash + sum((Decimal(target_out[s]) * px_map[s] for s in all_syms), Decimal("0")) + idle_ratio = float(cash / ending_eq) if ending_eq > 0 else 0.0 + + return MergedWholeSharePlan( + target_shares=target_out, + delta_shares=delta_out, + estimated_fees_usd=float(total_fees), + idle_cash_usd=float(cash), + idle_cash_ratio=idle_ratio, + zero_share_target_symbols=tuple(sorted(zero_share_targets)), + halted_retained_symbols=tuple(sorted(halted_retained)), + passive_breach_blocked_adds=tuple(sorted(passive_breached)), + ) diff --git a/tests/test_bucket_capital_ladder.py b/tests/test_bucket_capital_ladder.py new file mode 100644 index 00000000..3748f76f --- /dev/null +++ b/tests/test_bucket_capital_ladder.py @@ -0,0 +1,161 @@ +from __future__ import annotations + +import pytest + +from quant_platform_kit.risk import ( + TIER_1, + TIER_2, + TIER_3, + TIER_BELOW, + BucketLadderConfig, + classify_capital_tier, + compute_merged_whole_share_orders, + evaluate_bucket_allocation, + modeled_ibkr_tiered_fee, +) + + +def test_classify_capital_tier_uses_strict_half_open_boundaries() -> None: + cfg = BucketLadderConfig() + assert classify_capital_tier(0.0, cfg) == TIER_BELOW + assert classify_capital_tier(1_499.99, cfg) == TIER_BELOW + assert classify_capital_tier(1_500.0, cfg) == TIER_1 + assert classify_capital_tier(14_999.99, cfg) == TIER_1 + assert classify_capital_tier(15_000.0, cfg) == TIER_2 + assert classify_capital_tier(49_999.99, cfg) == TIER_2 + assert classify_capital_tier(50_000.0, cfg) == TIER_3 + + +def test_bucket_allocation_default_70_30_0_and_bucket_d_hard_50k_floor() -> None: + plan_t1 = evaluate_bucket_allocation(investable_nav_usd=1_500.0) + assert plan_t1.capital_tier == TIER_1 + assert plan_t1.bucket_weights == {"A": 0.7, "B": 0.3, "C": 0.0, "D": 0.0} + assert plan_t1.bucket_budgets_usd == pytest.approx({"A": 1_050.0, "B": 450.0, "C": 0.0, "D": 0.0}) + assert plan_t1.bucket_d_single_stock_max_usd == pytest.approx(30.0) + assert plan_t1.broker_routes == {"A": "ibkr", "B": "ibkr", "C": "read_only", "D": "ibkr"} + assert plan_t1.bucket_d_eligible is False + assert plan_t1.bucket_d_active is False + + # Custom tier3_min_usd=20k must NOT bypass the hard $50k Bucket D floor + cfg_low = BucketLadderConfig(tier3_min_usd=20_000.0, bucket_d_weight=0.10) + blocked = evaluate_bucket_allocation(investable_nav_usd=49_999.99, bucket_d_approved=True, config=cfg_low) + assert blocked.capital_tier == TIER_3 + assert blocked.bucket_d_eligible is False + assert blocked.bucket_d_active is False + assert blocked.bucket_weights["D"] == 0.0 + + allowed = evaluate_bucket_allocation(investable_nav_usd=50_000.0, bucket_d_approved=True, config=cfg_low) + assert allowed.bucket_d_eligible is True + assert allowed.bucket_d_active is True + assert allowed.bucket_weights == {"A": 0.6, "B": 0.3, "C": 0.0, "D": 0.1} + assert allowed.bucket_d_single_stock_max_usd == pytest.approx(1_000.0) + + +def test_bucket_allocation_multi_broker_and_tier_regression() -> None: + cfg_multi = BucketLadderConfig( + bucket_b_weight=0.35, + bucket_d_weight=0.10, + broker_routes={"A": "ibkr", "B": "schwab", "D": "ibkr"}, + ) + plan_t2 = evaluate_bucket_allocation( + investable_nav_usd=20_000.0, + bucket_d_approved=False, + prior_tier=TIER_1, + config=cfg_multi, + ) + assert plan_t2.capital_tier == TIER_2 + assert plan_t2.broker_routes["B"] == "schwab" + assert "TIER2_ELIGIBLE_OPTIONAL_MULTI_BROKER_SPLIT_REVIEW" in plan_t2.owner_decision_prompts + + plan_t3_unapproved = evaluate_bucket_allocation(investable_nav_usd=60_000.0, bucket_d_approved=False, config=cfg_multi) + assert plan_t3_unapproved.bucket_d_active is False + assert plan_t3_unapproved.bucket_d_reason == "AWAITING_OWNER_APPROVAL_AND_12M_OOS" + assert "TIER3_ELIGIBLE_BUCKET_D_FORWARD_EVALUATION_REVIEW" in plan_t3_unapproved.owner_decision_prompts + + regressed = evaluate_bucket_allocation(investable_nav_usd=14_500.0, prior_tier=TIER_2) + assert regressed.expansion_paused is True + assert "TIER_REGRESSED_EXPANSION_PAUSED_HOLD_EXISTING" in regressed.owner_decision_prompts + + +def test_merged_whole_share_orders_cross_sleeve_merge_sell_then_buy_and_guards() -> None: + # Modeled fee matches policy_v0_sizing: 1% cap applies after $0.35 min + assert modeled_ibkr_tiered_fee(1, 10.0) == pytest.approx(0.10) + assert modeled_ibkr_tiered_fee(10, 1_000.0) == pytest.approx(0.35) + assert modeled_ibkr_tiered_fee(200, 20_000.0) == pytest.approx(0.70) + + # Cross-sleeve duplicate QQQ ($260 + $260 = $520 >= 1 share @ $500) merges before flooring; + # Sell 2 SPY (@ $100) then buy 1 QQQ (@ $500) -> exact cash accounting check! + plan = compute_merged_whole_share_orders( + target_dollar_allocations=[("QQQ", 260.0), ("QQQ", 260.0), ("SPY", 0.0)], + total_available_nav_usd=520.0, + prices_usd={"QQQ": 500.0, "SPY": 100.0}, + current_shares={"SPY": 2}, + slippage_bps=0.0, + ) + # Initial cash = 520 - 200 = 320; sell 2 SPY -> +200 - 0.35 = 519.65; buy 1 QQQ -> -500 - 0.35 = 19.30 + assert plan.target_shares == {"QQQ": 1, "SPY": 0} + assert plan.delta_shares == {"QQQ": 1, "SPY": -2} + assert plan.estimated_fees_usd == pytest.approx(0.70) + assert plan.idle_cash_usd == pytest.approx(19.30) + + +def test_merged_whole_share_orders_halts_passive_breach_exit_slippage_and_decimal_precision() -> None: + # 1) Passive breach blocks adds when target > held, but allows explicit full exit (target=0) + exit_plan = compute_merged_whole_share_orders( + target_dollar_allocations={"CAPX": 0.0, "HALT": 0.0}, + total_available_nav_usd=1_700.0, + prices_usd={"CAPX": 100.0, "HALT": 100.0}, + current_shares={"CAPX": 12, "HALT": 5}, + halted_symbols=("HALT",), + single_symbol_max_usd={"CAPX": 1_000.0}, + slippage_bps=0.0, + ) + assert exit_plan.target_shares["CAPX"] == 0 + assert exit_plan.target_shares["HALT"] == 5 + assert exit_plan.halted_retained_symbols == ("HALT",) + assert exit_plan.passive_breach_blocked_adds == ("CAPX",) + + # 2) Buy slippage does NOT trigger spurious sell of already-held 1 share @ $100 when target == $100 + hold_plan = compute_merged_whole_share_orders( + target_dollar_allocations={"SPY": 100.0}, + total_available_nav_usd=100.0, + prices_usd={"SPY": 100.0}, + current_shares={"SPY": 1}, + slippage_bps=10.0, + ) + assert hold_plan.target_shares["SPY"] == 1 + assert hold_plan.delta_shares == {} + + # 3) Exact Decimal flooring: $0.30 / $0.10 == 3 shares (not 2 due to float dust) + dec_plan = compute_merged_whole_share_orders( + target_dollar_allocations={"TINY": 0.30}, + total_available_nav_usd=1.00, + prices_usd={"TINY": 0.10}, + slippage_bps=0.0, + ) + assert dec_plan.target_shares["TINY"] == 3 + assert dec_plan.idle_cash_usd >= 0.0 + + +def test_bucket_ladder_rejects_invalid_inputs_and_bare_halted_string() -> None: + with pytest.raises(ValueError, match="tier1_min_usd < tier2_min_usd < tier3_min_usd"): + BucketLadderConfig(tier1_min_usd=20_000.0, tier2_min_usd=15_000.0) + with pytest.raises(ValueError, match="bucket_b_weight"): + BucketLadderConfig(bucket_b_weight=0.50) + with pytest.raises(ValueError, match="bucket_d_weight"): + BucketLadderConfig(bucket_d_weight=0.25) + with pytest.raises(ValueError, match="not a bare string"): + compute_merged_whole_share_orders( + target_dollar_allocations={"HALT": 0.0}, + total_available_nav_usd=100.0, + prices_usd={"HALT": 100.0}, + current_shares={"HALT": 1}, + halted_symbols="HALT", + ) + with pytest.raises(ValueError, match="duplicate normalized symbol"): + compute_merged_whole_share_orders( + target_dollar_allocations={"HALT": 0.0}, + total_available_nav_usd=100.0, + prices_usd={"HALT": 100.0}, + current_shares={"halt": 1, "HALT": 0}, + ) From 89147d803c6f34656fd102ae21d49d5fd569d275 Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:55:07 +0800 Subject: [PATCH 2/2] fix(risk): derive zero-share targets after affordability check --- .../risk/bucket_capital_ladder.py | 14 +++++++------- tests/test_bucket_capital_ladder.py | 12 ++++++++++++ 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/src/quant_platform_kit/risk/bucket_capital_ladder.py b/src/quant_platform_kit/risk/bucket_capital_ladder.py index 6aefb8da..8edf2de6 100644 --- a/src/quant_platform_kit/risk/bucket_capital_ladder.py +++ b/src/quant_platform_kit/risk/bucket_capital_ladder.py @@ -311,11 +311,10 @@ def _compute_desired_shares( halted: set[str], caps: dict[str, Decimal], slip_dec: Decimal, -) -> tuple[dict[str, int], list[str], list[str], list[str]]: +) -> tuple[dict[str, int], list[str], list[str]]: desired: dict[str, int] = {} halted_retained: list[str] = [] passive_breached: list[str] = [] - zero_share_targets: list[str] = [] for sym in all_syms: held_q = cur.get(sym, 0) @@ -349,11 +348,9 @@ def _compute_desired_shares( buy_px = px * (Decimal("1") + slip_dec) add_q = int(inc_usd // buy_px) q = held_q + add_q - if q == 0: - zero_share_targets.append(sym) desired[sym] = q - return desired, halted_retained, passive_breached, zero_share_targets + return desired, halted_retained, passive_breached def compute_merged_whole_share_orders( @@ -388,7 +385,7 @@ def compute_merged_whole_share_orders( raise ValueError("current holdings market value exceeds total_available_nav_usd") cash = max(Decimal("0"), nav_dec - held_val) - desired, halted_retained, passive_breached, zero_share_targets = _compute_desired_shares( + desired, halted_retained, passive_breached = _compute_desired_shares( all_syms=all_syms, merged_dollars=merged_dollars, px_map=px_map, @@ -440,6 +437,9 @@ def compute_merged_whole_share_orders( delta_out = {s: target_out[s] - cur.get(s, 0) for s in all_syms if target_out[s] != cur.get(s, 0)} ending_eq = cash + sum((Decimal(target_out[s]) * px_map[s] for s in all_syms), Decimal("0")) idle_ratio = float(cash / ending_eq) if ending_eq > 0 else 0.0 + final_zero_share_targets = tuple( + sorted(s for s in all_syms if merged_dollars.get(s, Decimal("0")) > Decimal("0") and target_out[s] == 0) + ) return MergedWholeSharePlan( target_shares=target_out, @@ -447,7 +447,7 @@ def compute_merged_whole_share_orders( estimated_fees_usd=float(total_fees), idle_cash_usd=float(cash), idle_cash_ratio=idle_ratio, - zero_share_target_symbols=tuple(sorted(zero_share_targets)), + zero_share_target_symbols=final_zero_share_targets, halted_retained_symbols=tuple(sorted(halted_retained)), passive_breach_blocked_adds=tuple(sorted(passive_breached)), ) diff --git a/tests/test_bucket_capital_ladder.py b/tests/test_bucket_capital_ladder.py index 3748f76f..cb7b5b59 100644 --- a/tests/test_bucket_capital_ladder.py +++ b/tests/test_bucket_capital_ladder.py @@ -159,3 +159,15 @@ def test_bucket_ladder_rejects_invalid_inputs_and_bare_halted_string() -> None: prices_usd={"HALT": 100.0}, current_shares={"halt": 1, "HALT": 0}, ) + + +def test_zero_share_diagnostics_derived_after_affordability() -> None: + plan = compute_merged_whole_share_orders( + target_dollar_allocations={"SPY": 100.0}, + total_available_nav_usd=100.0, + prices_usd={"SPY": 100.0}, + slippage_bps=0.0, + ) + assert plan.target_shares["SPY"] == 0 + assert plan.idle_cash_usd == pytest.approx(100.0) + assert plan.zero_share_target_symbols == ("SPY",)