Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(combination): normalise the equal-weight fallback to 1/n (#1959)

Rudy Mizrahi Celeklie52aac8bb960
diff --git a/agent/src/quantlib/combination.py b/agent/src/quantlib/combination.py
index 7721f58b0..34bff16a1 100644
--- a/agent/src/quantlib/combination.py
+++ b/agent/src/quantlib/combination.py
@@ -232,7 +232,11 @@ def _walk_forward_weights(
estimates[name] = value
if not estimates:
if insufficient == "equal":
- frame.iloc[position] = 1.0
+ # Normalised like every other weight path, and like
+ # method="equal": an un-normalised 1.0 per factor leaves the
+ # row summing to the factor count, which reads as a full-book
+ # rebalance in weight_turnover once a real estimate replaces it.
+ frame.iloc[position] = 1.0 / len(names)
continue
total = float(sum(abs(value) for value in estimates.values()))
if not np.isfinite(total) or total <= 0:
diff --git a/agent/tests/quantlib/test_combination_equal_fallback_weights.py b/agent/tests/quantlib/test_combination_equal_fallback_weights.py
new file mode 100644
index 000000000..d4cb5bca7
--- /dev/null
+++ b/agent/tests/quantlib/test_combination_equal_fallback_weights.py
@@ -0,0 +1,52 @@
+"""The ``insufficient='equal'`` fallback must emit normalised equal weights."""
+
+from __future__ import annotations
+
+import numpy as np
+import pandas as pd
+
+from src.quantlib.combination import combine_factors
+
+ASSETS = 8
+NAMES = ("a", "b", "c")
+
+
+def _sample(rows=40, seed=7):
+ rng = np.random.default_rng(seed)
+ index = pd.date_range("2024-01-01", periods=rows, freq="D")
+ columns = [f"s{i}" for i in range(ASSETS)]
+ panels = {
+ name: pd.DataFrame(rng.normal(size=(rows, ASSETS)), index=index, columns=columns)
+ for name in NAMES
+ }
+ returns = pd.DataFrame(rng.normal(size=(rows, ASSETS)), index=index, columns=columns)
+ return panels, returns
+
+
+def test_equal_fallback_rows_sum_to_one_like_method_equal():
+ """A fallback row is the same weight vector ``method='equal'`` would use."""
+ panels, returns = _sample()
+ fallback = combine_factors(
+ panels, returns, method="ic", min_periods=5, insufficient="equal"
+ )
+ reference = combine_factors(panels, method="equal")
+
+ first = fallback.weights.iloc[0]
+ assert first.abs().sum() == 1.0
+ np.testing.assert_allclose(
+ first.to_numpy(), reference.weights.iloc[0].to_numpy(), atol=1e-12
+ )
+ assert first.eq(1.0 / len(NAMES)).all()
+
+
+def test_every_emitted_fallback_weight_row_is_normalised():
+ """No emitted row escapes the absolute-sum normalisation the docs promise."""
+ panels, returns = _sample()
+ result = combine_factors(
+ panels, returns, method="ic", min_periods=5, insufficient="equal"
+ )
+ rows = result.weights.dropna(how="all")
+ assert not rows.empty
+ np.testing.assert_allclose(
+ rows.abs().sum(axis=1).to_numpy(), np.ones(len(rows)), atol=1e-12
+ )