"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(factors): make ts_argmax/ts_argmin tie-breaking backend-independent
Rudy Celekli35df94ff3c44
diff --git a/agent/src/factors/base.py b/agent/src/factors/base.pyindex b2a8a7c21..cf1ee6c0c 100644--- a/agent/src/factors/base.py+++ b/agent/src/factors/base.py@@ -294,14 +294,16 @@ def _argmax_last(arr: np.ndarray) -> float:if np.isnan(arr).all():return np.nanarr_filled = np.where(np.isnan(arr), -np.inf, arr)- return float(np.argmax(arr_filled))+ # Ties resolve to the most recent bar, matching bottleneck's move_argmax.+ return float(len(arr) - 1 - np.argmax(arr_filled[::-1]))def _argmin_last(arr: np.ndarray) -> float:if np.isnan(arr).all():return np.nanarr_filled = np.where(np.isnan(arr), np.inf, arr)- return float(np.argmin(arr_filled))+ # Ties resolve to the most recent bar, matching bottleneck's move_argmin.+ return float(len(arr) - 1 - np.argmin(arr_filled[::-1]))def ts_argmax(df: pd.DataFrame, n: int) -> pd.DataFrame:diff --git a/agent/tests/factors/test_ts_argext_tie_backend.py b/agent/tests/factors/test_ts_argext_tie_backend.pynew file mode 100644index 000000000..71397ef11--- /dev/null+++ b/agent/tests/factors/test_ts_argext_tie_backend.py@@ -0,0 +1,38 @@+"""ts_argmax / ts_argmin must give the same answer with and without bottleneck.++On tied extrema bottleneck reports the most recent bar while the pandas+fallback used to report the earliest, so alpha101 values changed with whether+the optional dependency happened to be installed.+"""++from __future__ import annotations++import numpy as np+import pandas as pd+import pytest++from src.factors import base++[email protected](params=[False, True], ids=["pandas", "bottleneck"])+def backend(request, monkeypatch):+ if request.param and not base.HAS_BOTTLENECK:+ pytest.skip("bottleneck is not installed")+ monkeypatch.setattr(base, "HAS_BOTTLENECK", request.param)+++def _frame() -> pd.DataFrame:+ return pd.DataFrame({"a": [1, 3, 3, 2, 2, 1, np.nan, 2, 5, 5.0]})+++def test_ts_argmax_ties_use_most_recent_bar(backend):+ out = base.ts_argmax(_frame(), 3)["a"].tolist()+ assert out[2:6] == [2.0, 1.0, 0.0, 1.0]+ assert out[-1] == 2.0+ assert np.isnan(out[6:9]).all()+++def test_ts_argmin_ties_use_most_recent_bar(backend):+ out = base.ts_argmin(_frame(), 3)["a"].tolist()+ assert out[2:6] == [0.0, 2.0, 2.0, 2.0]+ assert out[-1] == 0.0