|
| 1 | +"""Helpers for whole-share execution on small accounts.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from collections.abc import Iterable, Mapping |
| 6 | + |
| 7 | + |
| 8 | +__all__ = ["project_unbuyable_value_targets_to_cash"] |
| 9 | + |
| 10 | + |
| 11 | +def _normalize_symbol(value: object) -> str: |
| 12 | + return str(value or "").strip().upper() |
| 13 | + |
| 14 | + |
| 15 | +def project_unbuyable_value_targets_to_cash( |
| 16 | + target_values: Mapping[str, object], |
| 17 | + prices: Mapping[str, object], |
| 18 | + *, |
| 19 | + symbols: Iterable[str] | None = None, |
| 20 | + quantity_step: float = 1.0, |
| 21 | +) -> tuple[dict[str, float], tuple[str, ...]]: |
| 22 | + """Zero value targets that cannot buy one execution quantity step. |
| 23 | +
|
| 24 | + This keeps strategy output intact while letting whole-share execution layers |
| 25 | + avoid preserving a single oversized share for a sleeve whose target is less |
| 26 | + than one tradable unit. |
| 27 | + """ |
| 28 | + |
| 29 | + adjusted = { |
| 30 | + _normalize_symbol(symbol): float(value or 0.0) |
| 31 | + for symbol, value in dict(target_values or {}).items() |
| 32 | + } |
| 33 | + step = max(0.0, float(quantity_step or 0.0)) |
| 34 | + if step <= 0.0: |
| 35 | + return adjusted, () |
| 36 | + |
| 37 | + if symbols is None: |
| 38 | + candidate_symbols = tuple(adjusted) |
| 39 | + else: |
| 40 | + candidate_symbols = tuple(dict.fromkeys(_normalize_symbol(symbol) for symbol in symbols)) |
| 41 | + |
| 42 | + substituted: list[str] = [] |
| 43 | + normalized_prices = { |
| 44 | + _normalize_symbol(symbol): float(price or 0.0) |
| 45 | + for symbol, price in dict(prices or {}).items() |
| 46 | + } |
| 47 | + for symbol in candidate_symbols: |
| 48 | + if not symbol: |
| 49 | + continue |
| 50 | + target_value = max(0.0, float(adjusted.get(symbol, 0.0) or 0.0)) |
| 51 | + price = max(0.0, float(normalized_prices.get(symbol, 0.0) or 0.0)) |
| 52 | + if price <= 0.0: |
| 53 | + continue |
| 54 | + if 0.0 < target_value < (price * step): |
| 55 | + adjusted[symbol] = 0.0 |
| 56 | + substituted.append(symbol) |
| 57 | + |
| 58 | + return adjusted, tuple(dict.fromkeys(substituted)) |
0 commit comments