Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(factors): add frequency-independent neutralization and PCA

BHhhh-123a54195adf532
diff --git a/README.md b/README.md
index 94db681f7..a742a9f0c 100644
--- a/README.md
+++ b/README.md
@@ -888,6 +888,7 @@ that is a bug, not a pattern.
| `attribution` | Brinson-Fachler decomposition |
| `performance` · `fundmath` | TWR / MWR / Modified Dietz; XIRR / MOIC / DPI / TVPI |
| `factormodel` · `eventstudy` | Factor regressions, event studies; portfolio style exposure reports incomplete factor rows as unmatched weight. |
+| `neutralization` | Optional per-observation OLS/WLS factor residualization, audited control quality selection, and cross-sectional PCA at any panel frequency. [Workflow and examples](agent/src/skills/factor-research/references/neutralization.md). |
| `multipletesting` · `crossvalidation` | Deflated significance, purged CV; purged walk-forward splits omit folds with no training observations left after purging; Sharpe significance summaries reject non-finite inputs by name. |
| `impact` | Market-impact models |
| `volatility` | Heston (1993) stochastic-volatility pricing; Heston pricing requires finite inputs and a positive integration limit; invalid inputs return a domain error. |
diff --git a/agent/src/quantlib/__init__.py b/agent/src/quantlib/__init__.py
index a025b9313..5f1aea7c6 100644
--- a/agent/src/quantlib/__init__.py
+++ b/agent/src/quantlib/__init__.py
@@ -23,6 +23,7 @@ Submodules:
crossvalidation Purged + embargoed splits for overlapping financial labels
eventstudy Abnormal returns around dated events (CAR/CAAR, Patell, BMP)
factormodel Cross-sectional style exposures, factor returns, style drift
+ neutralization Per-observation OLS/WLS factor residuals and cross-sectional PCA
attribution Brinson-Fachler allocation/selection/interaction
impact Market-impact and slippage models
fundmath Private-markets fund maths on the irregular cash-flow spine
diff --git a/agent/src/quantlib/neutralization.py b/agent/src/quantlib/neutralization.py
new file mode 100644
index 000000000..f7073a5f6
--- /dev/null
+++ b/agent/src/quantlib/neutralization.py
@@ -0,0 +1,500 @@
+"""Frequency-independent cross-sectional residualization and factor PCA.
+
+Each panel row is one observation time and each column is an asset. Rows are
+never pooled, resampled or filled across time. The caller must supply exposures
+and classifications known at that observation time; alignment alone cannot
+verify their publication dates. No returns or labels are used for selection.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from dataclasses import dataclass
+from numbers import Integral, Real
+from typing import Any
+
+import numpy as np
+import pandas as pd
+from sklearn.decomposition import PCA
+
+__all__ = ["neutralize_factor", "pca_factors"]
+
+
+@dataclass
+class NeutralizationResult:
+ """Residual panel and per-observation selection/exposure diagnostics."""
+
+ residuals: pd.DataFrame
+ diagnostics: list[dict[str, Any]]
+ method: str
+ control_selection: str
+
+
+@dataclass
+class FactorPCAResult:
+ """Component panels and per-observation PCA loadings/variance diagnostics."""
+
+ components: dict[str, pd.DataFrame]
+ diagnostics: list[dict[str, Any]]
+
+
+def _check_panel(panel: pd.DataFrame, name: str) -> None:
+ if not isinstance(panel, pd.DataFrame):
+ raise ValueError(f"{name} must be an indexed DataFrame (time x asset)")
+ if panel.empty or not panel.index.is_unique or not panel.columns.is_unique:
+ raise ValueError(f"{name} must be nonempty with unique time/asset labels")
+
+
+def _numeric(panel: pd.DataFrame, name: str) -> pd.DataFrame:
+ _check_panel(panel, name)
+ try:
+ values = panel.to_numpy(dtype=float, na_value=np.nan)
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f"{name} must contain numeric values") from exc
+ values = np.where(np.isfinite(values), values, np.nan)
+ return pd.DataFrame(values, index=panel.index, columns=panel.columns)
+
+
+def _aligned(panel: pd.DataFrame, reference: pd.DataFrame) -> pd.DataFrame:
+ return panel.reindex(index=reference.index, columns=reference.columns)
+
+
+def _mask(mask: pd.DataFrame | None, reference: pd.DataFrame) -> np.ndarray:
+ if mask is None:
+ return np.ones(reference.shape, dtype=bool)
+ _check_panel(mask, "mask")
+ aligned = _aligned(mask, reference)
+ if not aligned.isin([True, False]).all().all():
+ raise ValueError("mask must have boolean values for every factor time/asset")
+ return aligned.to_numpy(dtype=bool)
+
+
+def _positive_int(value: int, name: str, minimum: int = 1) -> None:
+ if isinstance(value, bool) or not isinstance(value, Integral) or value < minimum:
+ raise ValueError(f"{name} must be an integer >= {minimum}")
+
+
+def _mapping(value: Mapping[str, pd.DataFrame], name: str) -> None:
+ if not isinstance(value, Mapping):
+ raise ValueError(f"{name} must map names to DataFrames")
+ if any(not isinstance(key, str) or not key for key in value):
+ raise ValueError(f"{name} requires nonempty string names")
+
+
+def _weights(values: np.ndarray) -> np.ndarray:
+ return values / values.max()
+
+
+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
+ 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])
+
+
+def _rank(design: np.ndarray, weights: np.ndarray, rcond: float) -> int:
+ singular = np.linalg.svd(design * np.sqrt(weights)[:, None], compute_uv=False)
+ return int(np.count_nonzero(singular > rcond * singular[0]))
+
+
+def _correlation(a: np.ndarray, b: np.ndarray, weights: np.ndarray) -> float | None:
+ probability = weights / weights.sum()
+ a = a - probability @ a
+ b = b - probability @ b
+ scale_a = float(np.sqrt(probability @ np.square(a)))
+ scale_b = float(np.sqrt(probability @ np.square(b)))
+ if scale_a == 0 or scale_b == 0:
+ return None
+ return float(np.clip(probability @ ((a / scale_a) * (b / scale_b)), -1, 1))
+
+
+def _columns(
+ numeric: dict[str, pd.DataFrame],
+ categorical: dict[str, pd.DataFrame],
+ row: int,
+) -> dict[str, pd.DataFrame | pd.Series]:
+ candidates: dict[str, pd.DataFrame | pd.Series] = {
+ name: frame.iloc[row].to_frame(name) for name, frame in numeric.items()
+ }
+ for name, frame in categorical.items():
+ candidates[name] = frame.iloc[row].astype("string")
+ return candidates
+
+
+def _complete(candidate: pd.DataFrame | pd.Series) -> np.ndarray:
+ if isinstance(candidate, pd.Series):
+ return candidate.notna().to_numpy()
+ return np.isfinite(candidate.to_numpy()).all(axis=1)
+
+
+def _select(
+ candidates: dict[str, pd.DataFrame | pd.Series],
+ base: np.ndarray,
+ weights: np.ndarray,
+ selection: str,
+ min_coverage: float,
+ min_observations: int,
+ min_residual_dof: int,
+ rcond: float,
+) -> tuple[pd.DataFrame, np.ndarray, list[str], dict[str, str]]:
+ matrix = pd.DataFrame(index=next(iter(candidates.values())).index)
+ valid = base.copy()
+ if selection == "explicit":
+ for candidate in candidates.values():
+ valid &= _complete(candidate)
+ selected: list[str] = []
+ dropped: dict[str, str] = {}
+ for name, candidate in candidates.items():
+ complete = _complete(candidate)
+ trial_valid = valid & complete
+ if isinstance(candidate, pd.Series):
+ labels = candidate.where(trial_valid)
+ candidate = pd.get_dummies(
+ labels, prefix=name, prefix_sep="=", drop_first=True, dtype=float
+ )
+ candidate.loc[labels.isna(), :] = np.nan
+ # One observed category has no estimable group contrast.
+ if candidate.shape[1] == 0:
+ candidate[f"{name}=constant"] = np.where(labels.notna(), 0.0, np.nan)
+ trial = pd.concat([matrix, candidate], axis=1)
+ if not trial.columns.is_unique:
+ raise ValueError(
+ "encoded control names collide; rename the supplied controls"
+ )
+ reason = None
+ if selection == "auto":
+ count = int(trial_valid.sum())
+ if (base & complete).sum() / max(int(base.sum()), 1) < min_coverage:
+ reason = "low_coverage"
+ elif (
+ count < min_observations
+ or count - trial.shape[1] - 1 < min_residual_dof
+ ):
+ reason = "insufficient_sample_or_residual_dof"
+ else:
+ design = _design(
+ trial.to_numpy()[trial_valid], _weights(weights[trial_valid])
+ )
+ if (
+ _rank(design, _weights(weights[trial_valid]), rcond)
+ < design.shape[1]
+ ):
+ reason = "constant_or_collinear"
+ if reason:
+ dropped[name] = reason
+ else:
+ matrix, valid = trial, trial_valid
+ selected.append(name)
+ return matrix, valid, selected, dropped
+
+
+def neutralize_factor(
+ factor: pd.DataFrame,
+ controls: Mapping[str, pd.DataFrame] | None = None,
+ *,
+ categorical_controls: Mapping[str, pd.DataFrame] | None = None,
+ method: str = "ols",
+ weights: pd.DataFrame | None = None,
+ control_selection: str = "explicit",
+ min_coverage: float = 0.8,
+ min_observations: int = 10,
+ min_residual_dof: int = 2,
+ standardize: bool = True,
+ mask: pd.DataFrame | None = None,
+ rcond: float = 1e-10,
+) -> NeutralizationResult:
+ """Remove specified exposures separately at every input observation time.
+
+ Args:
+ factor: Numeric time-by-asset panel at any frequency, including irregular.
+ controls: Named numeric exposure panels, e.g. log_market_cap or beta.
+ categorical_controls: Named contemporaneous classifications, dummy-coded
+ per observation with one reference category omitted.
+ method: 'ols' or 'wls'. WLS uses positive finite observation weights.
+ weights: Required for WLS; missing/nonpositive cells are excluded.
+ control_selection: 'explicit' requires all controls; 'auto' greedily
+ selects in supplied order using coverage, rank and sample size only.
+ min_coverage: Minimum per-control coverage in auto mode (0 < value <= 1).
+ min_observations: Minimum complete assets in a fitted cross-section.
+ min_residual_dof: Minimum observations minus design rank (incl. intercept).
+ standardize: Scale residuals to unit weighted standard deviation. Exact
+ zero residuals stay zero; residuals are never winsorized or ranked.
+ mask: Fully aligned boolean tradable/universe panel.
+ rcond: Relative singular-value threshold for rank checking and fitting.
+
+ Returns:
+ Residuals on the original axes, with NaN for excluded/skipped cells.
+ Diagnostics disclose selected/dropped controls, coverage, rank, degrees
+ of freedom and weighted Pearson exposure before/after on the same sample.
+
+ Raises:
+ ValueError: Invalid panels, settings or a missing WLS weight panel.
+
+ Notes:
+ No publication-date verification is possible without source metadata.
+ Auto selection is data-quality filtering, not economic model selection.
+ Rank-deficient explicit fits and empty auto selections are skipped;
+ they never silently fall back to intercept-only demeaning. Compare IC
+ and backtests separately using identical samples and holding horizons.
+ """
+ factor = _numeric(factor, "factor")
+ controls = {} if controls is None else controls
+ categorical_controls = {} if categorical_controls is None else categorical_controls
+ _mapping(controls, "controls")
+ _mapping(categorical_controls, "categorical_controls")
+ if not controls and not categorical_controls:
+ raise ValueError("at least one control is required")
+ if set(controls) & set(categorical_controls):
+ raise ValueError("numeric and categorical control names must be distinct")
+ if method not in ("ols", "wls") or control_selection not in ("explicit", "auto"):
+ raise ValueError(
+ "method must be ols/wls; control_selection must be explicit/auto"
+ )
+ if not isinstance(standardize, bool):
+ raise ValueError("standardize must be boolean")
+ if (
+ not isinstance(min_coverage, Real)
+ or not np.isfinite(min_coverage)
+ or not 0 < min_coverage <= 1
+ ):
+ raise ValueError("min_coverage must be in (0, 1]")
+ if not isinstance(rcond, Real) or not np.isfinite(rcond) or not 0 < rcond < 1:
+ raise ValueError("rcond must be in (0, 1)")
+ _positive_int(min_observations, "min_observations", 2)
+ _positive_int(min_residual_dof, "min_residual_dof")
+ if method == "wls" and weights is None:
+ raise ValueError("wls requires weights")
+ if method == "ols" and weights is not None:
+ raise ValueError(
+ "weights require method='wls'; OLS never silently ignores them"
+ )
+ numeric = {
+ name: _aligned(_numeric(frame, name), factor)
+ for name, frame in controls.items()
+ }
+ categorical = {}
+ for name, frame in categorical_controls.items():
+ _check_panel(frame, name)
+ categorical[name] = _aligned(frame, factor)
+ allowed = _mask(mask, factor)
+ weight_values = (
+ _aligned(_numeric(weights, "weights"), factor).to_numpy()
+ if weights is not None
+ else np.ones(factor.shape)
+ )
+ residuals = pd.DataFrame(np.nan, index=factor.index, columns=factor.columns)
+ diagnostics = []
+ for row, timestamp in enumerate(factor.index):
+ y = factor.iloc[row].to_numpy()
+ w = weight_values[row]
+ signal_valid = allowed[row] & np.isfinite(y)
+ base = signal_valid & np.isfinite(w) & (w > 0)
+ matrix, valid, selected, dropped = _select(
+ _columns(numeric, categorical, row),
+ base,
+ w,
+ control_selection,
+ min_coverage,
+ min_observations,
+ min_residual_dof,
+ rcond,
+ )
+ count = int(valid.sum())
+ detail: dict[str, Any] = {
+ "time": str(timestamp),
+ "status": "skipped",
+ "selected_controls": selected,
+ "dropped_controls": dropped,
+ "input_count": int(signal_valid.sum()),
+ "complete_count": count,
+ "fit_count": 0,
+ "excluded_weight_count": int((signal_valid & ~base).sum()),
+ "coverage": 0.0,
+ }
+ diagnostics.append(detail)
+ if not selected:
+ detail["reason"] = "no_usable_controls"
+ continue
+ if count < min_observations:
+ detail["reason"] = "insufficient_sample"
+ continue
+ fit_w = _weights(w[valid])
+ x = matrix.to_numpy()[valid]
+ design = _design(x, fit_w)
+ rank = _rank(design, fit_w, rcond)
+ detail.update(rank=rank, residual_dof=count - rank)
+ if rank != design.shape[1]:
+ detail["reason"] = "rank_deficient"
+ continue
+ if count - rank < min_residual_dof:
+ detail["reason"] = "insufficient_residual_dof"
+ continue
+ fit_y = y[valid]
+ centered_y = fit_y - (fit_w / fit_w.sum()) @ fit_y
+ root_w = np.sqrt(fit_w)
+ beta = np.linalg.lstsq(
+ design * root_w[:, None], centered_y * root_w, rcond=rcond
+ )[0]
+ residual = centered_y - design @ beta
+ zero = (
+ np.linalg.norm(residual)
+ <= np.finfo(float).eps * np.linalg.norm(centered_y) * count
+ )
+ if zero:
+ residual = np.zeros(count)
+ elif standardize:
+ residual /= np.sqrt((fit_w / fit_w.sum()) @ np.square(residual))
+ residuals.iloc[row, np.flatnonzero(valid)] = residual
+ detail.update(
+ status="ok",
+ fit_count=count,
+ coverage=count / max(int(signal_valid.sum()), 1),
+ zero_residual=bool(zero),
+ exposure_before={
+ name: _correlation(fit_y, x[:, col], fit_w)
+ for col, name in enumerate(matrix.columns)
+ },
+ exposure_after={
+ name: _correlation(residual, x[:, col], fit_w)
+ for col, name in enumerate(matrix.columns)
+ },
+ )
+ return NeutralizationResult(residuals, diagnostics, method, control_selection)
+
+
+def pca_factors(
+ factors: Mapping[str, pd.DataFrame],
+ *,
+ n_components: int | float = 0.95,
+ min_observations: int = 10,
+ standardize: bool = True,
+ mask: pd.DataFrame | None = None,
+) -> FactorPCAResult:
+ """Compress factor columns using PCA fitted independently at each time.
+
+ Args:
+ factors: At least two named time-by-asset panels at any input frequency.
+ The first panel defines output axes; others are aligned without fills.
+ n_components: Positive component count, or explained-variance fraction
+ strictly between zero and one. Fractions may yield different counts
+ at different observation times; unused component rows stay NaN.
+ min_observations: Minimum assets observed in every supplied factor.
+ standardize: Standardize factor columns before PCA (correlation PCA).
+ mask: Fully aligned boolean tradable/universe panel.
+
+ Returns:
+ PC score panels with original time/asset axes and diagnostics containing
+ per-time loadings, means, scales and explained variance. Component signs
+ are anchored by their largest loading; component identities can still
+ rotate between times, particularly for similar eigenvalues.
+
+ Raises:
+ ValueError: Invalid settings, panels or fewer than two factors.
+
+ Notes:
+ PCA decorrelates components; it does not remove designated industry/style
+ exposures. No full-period covariance or future rows are used. Missing
+ assets are excluded, not imputed. Constant factors or insufficient rank
+ produce a skipped observation instead of invented component scores.
+ """
+ _mapping(factors, "factors")
+ if len(factors) < 2:
+ raise ValueError("PCA requires at least two factors")
+ _positive_int(min_observations, "min_observations", 2)
+ if not isinstance(standardize, bool):
+ raise ValueError("standardize must be boolean")
+ fixed_count = isinstance(n_components, Integral) and not isinstance(
+ n_components, bool
+ )
+ if fixed_count:
+ _positive_int(n_components, "n_components")
+ if n_components > len(factors):
+ raise ValueError("n_components cannot exceed the factor count")
+ elif (
+ isinstance(n_components, bool)
+ or not isinstance(n_components, Real)
+ or not 0 < n_components < 1
+ ):
+ raise ValueError(
+ "n_components must be a positive integer or fraction in (0, 1)"
+ )
+ panels = {name: _numeric(frame, name) for name, frame in factors.items()}
+ reference = next(iter(panels.values()))
+ arrays = [_aligned(frame, reference).to_numpy() for frame in panels.values()]
+ allowed = _mask(mask, reference)
+ components: dict[str, pd.DataFrame] = {}
+ diagnostics = []
+ for row, timestamp in enumerate(reference.index):
+ x = np.column_stack([array[row] for array in arrays])
+ eligible = allowed[row] & np.isfinite(x[:, 0])
+ valid = allowed[row] & np.isfinite(x).all(axis=1)
+ count = int(valid.sum())
+ detail: dict[str, Any] = {
+ "time": str(timestamp),
+ "status": "skipped",
+ "complete_count": count,
+ "fit_count": 0,
+ "input_count": int(eligible.sum()),
+ "coverage": 0.0,
+ }
+ diagnostics.append(detail)
+ if count < min_observations:
+ detail["reason"] = "insufficient_sample"
+ continue
+ x = x[valid]
+ means = x.mean(axis=0)
+ scales = x.std(axis=0)
+ if np.any(scales == 0):
+ detail["reason"] = "constant_factor"
+ continue
+ fitted_scales = scales if standardize else np.ones(len(panels))
+ z = (x - means) / fitted_scales
+ rank = np.linalg.matrix_rank(z)
+ detail["rank"] = int(rank)
+ if rank == 0 or (fixed_count and n_components > rank):
+ detail["reason"] = "insufficient_rank"
+ continue
+ model = PCA(n_components=min(rank, len(panels)), svd_solver="full")
+ scores = model.fit_transform(z)
+ keep = (
+ int(n_components)
+ if fixed_count
+ else min(
+ rank,
+ int(
+ np.searchsorted(
+ np.cumsum(model.explained_variance_ratio_), n_components
+ )
+ )
+ + 1,
+ )
+ )
+ loadings = model.components_[:keep].copy()
+ for col in range(keep):
+ if loadings[col, np.argmax(np.abs(loadings[col]))] < 0:
+ loadings[col] *= -1
+ scores[:, col] *= -1
+ name = f"PC{col + 1}"
+ if name not in components:
+ components[name] = pd.DataFrame(
+ np.nan, index=reference.index, columns=reference.columns
+ )
+ components[name].iloc[row, np.flatnonzero(valid)] = scores[:, col]
+ detail.update(
+ status="ok",
+ fit_count=count,
+ coverage=count / max(int(eligible.sum()), 1),
+ n_components=keep,
+ explained_variance_ratio=model.explained_variance_ratio_[:keep].tolist(),
+ retained_variance=float(model.explained_variance_ratio_[:keep].sum()),
+ means=dict(zip(panels, means.tolist())),
+ scales=dict(zip(panels, fitted_scales.tolist())),
+ loadings={
+ f"PC{col + 1}": dict(zip(panels, loadings[col].tolist()))
+ for col in range(keep)
+ },
+ )
+ return FactorPCAResult(components, diagnostics)
diff --git a/agent/src/skills/factor-research/SKILL.md b/agent/src/skills/factor-research/SKILL.md
index 4e786fa0c..4c388f1de 100644
--- a/agent/src/skills/factor-research/SKILL.md
+++ b/agent/src/skills/factor-research/SKILL.md
@@ -102,6 +102,46 @@ First orthogonalize the factors with the Schmidt process to remove collinearity,
4. Combine the orthogonalized factors with equal weights
```
+### Reusable Cross-Sectional Transforms
+
+Use `quantlib_call` with `module="neutralization"` (or import
+`src.quantlib.neutralization`) for tested transforms rather than retyping a
+regression. `neutralize_factor` removes named numeric/classification exposures
+with OLS or WLS. `pca_factors` compresses correlated factor columns into
+uncorrelated components; PCA alone does not make a factor industry/style neutral.
+
+Panels use observation-time rows and asset columns. Minute, hourly, daily,
+weekly, monthly and irregular observations all use the same contract: each row
+is fitted independently, with no resampling, forward filling or full-period fit.
+Single-asset time-series residualization is a different model and is not provided.
+Align controls, weights, classifications and the tradable mask to information
+available at that observation time; the library cannot verify publication dates.
+
+`control_selection="explicit"` is the default. Optional `"auto"` filters the
+supplied controls in insertion order by current coverage, rank and remaining
+degrees of freedom. It reports every selection/drop and never uses IC, returns
+or test-period performance. Supply economically justified controls: automatic
+quality filtering cannot decide which economic exposures should be removed.
+Missing/nonpositive WLS weights are excluded, not replaced. Missing exposures
+remain missing; rank-deficient explicit fits and empty auto selections skip the
+observation with diagnostics rather than silently changing the requested model.
+
+Inspect coverage and Pearson exposure before/after on the same sample. WLS
+reports weighted exposure; unweighted or rank correlations need not be zero.
+Residual standardization is linear (no post-fit clipping/ranking), preserving
+the fitted orthogonality. Exact zero residuals are reported as such, not as an
+effective new factor. Compare raw/residual IC and group backtests separately
+with `factor_analysis`, using identical universes, masks and holding horizons.
+The transform itself does not calculate Sharpe, trading costs or turnover.
+
+PCA reports per-time loadings, centering/scales, retained variance and component
+counts. Its loading-sign convention does not guarantee stable component identity
+across time; near-equal eigenvalues can rotate. Choose component counts/variance
+thresholds using research/training data rather than test-period performance.
+
+See [the neutralization workflow](references/neutralization.md) for
+Python and JSON-envelope examples, diagnostics and limits.
+
## Common Pitfalls
### Look-Ahead Bias
diff --git a/agent/src/skills/factor-research/references/neutralization.md b/agent/src/skills/factor-research/references/neutralization.md
new file mode 100644
index 000000000..56b0192d0
--- /dev/null
+++ b/agent/src/skills/factor-research/references/neutralization.md
@@ -0,0 +1,197 @@
+# Cross-sectional factor neutralization and PCA
+
+The optional `neutralization` quantlib module provides two pure-compute functions:
+
+| Function | Purpose |
+| --- | --- |
+| `neutralize_factor` | OLS/WLS residualization of one signal against numeric and categorical exposures |
+| `pca_factors` | PCA compression of two or more factor panels, with loadings and explained variance |
+
+Both are available through `quantlib_call`, including transports without shell
+tools. The factor research committee grants this tool to its miner, validator
+and combiner. Existing alpha formulas and backtests are unchanged; applying a
+transform remains a research choice.
+
+## Observation frequency and data contract
+
+Each DataFrame has observation times as rows and assets as columns. One row is
+one independent cross-section, whether observations are minute, hourly, daily,
+weekly, monthly, timezone-aware or irregular. No annualization, time pooling,
+sorting, resampling or forward filling occurs. A single asset is insufficient
+for this model; time-series/rolling regression requires a separate model.
+
+The first signal/factor panel defines output axes. Controls, weights and other
+factors align by exact time/asset labels; missing observations stay missing.
+Supply a full boolean mask when restricting the universe. Duplicate labels and
+invalid settings are rejected. Nonfinite numeric observations are treated as
+missing, not made into zero exposures or prices.
+
+All exposures, classifications and universe memberships must be known at the
+signal timestamp. Equal labels do not prove point-in-time availability. For
+example, a monthly fundamental exposure used by an hourly signal must already
+be expanded to hourly observations using verified publication times. The module
+does not perform this expansion or infer release dates. Never supply forward
+returns, labels, future classifications or test-period-selected factors.
+
+## OLS and WLS
+
+At each observation, fit an intercept plus the supplied exposures to the raw
+signal. Return the residual at the same time/asset cell. Numeric design columns
+are centered/scaled on that complete cross-section to improve conditioning;
+categorical groups use dummy columns with one reference level omitted. This
+scaling preserves the regression span; it does not winsorize inputs.
+
+```python
+from src.quantlib.neutralization import neutralize_factor, pca_factors
+
+# signal, log_market_cap, beta and industry are time-by-asset DataFrames.
+result = neutralize_factor(
+ signal,
+ controls={"log_market_cap": log_market_cap, "beta": beta},
+ categorical_controls={"industry": industry},
+ control_selection="explicit",
+ min_observations=10,
+)
+residual_signal = result.residuals
+diagnostics = result.diagnostics
+
+# Weights must be economically justified and available at each signal time.
+weighted = neutralize_factor(
+ signal,
+ controls={"log_market_cap": log_market_cap, "beta": beta},
+ method="wls",
+ weights=regression_weights,
+)
+```
+
+OLS does not accept a weight panel that it would silently ignore. WLS requires
+one and excludes missing, zero, negative or infinite weights; it never imputes
+unit weights. Constant/collinear explicit designs, insufficient complete assets
+or insufficient residual degrees of freedom yield NaN residual rows and a
+specific skip reason. Default minimum complete assets is 10, with at least two
+residual degrees of freedom; both thresholds are configurable, not frequency
+dependent.
+
+Residuals default to unit standard deviation under the regression weights.
+Exact zero residuals remain zero and are flagged: an entirely explained signal
+does not supply independent alpha. Set `standardize=False` for raw residuals.
+No post-fit winsorization/ranking is applied, since nonlinear transformations
+can reintroduce exposure. OLS residuals are linearly orthogonal in the fitted
+sample; WLS residuals are orthogonal under its weights. Neither guarantees
+statistical independence, zero Spearman correlation or out-of-sample alpha.
+
+## Automatic control quality selection
+
+`control_selection="auto"` selects from caller-supplied candidates. It processes
+numeric controls in insertion order, then categorical groups in insertion order.
+This order expresses caller priority and is reported. Categorical groups are
+accepted/rejected together, not selectively stripped of some industries.
+
+For each time independently, reject candidates with coverage below
+`min_coverage` (default 0.8) among finite, unmasked signals with valid weights,
+constant/collinear designs, too few joint complete assets, or too few remaining
+degrees of freedom. Selection checks the joint sample, since two individually
+well-covered controls can have a poor overlap. It does not inspect the signal's
+correlation with a candidate, IC, returns, Sharpe or future rows.
+
+```python
+automatic = neutralize_factor(
+ signal,
+ controls={"log_market_cap": log_market_cap, "beta": beta, "legacy": old_factor},
+ categorical_controls={"industry": industry},
+ control_selection="auto",
+ min_coverage=0.9,
+)
+```
+
+No accepted candidates means a skipped row, not silent intercept-only
+demeaning. Quality selection is not economic model discovery: decide whether
+size, value, momentum etc. should be stripped for the research question. Control
+sets can change over time and must be reviewed using the diagnostic history.
+
+## PCA
+
+```python
+pca = pca_factors(
+ {"value": value_factor, "momentum": momentum_factor, "quality": quality_factor},
+ n_components=0.95, # Or an integer component count.
+ standardize=True,
+)
+first_component = pca.components["PC1"]
+```
+
+PCA fits across assets at each timestamp, using the existing scikit-learn PCA
+implementation with a full SVD. It centers factors and optionally standardizes
+their scales. Complete assets only are used; constant factors and inadequate
+sample/rank yield explicit skips. A variance fraction in `(0, 1)` chooses enough
+components to meet that threshold; an integer requires exactly that many
+nonzero components. Threshold selection can therefore produce varying component
+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
+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.
+
+## Tool invocation
+
+Use `action="list"` or `action="describe"` with `module="neutralization"` to
+inspect the two functions. Pass indexed panels using the existing JSON envelope:
+
+```json
+{
+ "action": "call",
+ "module": "neutralization",
+ "function": "neutralize_factor",
+ "kwargs": {
+ "factor": {"__dataframe__": {
+ "index": ["2024-01-02T09:35:00Z"],
+ "columns": ["A", "B", "C", "D", "E", "F"],
+ "data": [[1.5, 2.2, 2.7, 4.5, 3.9, 6.2]]
+ }},
+ "controls": {"size": {"__dataframe__": {
+ "index": ["2024-01-02T09:35:00Z"],
+ "columns": ["A", "B", "C", "D", "E", "F"],
+ "data": [[1, 2, 3, 4, 5, 6]]
+ }}},
+ "min_observations": 4
+ }
+}
+```
+
+Results serialize panels plus diagnostic records through the existing tool
+contract. Its 5,000-value output budget still applies; a truncated result is
+explicitly marked and is not a complete panel. Use smaller chunks or direct
+Python imports with normal artifact writing for large research panels. Chunking
+time rows preserves these independent fits; do not chunk the asset dimension,
+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
+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`.
+
+Compare raw and transformed IC/quantile backtests separately with the existing
+`factor_analysis` tool, using matching masks and explicitly chosen holding
+horizons. Sharpe, costs, drawdowns and portfolio turnover require a separate
+backtest; this module does not infer them from factor values or issue a pass/fail
+investment verdict. Coverage and smaller exposure alone are not evidence of
+profitable alpha.
+
+## Local validation
+
+```bash
+pytest agent/tests/quantlib/test_neutralization.py agent/tests/test_quantlib_tool.py -q
+```
+
+Fixtures are synthetic and offline. Tests cover OLS/WLS reference fits, weighted
+orthogonality, classification/missingness, control selection, PCA reconstruction,
+multiple frequencies, irregular observations, future-row independence, input
+validation and the JSON tool contract. No data credentials or broker actions
+are needed.
diff --git a/agent/src/swarm/presets/factor_research_committee.yaml b/agent/src/swarm/presets/factor_research_committee.yaml
index b129482ae..fe48289a5 100644
--- a/agent/src/swarm/presets/factor_research_committee.yaml
+++ b/agent/src/swarm/presets/factor_research_committee.yaml
@@ -45,7 +45,7 @@ agents:
4. **Expected IC Direction and Magnitude** — Based on historical research or theoretical inference, estimate IC mean range (e.g., ±0.03–0.08)
5. **Factor Correlation Preview** — Expected correlation matrix among candidate factors to avoid information overlap
6. **Mining Frontier Assessment** — Which factors are already overcrowded and which still have room
- tools: [bash, read_file, write_file, load_skill, factor_analysis]
+ tools: [bash, read_file, write_file, load_skill, factor_analysis, quantlib_call]
skills: [factor-research, multi-factor]
max_iterations: 50
timeout_seconds: 1800
@@ -94,7 +94,7 @@ agents:
4. **Decay Curve Characteristics** — Optimal holding period recommendation for each factor (based on half-life); turnover rate estimate
5. **Robustness Assessment** — Whether OOS performance decays significantly; stability across market regimes; flag high-risk factors
6. **Overfitting Risk Warning** — Flag factors whose statistics look "too good to be true" and may suffer from data mining bias
- tools: [bash, read_file, write_file, load_skill, factor_analysis]
+ tools: [bash, read_file, write_file, load_skill, factor_analysis, quantlib_call]
skills: [quant-statistics, factor-research]
max_iterations: 50
timeout_seconds: 1800
@@ -132,7 +132,15 @@ agents:
- **Rebalancing Frequency**: Determine optimal rebalancing cycle based on factor decay half-life
Use load_skill("multi-factor") for multi-factor framework standards; load_skill("strategy-generate") for strategy code standards.
- Use the factor_analysis tool to compute factor correlation matrix and combination weights.
+ Use quantlib_call(module="neutralization", function="neutralize_factor") for
+ optional per-observation OLS/WLS residualization against justified controls;
+ use pca_factors from the same module for factor compression. These accept any
+ observation frequency and never pool across time. Auto control selection is
+ coverage/rank filtering in supplied order, not optimization on future returns.
+ Report selected/dropped controls, missingness and before/after exposures.
+ PCA is not industry/style neutralization; its component identities can rotate.
+ Use factor_analysis to compare raw/residual IC and quantile NAV on identical
+ samples and holding horizons; it does not compute combination weights.
Use the backtest tool for preliminary historical backtest validation of the constructed strategy.
## Output Requirements
@@ -142,7 +150,7 @@ agents:
4. **Stock Selection Strategy Rules** — Complete stock selection logic (universe → scoring → sector neutralization → position constraints → rebalancing rules)
5. **Expected Portfolio Characteristics** — Estimated annualized excess return, information ratio, turnover rate, average monthly holdings count
6. **Strategy Improvement Roadmap** — How to further enhance the strategy (add which factor types, adjust which parameters, consider which alternative data)
- tools: [bash, read_file, write_file, load_skill, factor_analysis, backtest]
+ tools: [bash, read_file, write_file, load_skill, factor_analysis, backtest, quantlib_call]
skills: [multi-factor, strategy-generate]
max_iterations: 50
timeout_seconds: 1800
diff --git a/agent/src/tools/quantlib_tool.py b/agent/src/tools/quantlib_tool.py
index 544093e07..8d7644dc8 100644
--- a/agent/src/tools/quantlib_tool.py
+++ b/agent/src/tools/quantlib_tool.py
@@ -75,6 +75,7 @@ ALLOWED_MODULES: dict[str, str] = {
"performance": "src.quantlib.performance",
"eventstudy": "src.quantlib.eventstudy",
"factormodel": "src.quantlib.factormodel",
+ "neutralization": "src.quantlib.neutralization",
"multipletesting": "src.quantlib.multipletesting",
"crossvalidation": "src.quantlib.crossvalidation",
"valuation.dcf": "src.quantlib.valuation.dcf",
@@ -274,7 +275,8 @@ class QuantlibCallTool(BaseTool):
"VaR/CVaR/EVT and VaR backtesting (Kupiec/Christoffersen/Basel), "
"Brinson-Fachler attribution, market impact, fund maths "
"(XIRR/MOIC/DPI/TVPI/PME/waterfalls), TWR/Dietz/MWR, event studies "
- "(CAR/CAAR/Patell/BMP), style factor models, deflated Sharpe and PBO, "
+ "(CAR/CAAR/Patell/BMP), style factor models, cross-sectional OLS/WLS "
+ "factor neutralization and PCA at any observation frequency, deflated Sharpe and PBO, "
"purged cross-validation, and the valuation engine (DCF / comps / "
"three-statement). Read-only and pure-compute: it fetches no data and "
"writes no files. Start with action='list' to see modules, then "
diff --git a/agent/tests/quantlib/test_neutralization.py b/agent/tests/quantlib/test_neutralization.py
new file mode 100644
index 000000000..679083174
--- /dev/null
+++ b/agent/tests/quantlib/test_neutralization.py
@@ -0,0 +1,411 @@
+"""Statistical invariants, timing boundaries and tool contract for factor transforms."""
+
+from __future__ import annotations
+
+import json
+
+import numpy as np
+import pandas as pd
+import pytest
+
+from src.quantlib.neutralization import neutralize_factor, pca_factors
+from src.tools.quantlib_tool import QuantlibCallTool
+
+
+def panel(values, times=None):
+ values = np.atleast_2d(values).astype(float)
+ if times is None:
+ times = pd.date_range("2024-01-01", periods=len(values), freq="D")
+ return pd.DataFrame(
+ values, index=times, columns=[f"s{i}" for i in range(values.shape[1])]
+ )
+
+
+def sample(n_rows=3, times=None):
+ rng = np.random.default_rng(20)
+ x = panel(rng.normal(size=(n_rows, 20)), times)
+ other = panel(rng.normal(size=(n_rows, 20)), times)
+ noise = panel(rng.normal(size=(n_rows, 20)), times)
+ return 3 + 2 * x - other + noise, {"size": x, "momentum": other}
+
+
+def test_ols_matches_independent_least_squares_and_preserves_inputs():
+ signal, controls = sample()
+ original = signal.copy(deep=True)
+ result = neutralize_factor(signal, controls, standardize=False)
+ for row in range(len(signal)):
+ x = np.column_stack(
+ [np.ones(20), *[value.iloc[row].to_numpy() for value in controls.values()]]
+ )
+ y = signal.iloc[row].to_numpy()
+ expected = y - x @ np.linalg.lstsq(x, y, rcond=None)[0]
+ np.testing.assert_allclose(result.residuals.iloc[row], expected, atol=1e-12)
+ np.testing.assert_allclose(x.T @ result.residuals.iloc[row], 0, atol=1e-12)
+ assert (
+ max(
+ abs(value)
+ for value in result.diagnostics[row]["exposure_after"].values()
+ )
+ < 1e-12
+ )
+ pd.testing.assert_frame_equal(signal, original)
+
+
+def test_wls_matches_reference_and_standardization_preserves_weighted_orthogonality():
+ signal, controls = sample()
+ weights = panel(np.tile(np.arange(1, 21), (3, 1)))
+ result = neutralize_factor(signal, controls, method="wls", weights=weights)
+ for row in range(len(signal)):
+ x = np.column_stack(
+ [np.ones(20), *[value.iloc[row].to_numpy() for value in controls.values()]]
+ )
+ y = signal.iloc[row].to_numpy()
+ w = weights.iloc[row].to_numpy()
+ beta = np.linalg.lstsq(x * np.sqrt(w)[:, None], y * np.sqrt(w), rcond=None)[0]
+ expected = y - x @ beta
+ expected /= np.sqrt(np.average(expected**2, weights=w))
+ np.testing.assert_allclose(result.residuals.iloc[row], expected, atol=1e-12)
+ np.testing.assert_allclose(
+ x.T @ (w * result.residuals.iloc[row]), 0, atol=1e-10
+ )
+ assert (
+ max(
+ abs(value)
+ for value in result.diagnostics[row]["exposure_after"].values()
+ )
+ < 1e-12
+ )
+ equal = neutralize_factor(signal, controls, method="wls", weights=weights * 0 + 1)
+ pd.testing.assert_frame_equal(
+ equal.residuals, neutralize_factor(signal, controls).residuals
+ )
+
+
+def test_industry_dummies_remove_group_means_and_preserve_missing_labels():
+ signal = panel([2, 4, 10, 14, 3, 7, 11, 15, 6, 8, 20, 22])
+ industry = pd.DataFrame(
+ [["A", "A", "B", "B"] * 3], index=signal.index, columns=signal.columns
+ )
+ industry.iloc[0, -1] = None
+ result = neutralize_factor(
+ signal, categorical_controls={"industry": industry}, standardize=False
+ )
+ for tag in ("A", "B"):
+ assert result.residuals.iloc[0][
+ industry.iloc[0] == tag
+ ].mean() == pytest.approx(0, abs=1e-12)
+ assert pd.isna(result.residuals.iloc[0, -1])
+ assert result.diagnostics[0]["fit_count"] == 11
+
+
+def test_auto_selection_reports_low_coverage_constants_and_collinearity():
+ signal, controls = sample()
+ sparse = controls["size"].copy()
+ sparse.iloc[:, :10] = np.nan
+ candidates = {
+ "size": controls["size"],
+ "size_copy": controls["size"] * 4 + 10,
+ "constant": controls["size"] * 0 + 1,
+ "sparse": sparse,
+ "momentum": controls["momentum"],
+ }
+ result = neutralize_factor(signal, candidates, control_selection="auto")
+ for detail in result.diagnostics:
+ assert detail["selected_controls"] == ["size", "momentum"]
+ assert detail["dropped_controls"] == {
+ "size_copy": "constant_or_collinear",
+ "constant": "constant_or_collinear",
+ "sparse": "low_coverage",
+ }
+ pd.testing.assert_frame_equal(
+ result.residuals, neutralize_factor(signal, controls).residuals
+ )
+
+
+def test_categorical_reference_uses_fitted_assets_not_masked_or_missing_assets():
+ signal, controls = sample(n_rows=1)
+ industry = pd.DataFrame(
+ [["A"] + ["B", "C"] * 9 + ["B"]], index=signal.index, columns=signal.columns
+ )
+ mask = pd.DataFrame(True, index=signal.index, columns=signal.columns)
+ mask.iloc[0, 0] = False
+ masked = neutralize_factor(
+ signal, categorical_controls={"industry": industry}, mask=mask
+ )
+ assert masked.diagnostics[0]["status"] == "ok"
+ controls["size"].iloc[0, 0] = np.nan
+ missing = neutralize_factor(
+ signal, controls, categorical_controls={"industry": industry}
+ )
+ assert missing.diagnostics[0]["status"] == "ok"
+ assert missing.diagnostics[0]["fit_count"] == 19
+ auto = neutralize_factor(
+ signal,
+ controls,
+ categorical_controls={"industry": industry},
+ control_selection="auto",
+ )
+ assert auto.diagnostics[0]["selected_controls"] == ["size", "momentum", "industry"]
+ pd.testing.assert_frame_equal(auto.residuals, missing.residuals)
+
+
+def test_encoded_control_name_collisions_are_rejected():
+ signal, controls = sample(n_rows=1)
+ industry = pd.DataFrame(
+ [["A", "B"] * 10], index=signal.index, columns=signal.columns
+ )
+ with pytest.raises(ValueError, match="names collide"):
+ neutralize_factor(
+ signal,
+ {"industry=B": controls["size"]},
+ categorical_controls={"industry": industry},
+ )
+
+
+def test_auto_checks_joint_coverage_and_skipped_output_coverage_is_zero():
+ signal, controls = sample(n_rows=1)
+ controls["size"].iloc[0, :4] = np.nan
+ controls["momentum"].iloc[0, 4:8] = np.nan
+ result = neutralize_factor(
+ signal, controls, control_selection="auto", min_observations=14
+ )
+ detail = result.diagnostics[0]
+ assert detail["selected_controls"] == ["size"]
+ assert detail["fit_count"] == 16
+ assert detail["coverage"] == pytest.approx(0.8)
+ assert (
+ detail["dropped_controls"]["momentum"] == "insufficient_sample_or_residual_dof"
+ )
+ skipped = neutralize_factor(signal, controls, min_observations=20)
+ assert skipped.diagnostics[0]["coverage"] == 0
+ assert skipped.diagnostics[0]["fit_count"] == 0
+
+
+def test_auto_selection_respects_residual_dof_and_does_not_fallback_to_demeaning():
+ signal, controls = sample()
+ result = neutralize_factor(
+ signal, controls, control_selection="auto", min_residual_dof=18
+ )
+ assert result.diagnostics[0]["selected_controls"] == ["size"]
+ assert (
+ result.diagnostics[0]["dropped_controls"]["momentum"]
+ == "insufficient_sample_or_residual_dof"
+ )
+ empty = neutralize_factor(
+ signal, {"constant": signal * 0 + 1}, control_selection="auto"
+ )
+ assert empty.residuals.isna().all().all()
+ assert all(detail["reason"] == "no_usable_controls" for detail in empty.diagnostics)
+
+
+def test_alignment_mask_and_wls_weight_exclusions_are_explicit():
+ signal, controls = sample()
+ aligned = {name: value.iloc[::-1, ::-1] for name, value in controls.items()}
+ pd.testing.assert_frame_equal(
+ neutralize_factor(signal, controls).residuals,
+ neutralize_factor(signal, aligned).residuals,
+ )
+ weights = signal * 0 + 1
+ weights.iloc[0, :4] = [0, -1, np.nan, np.inf]
+ mask = pd.DataFrame(True, index=signal.index, columns=signal.columns)
+ mask.iloc[0, 4] = False
+ signal.iloc[0, 5] = np.nan
+ controls["size"].iloc[0, 6] = np.nan
+ result = neutralize_factor(
+ signal, controls, method="wls", weights=weights, mask=mask
+ )
+ assert result.residuals.iloc[0, :7].isna().all()
+ assert result.diagnostics[0]["excluded_weight_count"] == 4
+ assert result.diagnostics[0]["fit_count"] == 13
+ pd.testing.assert_index_equal(result.residuals.index, signal.index)
+ pd.testing.assert_index_equal(result.residuals.columns, signal.columns)
+
+
[email protected]("frequency", ["min", "h", "D", "W", "MS"])
+def test_frequency_independence_and_no_future_row_influence(frequency):
+ times = pd.date_range("2024-01-01", periods=3, freq=frequency, tz="UTC")
+ signal, controls = sample(times=times)
+ result = neutralize_factor(signal, controls, control_selection="auto")
+ pca = pca_factors(controls, n_components=2)
+ signal.iloc[1:] *= -1000
+ for frame in controls.values():
+ frame.iloc[1:] *= 42
+ updated = neutralize_factor(signal, controls, control_selection="auto")
+ updated_pca = pca_factors(controls, n_components=2)
+ pd.testing.assert_series_equal(result.residuals.iloc[0], updated.residuals.iloc[0])
+ assert result.diagnostics[0] == updated.diagnostics[0]
+ for name in pca.components:
+ pd.testing.assert_series_equal(
+ pca.components[name].iloc[0], updated_pca.components[name].iloc[0]
+ )
+ assert pca.diagnostics[0] == updated_pca.diagnostics[0]
+
+
+def test_irregular_times_are_not_sorted_or_resampled_and_missing_dates_are_not_filled():
+ times = pd.to_datetime(["2024-02-01 10:01", "2024-01-04 09:32", "2024-02-01 10:08"])
+ signal, controls = sample(times=times)
+ controls["size"] = controls["size"].iloc[:2]
+ result = neutralize_factor(signal, controls)
+ pd.testing.assert_index_equal(result.residuals.index, times)
+ assert result.residuals.iloc[2].isna().all()
+ assert result.diagnostics[2]["reason"] == "insufficient_sample"
+
+
+def test_explicit_collinearity_is_skipped_and_exactly_explained_signal_stays_zero():
+ signal, controls = sample()
+ bad = neutralize_factor(signal, {"x": controls["size"], "copy": controls["size"]})
+ assert bad.residuals.isna().all().all()
+ assert all(detail["reason"] == "rank_deficient" for detail in bad.diagnostics)
+ perfect = neutralize_factor(controls["size"] * 2 + 3, {"size": controls["size"]})
+ np.testing.assert_array_equal(perfect.residuals, 0)
+ assert all(detail["zero_residual"] for detail in perfect.diagnostics)
+
+
+def test_tiny_signal_is_not_mistaken_for_zero_residual():
+ signal, controls = sample()
+ expected = neutralize_factor(signal, controls)
+ actual = neutralize_factor(signal * 1e-15, controls)
+ np.testing.assert_allclose(actual.residuals, expected.residuals, atol=1e-12)
+
+
+def test_pca_components_are_uncorrelated_and_full_components_reconstruct_inputs():
+ _, factors = sample()
+ result = pca_factors(factors, n_components=2)
+ for row, detail in enumerate(result.diagnostics):
+ scores = np.column_stack(
+ [frame.iloc[row].to_numpy() for frame in result.components.values()]
+ )
+ covariance = np.cov(scores.T)
+ assert covariance[0, 1] == pytest.approx(0, abs=1e-12)
+ loadings = np.array(
+ [list(detail["loadings"][name].values()) for name in result.components]
+ )
+ x = np.column_stack([frame.iloc[row].to_numpy() for frame in factors.values()])
+ expected = (x - x.mean(axis=0)) / x.std(axis=0)
+ 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
+
+
+def test_pca_variance_fraction_handles_variable_component_counts_and_missing_assets():
+ _, factors = sample()
+ factors["momentum"].iloc[0] = factors["size"].iloc[0] * 2
+ factors["momentum"].iloc[2, 0] = np.nan
+ result = pca_factors(factors, n_components=0.95)
+ assert result.diagnostics[0]["n_components"] == 1
+ assert result.diagnostics[1]["n_components"] == 2
+ assert result.components["PC2"].iloc[0].isna().all()
+ assert pd.isna(result.components["PC1"].iloc[2, 0])
+ assert all(detail["retained_variance"] >= 0.95 for detail in result.diagnostics)
+
+
+def test_pca_constant_and_insufficient_rank_observations_are_skipped():
+ _, factors = sample()
+ constant = pca_factors({"x": factors["size"], "constant": factors["size"] * 0 + 1})
+ assert not constant.components
+ assert all(detail["reason"] == "constant_factor" for detail in constant.diagnostics)
+ rank_one = pca_factors(
+ {"x": factors["size"], "copy": factors["size"]}, n_components=2
+ )
+ assert not rank_one.components
+ assert all(
+ detail["reason"] == "insufficient_rank" for detail in rank_one.diagnostics
+ )
+ short = pca_factors({name: frame.iloc[:, :3] for name, frame in factors.items()})
+ assert all(
+ detail["reason"] == "insufficient_sample" for detail in short.diagnostics
+ )
+
+
+ "kwargs",
+ [
+ {"method": "unknown"},
+ {"control_selection": "best_ic"},
+ {"method": "wls"},
+ {"min_coverage": 0},
+ {"min_coverage": np.nan},
+ {"min_observations": True},
+ {"min_residual_dof": 0},
+ {"rcond": 0},
+ {"standardize": "yes"},
+ ],
+)
+def test_invalid_residualization_settings_are_rejected(kwargs):
+ signal, controls = sample()
+ with pytest.raises(ValueError):
+ neutralize_factor(signal, controls, **kwargs)
+
+
+def test_invalid_panels_masks_and_weight_method_combinations_are_rejected():
+ signal, controls = sample()
+ with pytest.raises(ValueError, match="at least one"):
+ neutralize_factor(signal)
+ with pytest.raises(ValueError, match="unique"):
+ neutralize_factor(pd.concat([signal, signal]), controls)
+ with pytest.raises(ValueError, match="boolean"):
+ neutralize_factor(signal, controls, mask=signal * 0 + 2)
+ with pytest.raises(ValueError, match="weights require"):
+ neutralize_factor(signal, controls, weights=signal * 0 + 1)
+ with pytest.raises(ValueError, match="distinct"):
+ neutralize_factor(signal, controls, categorical_controls=controls)
+
+
[email protected]("count", [0, -1, True, 1.0, 1.1, np.nan, 3])
+def test_invalid_pca_component_counts_are_rejected(count):
+ _, factors = sample()
+ with pytest.raises(ValueError):
+ pca_factors(factors, n_components=count)
+
+
+def envelope(frame):
+ return {
+ "__dataframe__": {
+ "index": [str(time) for time in frame.index],
+ "columns": list(frame.columns),
+ "data": frame.to_numpy().tolist(),
+ }
+ }
+
+
+def test_quantlib_tool_lists_calls_and_serializes_both_transforms():
+ tool = QuantlibCallTool()
+ listing = json.loads(tool.execute(action="list", module="neutralization"))
+ assert {item["name"] for item in listing["functions"]} == {
+ "neutralize_factor",
+ "pca_factors",
+ }
+ signal, controls = sample(n_rows=1)
+ encoded = {name: envelope(frame) for name, frame in controls.items()}
+ residual = json.loads(
+ tool.execute(
+ action="call",
+ module="neutralization",
+ function="neutralize_factor",
+ kwargs={"factor": envelope(signal), "controls": encoded},
+ )
+ )
+ assert residual["ok"]
+ assert residual["result"]["diagnostics"][0]["status"] == "ok"
+ assert "__dataframe__" in residual["result"]["residuals"]
+ pca = json.loads(
+ tool.execute(
+ action="call",
+ module="neutralization",
+ function="pca_factors",
+ kwargs={"factors": encoded, "n_components": 2},
+ )
+ )
+ assert pca["ok"]
+ assert set(pca["result"]["components"]) == {"PC1", "PC2"}
+ error = json.loads(
+ tool.execute(
+ action="call",
+ module="neutralization",
+ function="neutralize_factor",
+ kwargs={"factor": envelope(signal), "controls": encoded, "method": "wls"},
+ )
+ )
+ assert not error["ok"]
+ assert "requires weights" in error["error"]