Coverage for scripts/refresh_lean_interest_rate.py: 100%
80 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"""Bring Lean's risk-free file up to date from FRED DPCREDIT (V6.2.0).
3Lean's Sharpe subtracts the mean of `data/alternative/interest-rate/usa/interest-rate.csv` (the Fed's primary credit
4rate, percent, one row per change) over the equity curve and fills its last row forward. The file shipped with the Lean
5sample data ended at 2023-07-27 (5.5%), so every run since was charged 5.5% through 2026 although the rate was cut from
6September 2024 on. This appends FRED's change points after the file's last row, after checking that the history both
7sources share agrees (a disagreement stops the script; nothing is overwritten).
9 python scripts/refresh_lean_interest_rate.py [--end 2026-09-30] [--apply]
11Dry run by default (prints the new change points). `--apply` writes the file atomically.
12"""
14from __future__ import annotations
16import argparse
17import sys
18from datetime import date
19from pathlib import Path
21ROOT_DIR = Path(__file__).resolve().parents[1]
22sys.path.insert(0, str(ROOT_DIR))
24RATE_FILE = ROOT_DIR / "data" / "alternative" / "interest-rate" / "usa" / "interest-rate.csv"
25SERIES_ID = "DPCREDIT"
26TOLERANCE = 1e-9
27# The shipped file dates pre-2009 changes a day after FRED's effective date (its source's convention); from 2009 on both
28# agree to the day, which is what the shared-history check compares.
29CHECK_FROM = date(2009, 1, 1)
32def change_points(observations: list[tuple[date, float]]) -> list[tuple[date, float]]:
33 """Daily observations -> the days the value changed (the first observation included)."""
34 points: list[tuple[date, float]] = []
35 for day, value in sorted(observations):
36 if not points or abs(points[-1][1] - value) > TOLERANCE:
37 points.append((day, value))
38 return points
41def merge_rate_changes(
42 existing: list[tuple[date, float]], fred: list[tuple[date, float]], *, check_from: date = CHECK_FROM
43) -> list[tuple[date, float]]:
44 """New change points to append after `existing`'s last row. Raises ValueError when FRED's daily value disagrees with
45 the file's filled-forward value on any shared day from `check_from` on: the file would then not be the series this
46 script assumes."""
47 if not existing:
48 raise ValueError("the existing rate file is empty")
49 existing = sorted(existing)
50 last_day = existing[-1][0]
51 keys = [day for day, _rate in existing]
52 for day, value in fred:
53 if day > last_day or day < max(keys[0], check_from):
54 continue
55 in_force = existing[max(0, _bisect_right(keys, day) - 1)][1]
56 if abs(in_force - value) > TOLERANCE:
57 raise ValueError(f"{day}: the file holds {in_force} but FRED {SERIES_ID} says {value}")
58 in_force = existing[-1][1]
59 appended = []
60 for day, value in change_points([(day, value) for day, value in fred if day > last_day]):
61 if abs(value - in_force) > TOLERANCE:
62 appended.append((day, value))
63 in_force = value
64 return appended
67def _bisect_right(keys: list[date], day: date) -> int:
68 import bisect
70 return bisect.bisect_right(keys, day)
73def read_rate_file(path: Path) -> tuple[str, list[tuple[date, float]], list[str]]:
74 lines = path.read_text(encoding="utf-8").splitlines()
75 header = lines[0] if lines and not lines[0][:1].isdigit() else ""
76 rows, raw = [], []
77 for line in lines[1 if header else 0:]:
78 if not line.strip():
79 continue
80 day, value = line.split(",")[:2]
81 rows.append((date.fromisoformat(day.strip()), float(value)))
82 raw.append(line.rstrip())
83 return header, rows, raw
86def main() -> int:
87 from data_pipeline.fred_backfill import fetch_fred_series
88 from json_safety import atomic_write_text
90 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
91 parser.add_argument("--end", default="2026-09-30")
92 parser.add_argument("--file", default=str(RATE_FILE))
93 parser.add_argument("--apply", action="store_true")
94 args = parser.parse_args()
96 path = Path(args.file)
97 header, existing, raw = read_rate_file(path)
98 fred = [(row["date"], float(row["value"])) for row in fetch_fred_series(SERIES_ID, "2003-01-01", args.end)]
99 if not fred:
100 print(f"FRED {SERIES_ID} returned nothing; file unchanged")
101 return 1
102 appended = merge_rate_changes(existing, fred)
103 print(f"{path}: last row {existing[-1][0]} {existing[-1][1]}; FRED to {fred[-1][0]} ({len(fred)} observations)")
104 for day, value in appended:
105 print(f" + {day.isoformat()},{value:.2f}")
106 if not appended:
107 print(" nothing to append")
108 return 0
109 if not args.apply:
110 print("dry run (pass --apply to write)")
111 return 0
112 lines = ([header] if header else []) + raw + [f"{day.isoformat()},{value:.2f}" for day, value in appended]
113 atomic_write_text(path, "\n".join(lines) + "\n")
114 print(f"written {path}")
115 return 0
118if __name__ == "__main__":
119 raise SystemExit(main())