"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(quantlib): normalize explicit weights without overflow
Wu Shuwen391f680893dd
diff --git a/agent/src/quantlib/combination.py b/agent/src/quantlib/combination.pyindex e6822fdea..38ffac737 100644--- a/agent/src/quantlib/combination.py+++ b/agent/src/quantlib/combination.py@@ -264,8 +264,12 @@ def _static_weights(weights: Mapping[str, float], names: list[str], index: pd.Invalues[name] = float(value)if not any(values.values()):raise ValueError("at least one weight must be nonzero")- total = float(sum(abs(value) for value in values.values()))- return _constant_weights(names, index, {name: values[name] / total for name in names})+ scale = max(abs(value) for value in values.values())+ scaled = {name: value / scale for name, value in values.items()}+ total = float(sum(abs(value) for value in scaled.values()))+ return _constant_weights(+ names, index, {name: scaled[name] / total for name in names}+ )def _table_weights(weights: pd.DataFrame, names: list[str], index: pd.Index) -> pd.DataFrame:@@ -285,9 +289,16 @@ def _table_weights(weights: pd.DataFrame, names: list[str], index: pd.Index) ->except (TypeError, ValueError) as exc:raise ValueError("weight table must contain numeric values") from exctable = np.where(np.isfinite(table), table, np.nan)+ scale = np.max(+ np.where(np.isfinite(table), np.abs(table), 0.0), axis=1, keepdims=True+ )+ scale = np.where(scale > 0, scale, 1.0)+ table = table / scaletotal = np.nansum(np.abs(table), axis=1, keepdims=True)with np.errstate(invalid="ignore", divide="ignore"):- table = np.divide(table, total, out=np.full_like(table, np.nan), where=total > 0)+ table = np.divide(+ table, total, out=np.full_like(table, np.nan), where=total > 0+ )return pd.DataFrame(table, index=index, columns=names).ffill()diff --git a/agent/tests/quantlib/test_combination.py b/agent/tests/quantlib/test_combination.pyindex 8fe80d713..75ba8a1e8 100644--- a/agent/tests/quantlib/test_combination.py+++ b/agent/tests/quantlib/test_combination.py@@ -120,6 +120,24 @@ def test_static_weights_are_normalised_and_must_cover_every_factor():combine_factors({"a": first, "b": second}, method="explicit", weights={"a": 0.0, "b": 0.0})[email protected]("weight_kind", ["mapping", "table"])+def test_large_finite_explicit_weights_are_normalised_without_overflow(weight_kind):+ first, second = sample(rows=5)+ if weight_kind == "mapping":+ weights = {"a": 1e308, "b": 1e308}+ else:+ weights = pd.DataFrame(+ {"a": [1e308] * len(first), "b": [1e308] * len(first)}, index=first.index+ )++ result = combine_factors(+ {"a": first, "b": second}, method="explicit", weights=weights+ )++ np.testing.assert_allclose(result.weights.to_numpy(), 0.5, atol=1e-12)+ assert result.composite.notna().all().all()++def test_a_weight_table_changes_the_composite_over_time():first, second = sample(rows=6)weights = pd.DataFrame(