Coverage for portfolio/financing.py: 100%
45 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"""Daily financing of the target-weights path (V6.5.0): what a broker charges and Lean does not.
3Lean charges no margin interest and no stock borrow, and pays no FX swap (`portfolio/cash_sweep.py`), so a leveraged or carry
4candidate looks better in a backtest than it can be live. main.py books this amount on the USD cash and the offline
5engine adds it to its cash, so both see the same charge.
7Pure, NaN-safe. A negative result is a cost.
8"""
10from __future__ import annotations
12import bisect
13import csv
14import math
15from collections.abc import Iterable
16from pathlib import Path
18DAY_COUNT = 360.0
21def _finite(value, default: float = 0.0) -> float:
22 try:
23 number = float(value)
24 except (TypeError, ValueError):
25 return default
26 return number if math.isfinite(number) else default
29def daily_financing_usd(
30 *,
31 long_usd: float,
32 short_usd: float,
33 nav: float,
34 rf_annual_pct: float,
35 fx_positions: Iterable[tuple[float, float]] = (),
36 days: float = 1.0,
37 margin_spread_bps: float = 150.0,
38 borrow_bps: float = 25.0,
39 fx_spread_bps: float = 50.0,
40) -> float:
41 """Financing for `days` calendar days. `long_usd` and `short_usd` (positive) cover everything but forex, including
42 the T-bill sweep. The debit is what the longs need beyond NAV and the short proceeds, charged at the risk-free rate
43 plus the spread. Each forex position is (signed USD notional of the base currency, r_base - r_quote in percentage points):
44 long the base earns the differential, either way less the spread. Positive cash earns nothing, as in Lean."""
45 days = max(0.0, _finite(days))
46 if days == 0.0:
47 return 0.0
48 long_value, short_value = abs(_finite(long_usd)), abs(_finite(short_usd))
49 debit = max(0.0, long_value - short_value - _finite(nav))
50 rate = max(0.0, _finite(rf_annual_pct) + _finite(margin_spread_bps) / 100.0)
51 amount = -debit * rate / 100.0
52 amount -= short_value * _finite(borrow_bps) / 1e4
53 for notional, carry_pct in fx_positions:
54 value = _finite(notional)
55 amount += value * _finite(carry_pct) / 100.0
56 amount -= abs(value) * _finite(fx_spread_bps) / 1e4
57 return amount * days / DAY_COUNT
60def load_rate_series(path: Path | str) -> tuple[list[str], list[float]]:
61 """(ISO dates, rates in percent) of Lean's `interest-rate.csv`; empty when the file is missing or unreadable, so a
62 run without it charges a 0% base rate plus the spread rather than failing."""
63 dates: list[str] = []
64 rates: list[float] = []
65 try:
66 with Path(path).open(newline="", encoding="utf-8") as handle:
67 rows = list(csv.reader(handle))
68 except OSError:
69 return [], []
70 for row in rows[1:]:
71 if len(row) >= 2:
72 value = _finite(row[1], float("nan"))
73 if math.isfinite(value):
74 dates.append(row[0][:10])
75 rates.append(value)
76 return dates, rates
79def rate_asof(dates: list[str], rates: list[float], date: str) -> float:
80 """The last rate at or before `date`; 0.0 before the first observation."""
81 index = bisect.bisect_right(dates, str(date)[:10]) - 1
82 return rates[index] if index >= 0 else 0.0