Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(risk): count drawdown days on the civil calendar

Rudy Celekli12038752ac6c
diff --git a/agent/src/quantlib/risk.py b/agent/src/quantlib/risk.py
index cfba0cb4a..3d11d320e 100644
--- a/agent/src/quantlib/risk.py
+++ b/agent/src/quantlib/risk.py
@@ -510,15 +510,25 @@ def max_drawdown_analysis(equity: pd.Series | np.ndarray | Sequence[float]) -> d
"recovered": recovery_pos is not None,
"peak_to_trough_periods": trough_pos - peak_pos,
"trough_to_recovery_periods": None if recovery_pos is None else recovery_pos - trough_pos,
- "underwater_days": int((index[trough_pos] - index[peak_pos]).days) if is_dated else None,
+ "underwater_days": _civil_days(index[trough_pos], index[peak_pos]) if is_dated else None,
"recovery_days": (
- int((index[recovery_pos] - index[trough_pos]).days)
+ _civil_days(index[recovery_pos], index[trough_pos])
if is_dated and recovery_pos is not None
else None
),
}
+def _civil_days(later, earlier) -> int:
+ """Whole calendar days from ``earlier`` to ``later``.
+
+ ``Timedelta.days`` counts 24-hour blocks. Across a spring-forward, midnight
+ to the next midnight is 23 hours and that count is 0, so a drawdown that
+ lasted the whole civil day was reported as underwater for none.
+ """
+ return (pd.Timestamp(later).date() - pd.Timestamp(earlier).date()).days
+
+
def monte_carlo_gbm(
s0: float,
mu: float,
diff --git a/agent/tests/quantlib/test_risk.py b/agent/tests/quantlib/test_risk.py
index da6e54936..6a91577a8 100644
--- a/agent/tests/quantlib/test_risk.py
+++ b/agent/tests/quantlib/test_risk.py
@@ -303,6 +303,18 @@ def test_max_drawdown_drops_nan_and_keeps_the_surviving_index_labels():
assert result["underwater_days"] == 1
+def test_underwater_days_survive_a_spring_forward() -> None:
+ # 2024-03-10 00:00 America/New_York to the next midnight is 23 hours, so
+ # Timedelta.days is 0. The curve was underwater for one civil day.
+ index = pd.DatetimeIndex(
+ ["2024-03-10", "2024-03-11", "2024-03-12"], tz="America/New_York"
+ )
+ assert int((index[1] - index[0]).days) == 0
+ result = max_drawdown_analysis(pd.Series([100.0, 80.0, 100.0], index=index))
+ assert result["underwater_days"] == 1
+ assert result["recovery_days"] == 1
+
+
def test_max_drawdown_rejects_an_all_nan_series():
with pytest.raises(ValueError, match="no finite observation"):
max_drawdown_analysis([np.nan, np.nan])