"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(quantlib): add cross-sectional factor combination with walk-forward weights (#1953)
BH Hu90819468a502
diff --git a/README.md b/README.mdindex ba709cdbb..0b3fe650d 100644--- a/README.md+++ b/README.md@@ -879,7 +879,7 @@ The shared backtest market classifier recognizes `BTC/USD`, `ETH/USD`,</details><details>-<summary><b>Quant Library</b> <sub>308 tested functions across 24 modules, callable from every transport</sub></summary>+<summary><b>Quant Library</b> <sub>309 tested functions across 25 modules, callable from every transport</sub></summary>`src/quantlib` holds one tested implementation of each piece of finance math theagent needs. Skills **import** these rather than carrying formulas inside@@ -897,6 +897,7 @@ that is a bug, not a pattern.| `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). |+| `combination` | Optional walk-forward IC/ICIR-weighted composite of several factor panels, with per-factor and composite diagnostics; a caller-supplied weight table handles any other method. [Workflow and checklist](agent/src/skills/factor-research/references/combination.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/README_ar.md b/README_ar.mdindex 89d21726b..c068b623c 100644--- a/README_ar.md+++ b/README_ar.md@@ -730,7 +730,7 @@ LONGBRIDGE_ACCESS_TOKEN=...</details><details>-<summary><b>Quant Library</b> <sub>308 دالة مختبَرة عبر 24 وحدة، قابلة للاستدعاء من كل المسارات</sub></summary>+<summary><b>Quant Library</b> <sub>309 دالة مختبَرة عبر 25 وحدة، قابلة للاستدعاء من كل المسارات</sub></summary>يحتفظ `src/quantlib` بتنفيذ مختبَر **واحد فقط** لكل قطعة من الرياضيات المالية التييحتاجها الـ agent. صارت الـ skills **تستورد** هذه الدوال بدلاً من حمل الصيغ داخل كتلdiff --git a/README_es.md b/README_es.mdindex a493fe267..602efae4f 100644--- a/README_es.md+++ b/README_es.md@@ -735,7 +735,7 @@ Barras: 1m / 5m / 15m / 30m / 1H / 4H / 1D, más semanales / mensuales (1W / 1M,</details><details>-<summary><b>Quant Library</b> <sub>308 funciones probadas en 24 módulos, invocables desde cualquier transporte</sub></summary>+<summary><b>Quant Library</b> <sub>309 funciones probadas en 25 módulos, invocables desde cualquier transporte</sub></summary>`src/quantlib` contiene una implementación probada de cada pieza de matemáticafinanciera que el agente necesita. Las skills **importan** estas funciones endiff --git a/README_id.md b/README_id.mdindex ad5cae605..68af3e5e4 100644--- a/README_id.md+++ b/README_id.md@@ -896,7 +896,7 @@ Bar: 1m / 5m / 15m / 30m / 1H / 4H / 1D, plus mingguan / bulanan (1W / 1M, diban</details><details>-<summary><b>Quant Library</b> <sub>308 fungsi teruji dalam 24 modul, dapat dipanggil dari setiap transport</sub></summary>+<summary><b>Quant Library</b> <sub>309 fungsi teruji dalam 25 modul, dapat dipanggil dari setiap transport</sub></summary>`src/quantlib` menyimpan satu implementasi teruji untuk setiap matematika finansial yang dibutuhkan agent.Skill **mengimpor** fungsi-fungsi ini alih-alih membawa formula di dalamdiff --git a/README_ja.md b/README_ja.mdindex d1b1ae9e5..6dc46bd7f 100644--- a/README_ja.md+++ b/README_ja.md@@ -730,7 +730,7 @@ Bars: 1m / 5m / 15m / 30m / 1H / 4H / 1D, plus weekly / monthly (1W / 1M, built</details><details>-<summary><b>Quant Library</b> <sub>24 モジュール・308 個のテスト済み関数、すべての経路から呼び出し可能</sub></summary>+<summary><b>Quant Library</b> <sub>25 モジュール・309 個のテスト済み関数、すべての経路から呼び出し可能</sub></summary>`src/quantlib` は、agent が必要とする金融数学のそれぞれについて、テスト済みの実装を**1 つだけ**保持します。skill はこれらを **import** するようになり、markdown コードdiff --git a/README_ko.md b/README_ko.mdindex 383451774..308bbc41c 100644--- a/README_ko.md+++ b/README_ko.md@@ -730,7 +730,7 @@ Bars: 1m / 5m / 15m / 30m / 1H / 4H / 1D, plus weekly / monthly (1W / 1M, built</details><details>-<summary><b>Quant Library</b> <sub>24개 모듈 308개의 테스트된 함수, 모든 경로에서 호출 가능</sub></summary>+<summary><b>Quant Library</b> <sub>25개 모듈 309개의 테스트된 함수, 모든 경로에서 호출 가능</sub></summary>`src/quantlib`는 agent가 필요로 하는 각 금융 수학에 대해 테스트된 구현을 **하나씩만**보유합니다. skill은 이제 이 함수들을 **import**하며, markdown 코드 블록 안에 수식을diff --git a/README_zh.md b/README_zh.mdindex c45d9bf60..494d1696a 100644--- a/README_zh.md+++ b/README_zh.md@@ -743,7 +743,7 @@ Bar 周期:1m / 5m / 15m / 30m / 1H / 4H / 1D,以及由日线合成的周线</details><details>-<summary><b>Quant Library</b> <sub>24 个模块 308 个经测试的函数,四条通路皆可调用</sub></summary>+<summary><b>Quant Library</b> <sub>25 个模块 309 个经测试的函数,四条通路皆可调用</sub></summary>`src/quantlib` 为 agent 需要的每一块金融数学各提供**一份**经测试的实现。skill 现在是**import** 这些函数,而不再把公式抄在 markdown 代码块里——如果你在某个 `SKILL.md`diff --git a/agent/src/quantlib/__init__.py b/agent/src/quantlib/__init__.pyindex 5f1aea7c6..fab42b7de 100644--- a/agent/src/quantlib/__init__.py+++ b/agent/src/quantlib/__init__.py@@ -24,6 +24,7 @@ Submodules:eventstudy Abnormal returns around dated events (CAR/CAAR, Patell, BMP)factormodel Cross-sectional style exposures, factor returns, style driftneutralization Per-observation OLS/WLS factor residuals and cross-sectional PCA+ combination Walk-forward IC/ICIR composites of several factor panelsattribution Brinson-Fachler allocation/selection/interactionimpact Market-impact and slippage modelsfundmath Private-markets fund maths on the irregular cash-flow spinediff --git a/agent/src/quantlib/combination.py b/agent/src/quantlib/combination.pynew file mode 100644index 000000000..7721f58b0--- /dev/null+++ b/agent/src/quantlib/combination.py@@ -0,0 +1,473 @@+"""Cross-sectional factor combination with caller-owned or IC-based weights.++Each panel row is one observation time and each column is one asset -- the same+contract as :mod:`src.quantlib.neutralization`. Several factor panels are+combined into a single composite score per ``(time, asset)``.++There is no complete list of combination methods: equal weight, IC weighting,+decayed IC, maximum IC, regression weights, trained models and risk-based+weights all exist, and new ones keep appearing. This module therefore does not+enumerate methods. It fixes the *weight contract* instead:++* ``weights`` accepts a static mapping or a ``time x factor`` DataFrame. Any+ method that produces such a table -- fitted elsewhere, tuned however the+ caller likes -- can be combined here. A table is auditable, reproducible and+ transportable over MCP; a callback is none of those.+* ``equal``, ``ic`` and ``icir`` are shipped as transparent baselines, not as a+ catalogue: they need no tuning, no dependency and no training.++Weight timing is the one rule that cannot be relaxed: a weight applied at row+``t`` may only use information from rows ``< t``. ``ic``/``icir`` enforce this+internally; a caller-supplied table must already respect it. Passing full-sample+IC weights leaks the evaluation period into the signal.++This module combines signals; it does not size positions, penalise turnover or+build a risk model. Hand the composite panel to a signal engine or a backtest.++Rank IC is computed locally rather than by importing+:mod:`src.factors.factor_analysis_core`: the factors package already imports+``src.quantlib.multipletesting``, so the reverse import would be circular.+"""++from __future__ import annotations++import warnings+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++__all__ = ["combine_factors"]++_METHODS: tuple[str, ...] = ("equal", "explicit", "ic", "icir")+_WEIGHTED_METHODS: tuple[str, ...] = ("ic", "icir")+_MIN_ASSETS = 5+_STD_FLOOR = 1e-12+++@dataclass+class CombinationResult:+ """Composite panel, per-row weights and research diagnostics.++ Attributes:+ composite: Composite score per observation time and asset. ``NaN``+ wherever no factor was available or no weight had been estimated+ yet; never silently zero.+ weights: Weight per observation time and factor. Rows before the first+ estimable weight are ``NaN``; weights are held between rebalances.+ diagnostics: ``factor_ic``/``composite_ic``/``correlation`` summaries,+ weight turnover and the settings that produced them.+ method: The combination method that was requested.+ """++ composite: pd.DataFrame+ weights: pd.DataFrame+ diagnostics: dict[str, Any]+ method: str+++# --- input guards (same shape as src/quantlib/neutralization.py) ---+++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 _positive_int(value: Any, 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 _ordered_union(labels: list[pd.Index]) -> pd.Index:+ """Union of labels in first-seen order (input order is preserved)."""+ seen: dict[Any, None] = {}+ for index in labels:+ for label in index:+ seen.setdefault(label, None)+ return pd.Index(list(seen))+++def _bounded(values: np.ndarray) -> np.ndarray:+ """Scale each row by its largest magnitude.++ Centering and squared norms can overflow for large inputs (market caps) and+ underflow into a false zero variance for tiny ones (ratios); dividing by the+ row maximum first keeps the arithmetic inside the float range. Mirrors the+ guard in :func:`src.quantlib.neutralization._bounded`.+ """+ units = np.max(np.abs(values), axis=1, keepdims=True)+ units = np.where(np.isfinite(units) & (units > 0), units, 1.0)+ return values / units+++def _cross_sectional_z(panel: pd.DataFrame) -> pd.DataFrame:+ """Per-row z-score; rows with fewer than two values or no spread become NaN."""+ values = _bounded(panel.to_numpy(dtype=float))+ counts = np.sum(np.isfinite(values), axis=1, keepdims=True)+ with warnings.catch_warnings():+ warnings.simplefilter("ignore", RuntimeWarning)+ with np.errstate(invalid="ignore", divide="ignore"):+ mean = np.nanmean(values, axis=1, keepdims=True)+ std = np.nanstd(values, axis=1, ddof=1, keepdims=True)+ z = (values - mean) / std+ usable = np.isfinite(std) & (std > _STD_FLOOR) & (counts >= 2)+ z = np.where(usable, z, np.nan)+ return pd.DataFrame(z, index=panel.index, columns=panel.columns)+++# --- IC estimation ---+++def _rank_ic(factor: pd.Series, forward: pd.Series, min_assets: int) -> float | None:+ """Spearman correlation of one cross-section; ``None`` when unestimable."""+ mask = factor.notna() & forward.notna()+ if int(mask.sum()) < min_assets:+ return None+ left = factor[mask].rank()+ right = forward[mask].rank()+ left = left - left.mean()+ right = right - right.mean()+ denominator = float(np.sqrt((left * left).sum() * (right * right).sum()))+ if not np.isfinite(denominator) or denominator <= 0:+ return None+ return float((left * right).sum() / denominator)+++def _ic_series(factor: pd.DataFrame, forward: pd.DataFrame, min_assets: int) -> pd.Series:+ values = [_rank_ic(factor.loc[time], forward.loc[time], min_assets) for time in factor.index]+ return pd.Series(values, index=factor.index, dtype=float)+++def _ic_stats(ic: pd.Series) -> dict[str, Any]:+ clean = ic.dropna()+ count = int(clean.size)+ if count == 0:+ return {+ "ic_mean": None,+ "ic_std": None,+ "ir": None,+ "ic_positive_ratio": None,+ "n_obs": 0,+ }+ mean = float(clean.mean())+ std = float(clean.std(ddof=1)) if count > 1 else 0.0+ return {+ "ic_mean": mean,+ "ic_std": std,+ "ir": (mean / std) if std > 0 else None,+ "ic_positive_ratio": float((clean > 0).mean()),+ "n_obs": count,+ }+++def _mean_rank_correlation(panels: Mapping[str, pd.DataFrame], min_assets: int) -> pd.DataFrame:+ """Average per-date Spearman correlation between factor panels."""+ names = list(panels)+ total = pd.DataFrame(0.0, index=names, columns=names)+ seen = pd.DataFrame(0, index=names, columns=names)+ for time in next(iter(panels.values())).index:+ cross = pd.DataFrame({name: panels[name].loc[time] for name in names})+ cross = cross.dropna(how="any")+ if len(cross) < min_assets:+ continue+ correlation = cross.corr(method="spearman")+ total = total.add(correlation.fillna(0.0))+ seen = seen.add(correlation.notna().astype(int))+ return total / seen.replace(0, np.nan)+++# --- weights ---+++def _constant_weights(names: list[str], index: pd.Index, values: Mapping[str, float]) -> pd.DataFrame:+ row = np.array([float(values[name]) for name in names], dtype=float)+ return pd.DataFrame(np.tile(row, (len(index), 1)), index=index, columns=names)+++def _walk_forward_weights(+ ic_history: Mapping[str, pd.Series],+ index: pd.Index,+ *,+ method: str,+ window: int | None,+ min_periods: int,+ rebalance: int,+ insufficient: str,+) -> pd.DataFrame:+ """Estimate weights at each rebalance from strictly earlier IC values."""+ names = list(ic_history)+ frame = pd.DataFrame(np.nan, index=index, columns=names)+ for position in range(0, len(index), rebalance):+ estimates: dict[str, float] = {}+ for name in names:+ history = ic_history[name].iloc[:position].dropna()+ if window is not None:+ history = history.iloc[-window:]+ if len(history) < min_periods:+ continue+ if method == "ic":+ value = float(history.mean())+ else:+ deviation = float(history.std(ddof=1))+ if not deviation > 0:+ continue+ value = float(history.mean() / deviation)+ if np.isfinite(value):+ estimates[name] = value+ if not estimates:+ if insufficient == "equal":+ frame.iloc[position] = 1.0+ continue+ total = float(sum(abs(value) for value in estimates.values()))+ if not np.isfinite(total) or total <= 0:+ continue+ frame.iloc[position] = [estimates.get(name, 0.0) / total for name in names]+ return frame.ffill()+++def _static_weights(weights: Mapping[str, float], names: list[str], index: pd.Index) -> pd.DataFrame:+ missing = [name for name in names if name not in weights]+ unknown = [name for name in weights if name not in names]+ if missing or unknown:+ raise ValueError(f"weights must cover every factor exactly; missing={missing}, unknown={unknown}")+ values: dict[str, float] = {}+ for name in names:+ value = weights[name]+ if isinstance(value, bool) or not isinstance(value, Real):+ raise ValueError(f"weight for {name!r} must be a real number")+ if not np.isfinite(float(value)):+ raise ValueError(f"weight for {name!r} must be finite")+ values[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})+++def _table_weights(weights: pd.DataFrame, names: list[str], index: pd.Index) -> pd.DataFrame:+ """Align a caller-supplied ``time x factor`` weight table.++ Rows may be supplied only at rebalance dates; they are held forward. A+ missing weight is excluded from that row rather than read as zero, and rows+ whose weights are all missing stay ``NaN`` (honest empty, no default).+ """+ _check_panel(weights, "weights")+ missing = [name for name in names if name not in weights.columns]+ unknown = [column for column in weights.columns if column not in names]+ if missing or unknown:+ raise ValueError(f"weight table must cover every factor exactly; missing={missing}, unknown={unknown}")+ try:+ table = weights.reindex(index=index)[names].to_numpy(dtype=float, na_value=np.nan)+ except (TypeError, ValueError) as exc:+ raise ValueError("weight table must contain numeric values") from exc+ table = np.where(np.isfinite(table), table, np.nan)+ total = 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)+ return pd.DataFrame(table, index=index, columns=names).ffill()+++def _turnover(weights: pd.DataFrame) -> float | None:+ effective = weights.dropna(how="all")+ if len(effective) < 2:+ return None+ change = effective.diff().iloc[1:].abs().sum(axis=1)+ return float(change.mean())+++# --- public entry point ---+++def combine_factors(+ panels: Mapping[str, pd.DataFrame],+ returns: pd.DataFrame | None = None,+ *,+ method: str = "equal",+ weights: Mapping[str, float] | pd.DataFrame | None = None,+ window: int | None = None,+ rebalance: int = 1,+ standardize: bool = True,+ min_assets: int = _MIN_ASSETS,+ min_periods: int = 20,+ insufficient: str = "skip",+) -> CombinationResult:+ """Combine factor panels into one composite score.++ Args:+ panels: Factor name -> panel (time x asset) of factor values.+ returns: Forward-return panel aligned to the factor panels: the value at+ row ``t`` is the return earned *after* observing ``t``. Required for+ ``method="ic"`` and ``"icir"``, unused otherwise.+ method: ``"equal"``, ``"explicit"``, ``"ic"`` (mean rank IC weights) or+ ``"icir"`` (mean/std rank IC weights). IC weights keep the sign, so+ a reversed factor receives a negative weight instead of being+ silently flipped. Use ``"explicit"`` to bring any other method:+ decayed IC, maximum IC, regression or trained weights, risk parity.+ weights: Required by ``method="explicit"`` and rejected otherwise.+ Either a mapping (factor -> constant weight) or a ``time x factor``+ DataFrame for weights that change over time; table rows may cover+ only rebalance dates and are held forward. Values are normalised by+ their absolute sum. A caller-supplied table must already respect+ walk-forward timing: this function cannot see how it was produced.+ window: Number of trailing IC observations used to estimate a weight.+ ``None`` uses all strictly earlier observations.+ rebalance: Re-estimate weights every ``rebalance`` rows; between+ rebalances the last estimate is held.+ standardize: Cross-sectionally z-score each factor per row before+ summing. Recommended when factor units differ.+ min_assets: Minimum instruments with both a factor and a return value+ for an IC observation to count.+ min_periods: Minimum IC observations required before a weight is+ estimated.+ insufficient: ``"skip"`` leaves rows before the first estimate ``NaN``+ (honest empty); ``"equal"`` falls back to equal weights there.++ Returns:+ A :class:`CombinationResult` with the composite panel, the per-row+ weight table and diagnostics.++ Raises:+ ValueError: On unknown method, malformed panels, missing returns for a+ weighted method, or weights that do not match the panel names.+ """+ if method not in _METHODS:+ raise ValueError(f"method must be one of {_METHODS}, got {method!r}")+ if weights is not None and method != "explicit":+ raise ValueError("weights is only accepted with method='explicit'")+ if not isinstance(panels, Mapping) or not panels:+ raise ValueError("panels must be a non-empty mapping of name -> DataFrame")+ for name, panel in panels.items():+ if not isinstance(name, str) or not name:+ raise ValueError("panel names must be non-empty strings")+ _check_panel(panel, f"panels[{name!r}]")+ _positive_int(rebalance, "rebalance")+ _positive_int(min_assets, "min_assets", minimum=2)+ _positive_int(min_periods, "min_periods", minimum=2)+ if window is not None:+ _positive_int(window, "window", minimum=2)+ if insufficient not in ("skip", "equal"):+ raise ValueError("insufficient must be 'skip' or 'equal'")++ names = list(panels)+ index = _ordered_union([panels[name].index for name in names])+ columns = _ordered_union([panels[name].columns for name in names])+ aligned = {+ name: _numeric(panels[name], f"panels[{name!r}]").reindex(index=index, columns=columns) for name in names+ }+ empty = [name for name in names if aligned[name].isna().all().all()]+ if len(empty) == len(names):+ raise ValueError("every factor panel is empty after alignment")++ forward: pd.DataFrame | None = None+ if method in _WEIGHTED_METHODS:+ if returns is None:+ raise ValueError(f"method={method!r} requires a forward-return panel")+ forward = _numeric(returns, "returns").reindex(index=index, columns=columns)++ explicit: Any = None+ if method == "explicit":+ if weights is None:+ raise ValueError("method='explicit' requires weights")+ if isinstance(weights, pd.DataFrame):+ explicit = _table_weights(weights, names, index)+ elif isinstance(weights, Mapping):+ explicit = _static_weights(weights, names, index)+ else:+ raise ValueError("weights must be a mapping of factor -> number or a time x factor DataFrame")++ factor_ic: dict[str, pd.Series] = {}+ if method in _WEIGHTED_METHODS and forward is not None:+ factor_ic = {name: _ic_series(aligned[name], forward, min_assets) for name in names}++ if method == "equal":+ weights_frame = _constant_weights(names, index, {name: 1.0 / len(names) for name in names})+ elif method == "explicit" and isinstance(explicit, pd.DataFrame):+ weights_frame = explicit+ else:+ weights_frame = _walk_forward_weights(+ factor_ic,+ index,+ method=method,+ window=window,+ min_periods=min_periods,+ rebalance=rebalance,+ insufficient=insufficient,+ )++ prepared = {name: _cross_sectional_z(aligned[name]) if standardize else aligned[name] for name in names}++ shape = (len(index), len(columns))+ numerator = np.zeros(shape, dtype=float)+ denominator = np.zeros(shape, dtype=float)+ for name in names:+ values = prepared[name].to_numpy(dtype=float)+ weight = weights_frame[name].to_numpy(dtype=float)[:, None]+ available = np.isfinite(values) & np.isfinite(weight)+ numerator += np.where(available, weight * np.nan_to_num(values), 0.0)+ denominator += np.where(available, np.abs(weight), 0.0)+ composite = np.divide(+ numerator,+ denominator,+ out=np.full(shape, np.nan),+ where=denominator > 0,+ )++ diagnostics: dict[str, Any] = {+ "method": method,+ "weights_source": (+ "caller_table"+ if isinstance(explicit, pd.DataFrame)+ else ("caller_mapping" if isinstance(explicit, Mapping) else method)+ ),+ "standardize": bool(standardize),+ "window": window,+ "rebalance": rebalance,+ "n_factors": len(names),+ "n_observations": int(len(index)),+ "n_assets": int(len(columns)),+ "factor_names": names,+ "factor_ic": pd.DataFrame({name: _ic_stats(factor_ic[name]) for name in names}).T if factor_ic else None,+ "composite_ic": _ic_stats(+ _ic_series(+ pd.DataFrame(composite, index=index, columns=columns),+ forward,+ min_assets,+ )+ )+ if forward is not None+ else None,+ "correlation": _mean_rank_correlation(prepared, min_assets) if len(names) > 1 else None,+ "weight_turnover": _turnover(weights_frame),+ "rows_without_weights": int(weights_frame.isna().all(axis=1).sum()),+ "notes": [+ "factor_ic and composite_ic are full-sample research diagnostics, "+ "not the walk-forward weights used to build the composite",+ "composite is the weighted mean of available factors per row, "+ "renormalised by the available absolute weight",+ f"weights are re-estimated every {rebalance} observation(s); set "+ "rebalance to the holding horizon the strategy will use",+ ],+ }++ return CombinationResult(+ composite=pd.DataFrame(composite, index=index, columns=columns),+ weights=weights_frame,+ diagnostics=diagnostics,+ method=method,+ )diff --git a/agent/src/skills/factor-research/SKILL.md b/agent/src/skills/factor-research/SKILL.mdindex 4c388f1de..6e81109ca 100644--- a/agent/src/skills/factor-research/SKILL.md+++ b/agent/src/skills/factor-research/SKILL.md@@ -102,6 +102,35 @@ First orthogonalize the factors with the Schmidt process to remove collinearity,4. Combine the orthogonalized factors with equal weights```+### Reusable Combination++The methods above are unrolled by hand only when you want to inspect every step.+The optional `combination` quantlib module performs the equal-weight and IC+variants as one reproducible call and returns the weights it used:++```python+from src.quantlib.combination import combine_factors++result = combine_factors(+ {"momentum": momentum_panel, "value": value_panel},+ forward_returns, # row t is the return earned after observing t+ method="ic", # "equal", "ic" or "icir"+ window=252, # trailing IC observations per weight+ rebalance=20,+)+result.composite, result.weights, result.diagnostics["correlation"]+```++Weights are estimated from rows strictly before the row they apply to, so a+weight never sees its own forward return. There is no complete list of+combination methods: for decayed IC, maximum IC, regression or trained weights,+compute the weight table yourself and pass `method="explicit", weights=table`+(a `time x factor` DataFrame). The module enforces the timing contract and+reports the diagnostics; it does not choose a method for you, and nothing in the+backtest path requires it. See+[references/combination.md](references/combination.md) for the pre-flight+checklist, the failure modes and the JSON envelope.+### Reusable Cross-Sectional TransformsUse `quantlib_call` with `module="neutralization"` (or importdiff --git a/agent/src/skills/factor-research/references/combination.md b/agent/src/skills/factor-research/references/combination.mdnew file mode 100644index 000000000..c7cc574c5--- /dev/null+++ b/agent/src/skills/factor-research/references/combination.md@@ -0,0 +1,205 @@+# Cross-sectional factor combination++The optional `combination` quantlib module provides one pure-compute function:++| Function | Purpose |+| --- | --- |+| `combine_factors` | Combine two or more factor panels into one composite score, with equal, IC/ICIR walk-forward, or caller-supplied weights |++It is available through `quantlib_call`, including transports without shell+tools. Nothing in the backtest path calls it: using it, skipping it, or replacing+it with your own weighting scheme is a research choice. Existing alpha formulas+and backtests are unchanged.++## Where this sits in the factor workflow++ compute factors -> validate each factor -> [clean] -> [combine] -> signal / backtest+ Alpha Zoo or IC / IR, quantile neutrali- this SignalEngine,+ your own panel backtest zation module `backtest` tool++- **Before** combining, every input factor should pass its own validity test+ (`factor_analysis`): the composite of two unusable factors is still unusable,+ and blending hides which input failed.+- **Neutralization** (a separate module) removes industry, size or style+ exposures from a *single* factor. Combination does not do that job; it merges+ factors that are already acceptable. Either step may be used without the other.+- **After** combining you hold one score panel per `(time, asset)`. Turn it into+ positions with a `SignalEngine` (`multi-factor` skill) and run the backtest+ engines; this module never sizes positions.++If you are new to factor research, the practical summary is: a single factor is+a hypothesis about which stocks will outperform, and a composite is a weighted+average of several such hypotheses. The weights decide how much each hypothesis+is believed; everything else in this document is about making that decision+honest and reproducible.++### When to skip it++- You have one factor: nothing to combine.+- You already own a defensible weighting scheme: use `method="explicit"` with+ your table, or do not call this module at all.+- You are still validating individual factors: finish `factor_analysis` first.++## Many methods, one weight contract++There is no complete list of combination methods. Equal weight, mean IC,+IC-IR-weighted, decayed IC, maximum IC, cross-sectional-regression weights,+trained models, risk-based weights and factor timing all exist, and practitioners+disagree about which is best. This module therefore does not enumerate methods;+it fixes the *weight contract*:++| You want | How to use this module |+| --- | --- |+| Equal weight | `method="equal"` |+| Mean IC weights | `method="ic"` with a forward-return panel |+| IC-IR weights | `method="icir"` with a forward-return panel |+| Decayed IC, maximum IC, regression, ML, risk parity, anything else | Compute a `time x factor` weight table yourself, then `method="explicit", weights=table` |++A table rather than a callback is deliberate: a table is auditable, reproducible,+serialisable over MCP and storable as a research artifact. A callback is none of+those, and this project has to answer "which workflow produced that number?".++The built-in methods are baselines, not recommendations. They exist because they+need no tuning, no dependency and no training, so they make a fair first+comparison.++## Weight timing is the one rule that cannot be relaxed++A weight applied at row `t` may only use information from rows `< t`.++`ic` and `icir` enforce this internally: the weight at `t` is estimated from IC+observations at rows `< t` (optionally limited to the trailing `window`). A+caller-supplied table must already respect it; the module cannot see how the+table was produced. Weighting every row by the full-sample IC is the most common+way to turn a real factor into a fake backtest: the weights already know which+factors worked over the evaluation period.++## Data contract++Each DataFrame has observation times as rows and assets as columns; one row is+one independent cross-section, whether observations are daily, weekly, monthly or+irregular. No resampling, forward filling or full-period fitting occurs. The+first panel defines output axes; other panels align by exact time/asset labels,+and labels missing from the first panel are appended in first-seen order.++- `panels` maps factor name -> panel. A name must be a non-empty string.+- `returns` is a forward-return panel aligned the same way: the value at row `t`+ is the return earned *after* observing `t`. It is required for `ic`/`icir`,+ optional elsewhere (used only for the `composite_ic` diagnostic).+- Non-finite values are treated as missing, never as zero.+- A factor missing at a given row is excluded from that row and the remaining+ weights are renormalised; a row with no available factor stays `NaN`.+- Factors are z-scored per row by default. Z-scoring is unit-invariant, and+ inputs are bounded before centering so large or tiny units cannot overflow+ into a false zero variance.++## Built-in baselines++| `method` | Weight | Needs `returns` | Fails when |+| --- | --- | --- | --- |+| `equal` | `1 / n` | no | inputs are highly correlated: the blend double-counts one style |+| `ic` | trailing mean rank IC, sign preserved, normalised by absolute sum | yes | IC history is short or unstable; a reversed factor gets a negative weight |+| `icir` | trailing mean/std rank IC, same normalisation | yes | the IC series has near-zero dispersion, which inflates the ratio |++Signs are preserved: a factor whose IC is negative receives a negative weight+instead of being silently flipped. Report the sign, do not hide it.++## Bring your own weights++```python+import pandas as pd++# Any method: here, a 60-observation half-life on the IC series.+weights = pd.DataFrame({"momentum": w_mom, "value": w_val}, index=dates)+result = combine_factors(+ {"momentum": momentum, "value": value},+ forward_returns,+ method="explicit",+ weights=weights, # time x factor; rows may cover rebalance dates only+)+```++Rows supplied only at rebalance dates are held forward. A weight table must+cover every factor exactly, and rows whose weights are all missing stay `NaN`.+Values are normalised by their absolute sum per row.++## Output and diagnostics++`combine_factors` returns a `CombinationResult`:++- `composite`: the score panel (`time x asset`).+- `weights`: the weight actually applied per row and factor.+- `diagnostics`:+ - `factor_ic`: per-factor IC mean, std, IR, positive ratio and observation+ count. **In-sample** description of the inputs.+ - `composite_ic`: the same statistics for the composite. **In-sample**.+ - `correlation`: average per-date Spearman correlation between factors. Two+ inputs correlated above ~0.9 are effectively one factor.+ - `weight_turnover`: mean absolute weight change between rebalances.+ - `weights_source`, `rows_without_weights`, `n_observations`, `n_assets`.++`factor_ic` and `composite_ic` describe the sample they were computed on; they+are not the walk-forward weights used to build the composite, and they say+nothing about out-of-sample behaviour.++## Pre-flight checklist++1. Every input factor passed `factor_analysis` on the same universe and horizon.+2. `correlation` was inspected; highly correlated inputs were dropped,+ orthogonalised or given a reduced weight on purpose.+3. Weights respect walk-forward timing (or `method="ic"/"icir"` is used).+4. The composite has its own `composite_ic`, not only the inputs' IC.+5. `weight_turnover` is affordable at the chosen `rebalance` frequency.+6. Direction signs were reviewed, not silently flipped.+7. The universe mask and holding horizon match the backtest that follows.+8. Method and hyper-parameters were chosen on research data, not the test period.++## Common failure modes++| Symptom | Cause | Fix |+| --- | --- | --- |+| Composite IC below every input | full-sample IC weights, or one input misaligned | use `ic` with a `window`, or an explicit table built walk-forward |+| Composite behaves like one factor | correlated inputs, equal weights | inspect `correlation`, orthogonalise (`neutralization`) or reduce the weight |+| Results not reproducible | weights computed ad hoc | pass a weight table; keep it as an artifact |+| Turnover explodes | `rebalance` far shorter than the factor's horizon | lengthen `rebalance`, or smooth the weights |+| Composite is blank early | `min_periods` not yet reached (`insufficient="skip"`) | that is the honest state; shorten `min_periods` only with enough data |++## Limits++- Does not size positions, apply costs or build a risk model.+- Does not neutralise industry, size or style exposures; use `neutralization`.+- Does not choose, tune or train a weighting method.+- Does not estimate multi-horizon returns; supply one forward-return panel.+- Does not validate point-in-time availability of the inputs.+- Does not guarantee out-of-sample performance; IC weights are sample estimates.++## Entry points++- **Python**: `from src.quantlib.combination import combine_factors`.+- **Agent / Web / REST / MCP**: `quantlib_call` with `module="combination"`,+ `function="combine_factors"`.+- **CLI prompt file**: request the same call in `request.txt` and run+ `vibe-trading run --prompt-file request.txt`.++JSON envelope example:++```json+{+ "action": "call",+ "module": "combination",+ "function": "combine_factors",+ "kwargs": {+ "panels": {"momentum": {"__dataframe__": {"index": ["2024-01-02"], "columns": ["a", "b"], "data": [[0.1, -0.2]]}}},+ "method": "equal"+ }+}+```++## Local validation++```bash+python -m pytest agent/tests/quantlib/test_combination.py agent/tests/test_mcp_combination.py -q+```++The suite pins unit-scale invariance, the no-look-ahead boundary, the truthful+`NaN` policy, the weight-table contract and the MCP round trip.diff --git a/agent/src/swarm/presets/factor_research_committee.yaml b/agent/src/swarm/presets/factor_research_committee.yamlindex fe48289a5..bb340d30d 100644--- a/agent/src/swarm/presets/factor_research_committee.yaml+++ b/agent/src/swarm/presets/factor_research_committee.yaml@@ -141,6 +141,14 @@ agents:PCA is not industry/style neutralization; its component identities can rotate.Use factor_analysis to compare raw/residual IC and quantile NAV on identicalsamples and holding horizons; it does not compute combination weights.+ Use quantlib_call(module="combination", function="combine_factors") for the+ equal/IC/ICIR baselines: each weight is estimated from IC observations strictly+ before the row it applies to, and the result carries the applied weights plus+ per-factor, composite and correlation diagnostics. For decayed IC, maximum IC,+ ML or risk-parity weights, compute the weight table yourself and pass+ method="explicit" with a time-by-factor table; the module does not choose,+ tune or train a method. Report the weights actually used, the correlation+ matrix and the composite IC next to the single-factor ICs.Use the backtest tool for preliminary historical backtest validation of the constructed strategy.## Output Requirementsdiff --git a/agent/src/tools/quantlib_tool.py b/agent/src/tools/quantlib_tool.pyindex 8d7644dc8..f39f3c8f8 100644--- a/agent/src/tools/quantlib_tool.py+++ b/agent/src/tools/quantlib_tool.py@@ -76,6 +76,7 @@ ALLOWED_MODULES: dict[str, str] = {"eventstudy": "src.quantlib.eventstudy","factormodel": "src.quantlib.factormodel","neutralization": "src.quantlib.neutralization",+ "combination": "src.quantlib.combination","multipletesting": "src.quantlib.multipletesting","crossvalidation": "src.quantlib.crossvalidation","valuation.dcf": "src.quantlib.valuation.dcf",@@ -276,7 +277,9 @@ class QuantlibCallTool(BaseTool):"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, cross-sectional OLS/WLS "- "factor neutralization and PCA at any observation frequency, deflated Sharpe and PBO, "+ "factor neutralization and PCA at any observation frequency, "+ "multi-factor combination with walk-forward IC weights, "+ "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_combination.py b/agent/tests/quantlib/test_combination.pynew file mode 100644index 000000000..8fe80d713--- /dev/null+++ b/agent/tests/quantlib/test_combination.py@@ -0,0 +1,182 @@+"""Timing, weighting and truthful-empty invariants for factor combination."""++from __future__ import annotations++import json++import numpy as np+import pandas as pd+import pytest++from src.quantlib.combination import combine_factors+from src.tools.quantlib_tool import ALLOWED_MODULES, QuantlibCallTool++ASSETS = 20+++def panel(values, columns=ASSETS, start="2024-01-01"):+ values = np.atleast_2d(np.asarray(values, dtype=float))+ index = pd.date_range(start, periods=values.shape[0], freq="D")+ return pd.DataFrame(values, index=index, columns=[f"s{i}" for i in range(columns)])+++def sample(rows=40, seed=11):+ rng = np.random.default_rng(seed)+ first = panel(rng.normal(size=(rows, ASSETS)))+ second = panel(rng.normal(size=(rows, ASSETS)))+ return first, second+++def test_equal_weights_reproduce_the_mean_of_standardized_factors():+ first, second = sample()+ result = combine_factors({"a": first, "b": second}, method="equal")++ def z(frame):+ return frame.sub(frame.mean(axis=1), axis=0).div(frame.std(axis=1, ddof=1), axis=0)++ expected = (z(first) + z(second)) / 2+ np.testing.assert_allclose(result.composite.to_numpy(), expected.to_numpy(), atol=1e-12)+ assert result.weights["a"].eq(0.5).all()+ assert result.weights["b"].eq(0.5).all()+++def test_a_missing_factor_is_excluded_not_read_as_zero():+ first, second = sample(rows=5)+ second.iloc[2] = np.nan+ result = combine_factors({"a": first, "b": second}, method="equal")+ row = first.iloc[2]+ expected = (row - row.mean()) / row.std(ddof=1)+ np.testing.assert_allclose(result.composite.iloc[2].to_numpy(), expected.to_numpy(), atol=1e-12)+++def test_a_row_with_no_available_factor_stays_nan():+ first, second = sample(rows=4)+ first.iloc[1] = np.nan+ second.iloc[1] = np.nan+ result = combine_factors({"a": first, "b": second}, method="equal")+ assert result.composite.iloc[1].isna().all()+++def test_ic_weights_favour_the_predictive_factor():+ first, second = sample(rows=60)+ returns = first * 0.01 # monotone in the first factor: IC = 1, second is noise+ result = combine_factors({"a": first, "b": second}, returns, method="ic", min_periods=20)+ tail = result.weights.dropna(how="all").iloc[-5:]+ assert (tail["a"] > 0.8).all()+ assert (tail["b"].abs() < 0.2).all()+++def test_weights_never_use_the_return_of_the_row_they_apply_to():+ first, second = sample(rows=40)+ returns = panel(np.random.default_rng(3).normal(size=(40, ASSETS)))+ baseline = combine_factors({"a": first, "b": second}, returns, method="ic", min_periods=10, window=20)+ changed = returns.copy()+ changed.iloc[20:] = changed.iloc[20:] * -3.0+ altered = combine_factors({"a": first, "b": second}, changed, method="ic", min_periods=10, window=20)+ pd.testing.assert_frame_equal(baseline.weights.iloc[:20], altered.weights.iloc[:20])+ assert not baseline.weights.iloc[20:].equals(altered.weights.iloc[20:])+++def test_history_shorter_than_min_periods_is_skipped_not_defaulted():+ first, second = sample(rows=30)+ returns = first * 0.01+ result = combine_factors({"a": first, "b": second}, returns, method="ic", min_periods=15)+ assert result.weights.iloc[:15].isna().all().all()+ assert result.composite.iloc[:15].isna().all().all()+ assert result.composite.iloc[15:].notna().any().any()+ assert result.diagnostics["rows_without_weights"] == 15+++def test_combination_is_invariant_to_factor_units():+ first, second = sample(rows=40)+ returns = first * 0.01+ base = combine_factors({"a": first, "b": second}, returns, method="ic", min_periods=10)+ for scale in (1e6, 1e-6):+ scaled = combine_factors(+ {"a": first * scale, "b": second * scale},+ returns,+ method="ic",+ min_periods=10,+ )+ np.testing.assert_allclose(base.composite, scaled.composite, atol=1e-10)+ np.testing.assert_allclose(base.weights, scaled.weights, atol=1e-12)+++def test_correlation_diagnostic_marks_duplicate_factors():+ first, _ = sample()+ result = combine_factors({"a": first, "b": first.copy()}, method="equal")+ correlation = result.diagnostics["correlation"]+ assert correlation.loc["a", "b"] == pytest.approx(1.0, abs=1e-9)+++def test_static_weights_are_normalised_and_must_cover_every_factor():+ first, second = sample(rows=10)+ result = combine_factors({"a": first, "b": second}, method="explicit", weights={"a": 3.0, "b": 1.0})+ assert result.weights["a"].iloc[0] == pytest.approx(0.75)+ assert result.weights["b"].iloc[0] == pytest.approx(0.25)+ with pytest.raises(ValueError, match="cover every factor"):+ combine_factors({"a": first, "b": second}, method="explicit", weights={"a": 1.0})+ with pytest.raises(ValueError, match="at least one weight"):+ combine_factors({"a": first, "b": second}, method="explicit", weights={"a": 0.0, "b": 0.0})+++def test_a_weight_table_changes_the_composite_over_time():+ first, second = sample(rows=6)+ weights = pd.DataFrame(+ {"a": [1.0, 1.0, 1.0, 0.0, 0.0, 0.0], "b": [0.0, 0.0, 0.0, 1.0, 1.0, 1.0]},+ index=first.index,+ )+ result = combine_factors({"a": first, "b": second}, method="explicit", weights=weights)++ def z(frame):+ return frame.sub(frame.mean(axis=1), axis=0).div(frame.std(axis=1, ddof=1), axis=0)++ np.testing.assert_allclose(result.composite.iloc[0], z(first).iloc[0], atol=1e-12)+ np.testing.assert_allclose(result.composite.iloc[-1], z(second).iloc[-1], atol=1e-12)+ assert result.diagnostics["weights_source"] == "caller_table"+++def test_a_weight_table_may_cover_only_rebalance_dates():+ first, second = sample(rows=6)+ weights = pd.DataFrame({"a": [1.0, 0.0], "b": [0.0, 1.0]}, index=[first.index[0], first.index[3]])+ result = combine_factors({"a": first, "b": second}, method="explicit", weights=weights)+ assert result.weights["a"].iloc[2] == pytest.approx(1.0)+ assert result.weights["b"].iloc[4] == pytest.approx(1.0)+++def test_weights_are_rejected_outside_explicit_mode():+ first, second = sample(rows=5)+ with pytest.raises(ValueError, match="only accepted with method='explicit'"):+ combine_factors({"a": first, "b": second}, weights={"a": 0.5, "b": 0.5})+++def test_ic_method_requires_returns():+ first, second = sample(rows=5)+ with pytest.raises(ValueError, match="requires a forward-return panel"):+ combine_factors({"a": first, "b": second}, method="ic")+++def test_rebalance_holds_weights_between_estimates():+ first, second = sample(rows=40)+ returns = first * 0.01+ result = combine_factors(+ {"a": first, "b": second},+ returns,+ method="ic",+ min_periods=10,+ rebalance=5,+ )+ defined = result.weights.dropna(how="all")+ changes = defined.diff().abs().sum(axis=1)+ rebalance_dates = set(result.weights.index[::5])+ for timestamp, change in changes.items():+ if timestamp not in rebalance_dates:+ assert change == pytest.approx(0.0)+++def test_combination_is_allowlisted_and_dispatchable():+ assert ALLOWED_MODULES["combination"] == "src.quantlib.combination"+ tool = QuantlibCallTool()+ listed = json.loads(tool.execute(action="list", module="combination"))+ names = {entry["name"] for entry in listed["functions"]}+ assert "combine_factors" in namesdiff --git a/agent/tests/test_mcp_combination.py b/agent/tests/test_mcp_combination.pynew file mode 100644index 000000000..bf9a987be--- /dev/null+++ b/agent/tests/test_mcp_combination.py@@ -0,0 +1,57 @@+"""Factor combination round-trips 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_combination_without_shell_tools_over_mcp(monkeypatch):+ registry = build_registry(include_shell_tools=False)+ monkeypatch.setattr(mcp_server, "_registry", registry)+ rng = np.random.default_rng(2210)+ dates = ["2026-10-19", "2026-10-20", "2026-10-21"]+ columns = [f"asset{i}" for i in range(8)]++ def panel(values):+ return {+ "__dataframe__": {+ "index": dates,+ "columns": columns,+ "data": np.asarray(values).tolist(),+ }+ }++ first = rng.normal(size=(len(dates), len(columns)))+ second = rng.normal(size=(len(dates), len(columns)))+ args = {+ "action": "call",+ "module": "combination",+ "function": "combine_factors",+ "kwargs": {+ "panels": {"momentum": panel(first), "value": panel(second)},+ "method": "equal",+ },+ }++ async def run():+ async with Client(mcp_server.mcp) as client:+ 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"]+ result = actual["result"]+ assert set(result) == {"composite", "weights", "diagnostics", "method"}+ composite = result["composite"]["__dataframe__"]+ assert composite["columns"] == columns+ assert len(composite["data"]) == len(dates)+ weights = result["weights"]["__dataframe__"]+ assert weights["columns"] == ["momentum", "value"]+ assert result["diagnostics"]["n_factors"] == 2++ asyncio.run(run())