Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(factors): stabilize neutralization and PCA across input units

Haozhe Wu9d646f228732
diff --git a/agent/src/quantlib/neutralization.py b/agent/src/quantlib/neutralization.py
index f7073a5f6..3261361ef 100644
--- a/agent/src/quantlib/neutralization.py
+++ b/agent/src/quantlib/neutralization.py
@@ -85,11 +85,19 @@ def _weights(values: np.ndarray) -> np.ndarray:
return values / values.max()
+def _bounded(values: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
+ """Change units before centering/squaring to avoid float overflow/underflow."""
+ units = np.max(np.abs(values), axis=0)
+ units = np.where(units > 0, units, 1.0)
+ return values / units, units
+
+
def _design(x: np.ndarray, weights: np.ndarray) -> np.ndarray:
# Center/scale only on the current complete cross-section; this preserves
# the regression span while making rank checks insensitive to input units.
probability = weights / weights.sum()
- centered = x - probability @ x
+ bounded, _ = _bounded(x)
+ centered = bounded - probability @ bounded
scale = np.sqrt(probability @ np.square(centered))
scaled = centered / np.where(scale > 0, scale, 1.0)
return np.column_stack([np.ones(len(x)), scaled])
@@ -102,6 +110,8 @@ def _rank(design: np.ndarray, weights: np.ndarray, rcond: float) -> int:
def _correlation(a: np.ndarray, b: np.ndarray, weights: np.ndarray) -> float | None:
probability = weights / weights.sum()
+ a, _ = _bounded(a)
+ b, _ = _bounded(b)
a = a - probability @ a
b = b - probability @ b
scale_a = float(np.sqrt(probability @ np.square(a)))
@@ -333,7 +343,8 @@ def neutralize_factor(
detail["reason"] = "insufficient_residual_dof"
continue
fit_y = y[valid]
- centered_y = fit_y - (fit_w / fit_w.sum()) @ fit_y
+ bounded_y, signal_units = _bounded(fit_y)
+ centered_y = bounded_y - (fit_w / fit_w.sum()) @ bounded_y
root_w = np.sqrt(fit_w)
beta = np.linalg.lstsq(
design * root_w[:, None], centered_y * root_w, rcond=rcond
@@ -347,6 +358,12 @@ def neutralize_factor(
residual = np.zeros(count)
elif standardize:
residual /= np.sqrt((fit_w / fit_w.sum()) @ np.square(residual))
+ elif not standardize:
+ with np.errstate(over="ignore", invalid="ignore"):
+ residual *= signal_units
+ if not np.isfinite(residual).all():
+ detail["reason"] = "nonfinite_result"
+ continue
residuals.iloc[row, np.flatnonzero(valid)] = residual
detail.update(
status="ok",
@@ -445,13 +462,25 @@ def pca_factors(
detail["reason"] = "insufficient_sample"
continue
x = x[valid]
- means = x.mean(axis=0)
- scales = x.std(axis=0)
- if np.any(scales == 0):
+ bounded, units = _bounded(x)
+ bounded_means = bounded.mean(axis=0)
+ centered = bounded - bounded_means
+ bounded_scales = np.sqrt(np.mean(np.square(centered), axis=0))
+ means = bounded_means * units
+ scales = bounded_scales * units
+ if np.any(bounded_scales == 0):
detail["reason"] = "constant_factor"
continue
fitted_scales = scales if standardize else np.ones(len(panels))
- z = (x - means) / fitted_scales
+ # Covariance PCA must retain relative factor units: use ONE common
+ # scale, then restore score units. Per-column scaling here would
+ # accidentally turn covariance PCA into correlation PCA.
+ score_units = 1.0 if standardize else float(units.max())
+ z = (
+ centered / bounded_scales
+ if standardize
+ else centered * (units / score_units)
+ )
rank = np.linalg.matrix_rank(z)
detail["rank"] = int(rank)
if rank == 0 or (fixed_count and n_components > rank):
@@ -473,8 +502,21 @@ def pca_factors(
)
)
loadings = model.components_[:keep].copy()
+ with np.errstate(over="ignore", invalid="ignore"):
+ scores = scores[:, :keep] * score_units
+ if not np.isfinite(scores).all():
+ detail["reason"] = "nonfinite_result"
+ continue
for col in range(keep):
- if loadings[col, np.argmax(np.abs(loadings[col]))] < 0:
+ magnitude = np.abs(loadings[col])
+ # Equal-magnitude loadings are common with two standardized
+ # factors. Resolve roundoff ties in input order, not by SVD noise.
+ anchor = np.flatnonzero(
+ np.isclose(
+ magnitude, magnitude.max(), rtol=32 * np.finfo(float).eps, atol=0
+ )
+ )[0]
+ if loadings[col, anchor] < 0:
loadings[col] *= -1
scores[:, col] *= -1
name = f"PC{col + 1}"
diff --git a/agent/src/skills/factor-research/references/neutralization.md b/agent/src/skills/factor-research/references/neutralization.md
index 56b0192d0..e0866c998 100644
--- a/agent/src/skills/factor-research/references/neutralization.md
+++ b/agent/src/skills/factor-research/references/neutralization.md
@@ -130,12 +130,35 @@ counts, with unused component rows kept NaN.
Per-time diagnostics include loadings, factor means/scales, explained-variance
ratios and retained variance. The largest absolute loading anchors each
-component's sign. It does not prevent rotation, permutation or instability
+component's sign; roundoff ties use the first factor in input order. It does not prevent rotation, permutation or instability
between times when eigenvalues are close; do not assume `PC1` is a stable
tradable economic factor without assessing this. PCA decorrelates components,
not designated industry/style exposures. Avoid choosing PCA settings on the
final test period.
+## User entry points
+
+- **Web chat / interactive CLI**: ask to load `factor-research` and its
+ `references/neutralization.md`, then use `quantlib_call` with your supplied
+ time-by-asset panels. For example: "Use neutralize_factor with my signal and
+ size/industry controls; report missing observations, selected controls and
+ exposure before/after. Then use pca_factors on my factor panels and report
+ retained variance. Do not invent missing inputs or infer profitability."
+- **CLI prompt file**: put that request and the indexed JSON panels in
+ `request.txt`, then run `vibe-trading run --prompt-file request.txt`.
+- **REST chat**: send the same prompt as `content` to the authenticated
+ `POST /sessions/{session_id}/messages` route of an existing session. This
+ starts the ordinary agent run; it is not a synchronous transform endpoint.
+- **MCP**: call the served `quantlib_call` tool directly with the arguments
+ below. This executes the calculation without an LLM or shell tool.
+- **Python**: import the two functions as above for deterministic processing
+ and full-size output.
+
+Chat entry points require a configured model and an enabled `quantlib_call`
+tool. This workflow does not add an `alpha neutralize` subcommand or a dedicated
+Alpha Zoo form. Panel inputs and economically justified controls are supplied
+by the caller; no exposure data source is fetched automatically.
+
## Tool invocation
Use `action="list"` or `action="describe"` with `module="neutralization"` to
@@ -172,7 +195,10 @@ which would change each cross-section.
## Diagnostics and evaluation
Every observation reports status, complete/fitted counts and output coverage.
-Skipped observations have zero output coverage. Residualization also reports
+Skipped observations have zero output coverage. Calculations rescale finite
+inputs before centering/squaring to preserve unit invariance. If raw residuals
+or raw PCA scores exceed floating-point range, that observation is skipped with
+`nonfinite_result`, never reported as a successful infinite panel. Residualization also reports
selected/dropped controls, exclusion reasons, rank, residual degrees of freedom,
zero-residual flags and Pearson exposures before/after on identical fit assets.
WLS exposures use its regression weights. Undefined correlations are `None`.
@@ -187,7 +213,7 @@ profitable alpha.
## Local validation
```bash
-pytest agent/tests/quantlib/test_neutralization.py agent/tests/test_quantlib_tool.py -q
+pytest agent/tests/quantlib/test_neutralization.py agent/tests/test_quantlib_tool.py agent/tests/test_mcp_neutralization.py -q
```
Fixtures are synthetic and offline. Tests cover OLS/WLS reference fits, weighted
diff --git a/agent/tests/quantlib/test_neutralization.py b/agent/tests/quantlib/test_neutralization.py
index 679083174..6d929a526 100644
--- a/agent/tests/quantlib/test_neutralization.py
+++ b/agent/tests/quantlib/test_neutralization.py
@@ -285,7 +285,15 @@ def test_pca_components_are_uncorrelated_and_full_components_reconstruct_inputs(
np.testing.assert_allclose(scores @ loadings, expected, atol=1e-12)
assert sum(detail["explained_variance_ratio"]) == pytest.approx(1)
for loading in loadings:
- assert loading[np.argmax(np.abs(loading))] >= 0
+ anchors = np.flatnonzero(
+ np.isclose(
+ np.abs(loading),
+ np.abs(loading).max(),
+ rtol=32 * np.finfo(float).eps,
+ atol=0,
+ )
+ )
+ assert loading[anchors[0]] >= 0
def test_pca_variance_fraction_handles_variable_component_counts_and_missing_assets():
@@ -409,3 +417,89 @@ def test_quantlib_tool_lists_calls_and_serializes_both_transforms():
)
assert not error["ok"]
assert "requires weights" in error["error"]
+
+
[email protected]("units", [1e-200, 1e200])
[email protected]("method", ["ols", "wls"])
+def test_residualization_is_stable_under_finite_unit_changes(units, method):
+ signal, controls = sample(n_rows=1)
+ kwargs = {"method": method}
+ if method == "wls":
+ kwargs["weights"] = panel([np.arange(1, 21)])
+ reference = neutralize_factor(signal, controls, **kwargs)
+ changed = {name: value * units for name, value in controls.items()}
+ actual = neutralize_factor(signal * units, changed, **kwargs)
+ assert actual.diagnostics[0]["status"] == "ok"
+ np.testing.assert_allclose(actual.residuals, reference.residuals, atol=1e-12)
+ raw = neutralize_factor(signal * units, changed, standardize=False, **kwargs)
+ expected = neutralize_factor(signal, controls, standardize=False, **kwargs)
+ np.testing.assert_allclose(raw.residuals / units, expected.residuals, atol=1e-12)
+ assert all(
+ np.isfinite(v) for v in actual.diagnostics[0]["exposure_before"].values()
+ )
+
+
[email protected]("units", [1e-200, 1e200])
[email protected]("standardize", [False, True])
+def test_pca_preserves_variance_and_reconstruction_across_units(units, standardize):
+ _, factors = sample(n_rows=1)
+ reference = pca_factors(factors, n_components=2, standardize=standardize)
+ changed = {name: value * units for name, value in factors.items()}
+ actual = pca_factors(changed, n_components=2, standardize=standardize)
+ detail = actual.diagnostics[0]
+ assert detail["status"] == "ok"
+ np.testing.assert_allclose(
+ detail["explained_variance_ratio"],
+ reference.diagnostics[0]["explained_variance_ratio"],
+ atol=1e-12,
+ )
+ for name, scores in actual.components.items():
+ np.testing.assert_allclose(
+ scores / (1 if standardize else units),
+ reference.components[name],
+ atol=1e-12,
+ )
+ scores = np.column_stack([frame.iloc[0] for frame in actual.components.values()])
+ loadings = np.array([list(v.values()) for v in detail["loadings"].values()])
+ scales = np.array(list(detail["scales"].values()))
+ means = np.array(list(detail["means"].values()))
+ # Normalize before comparing to avoid an absolute tolerance hiding tiny output.
+ reconstructed = (scores @ loadings) * (scales / units) + means / units
+ original = np.column_stack([frame.iloc[0] for frame in factors.values()])
+ np.testing.assert_allclose(reconstructed, original, atol=1e-12)
+
+
[email protected]("units", [1e-200, 1e200])
+def test_signal_units_alone_never_turn_real_residuals_into_zero(units):
+ signal, controls = sample(n_rows=1)
+ reference = neutralize_factor(signal, controls)
+ result = neutralize_factor(signal * units, controls)
+ assert not result.diagnostics[0]["zero_residual"]
+ np.testing.assert_allclose(result.residuals, reference.residuals, atol=1e-12)
+
+
+def test_raw_pca_preserves_relative_factor_units_against_independent_svd():
+ _, factors = sample(n_rows=1)
+ factors["momentum"] *= 100
+ x = np.column_stack([frame.iloc[0] for frame in factors.values()])
+ centered = x - x.mean(axis=0)
+ _, singular, vt = np.linalg.svd(centered, full_matrices=False)
+ result = pca_factors(factors, n_components=2, standardize=False)
+ detail = result.diagnostics[0]
+ np.testing.assert_allclose(
+ detail["explained_variance_ratio"], singular**2 / (singular**2).sum()
+ )
+ actual = np.array([list(v.values()) for v in detail["loadings"].values()])
+ np.testing.assert_allclose(np.abs(actual), np.abs(vt), atol=1e-12)
+
+
+def test_unrepresentable_raw_pca_scores_skip_instead_of_successful_infinities():
+ factor = panel([1e308, -1e308] * 6)
+ result = pca_factors(
+ {"a": factor, "b": factor, "c": factor, "d": factor},
+ n_components=1,
+ standardize=False,
+ )
+ assert result.components == {}
+ assert result.diagnostics[0]["reason"] == "nonfinite_result"
+ assert result.diagnostics[0]["fit_count"] == 0
diff --git a/agent/tests/test_mcp_neutralization.py b/agent/tests/test_mcp_neutralization.py
new file mode 100644
index 000000000..27f2171aa
--- /dev/null
+++ b/agent/tests/test_mcp_neutralization.py
@@ -0,0 +1,54 @@
+"""Both factor transforms round-trip through the real registry and MCP protocol."""
+
+import asyncio
+import json
+
+import numpy as np
+from fastmcp import Client
+
+import mcp_server
+from src.tools import build_registry
+
+
+def test_factor_transforms_without_shell_tools_over_mcp(monkeypatch):
+ registry = build_registry(include_shell_tools=False)
+ monkeypatch.setattr(mcp_server, "_registry", registry)
+ rng = np.random.default_rng(1817)
+ x, y = rng.normal(size=(2, 20))
+
+ def panel(values):
+ return {
+ "__dataframe__": {
+ "index": ["2026-10-18T09:30:00Z"],
+ "columns": [f"asset{i}" for i in range(20)],
+ "data": [values.tolist()],
+ }
+ }
+
+ async def run():
+ async with Client(mcp_server.mcp) as client:
+ for function, kwargs in (
+ (
+ "neutralize_factor",
+ {"factor": panel(2 * x + y), "controls": {"x": panel(x)}},
+ ),
+ (
+ "pca_factors",
+ {"factors": {"x": panel(x), "y": panel(y)}, "n_components": 2},
+ ),
+ ):
+ args = {
+ "action": "call",
+ "module": "neutralization",
+ "function": function,
+ "kwargs": kwargs,
+ }
+ expected = json.loads(registry.execute("quantlib_call", args))
+ response = await client.call_tool("quantlib_call", args)
+ actual = json.loads(response.content[0].text)
+ assert actual == expected
+ assert actual["ok"]
+ assert actual["result"]["diagnostics"][0]["fit_count"] == 20
+ assert actual["result"]["diagnostics"][0]["status"] == "ok"
+
+ asyncio.run(run())