"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
perf(factors): optimize rolling operators and bench path
Haozhe Wu88dfc978776d
diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.pyindex ad379838c..9c584cbaf 100644--- a/agent/backtest/engines/base.py+++ b/agent/backtest/engines/base.py@@ -18,6 +18,7 @@ from collections.abc import Iterablefrom pathlib import Pathfrom typing import Any, Callable, Dict, List, Optional+import numpy as npimport pandas as pdfrom backtest.loaders.rsshub_events import (@@ -528,10 +529,20 @@ class BaseEngine(ABC):# c. Record equity snapshotsnap_equity = self._calc_equity(close_df, ts)- total_unrealized = 0.0- for p in self.positions.values():- cp = self._safe_price(close_df, ts, p.symbol, p.entry_price)- total_unrealized += self._calc_pnl(p.symbol, p.direction, p.size, p.entry_price, cp)+ if self.positions and type(self)._calc_pnl is BaseEngine._calc_pnl:+ _syms = list(self.positions.keys())+ _eps = np.array([p.entry_price for p in self.positions.values()])+ _dirs = np.array([p.direction for p in self.positions.values()])+ _sizes = np.array([p.size for p in self.positions.values()])+ _cps = np.array(+ [self._safe_price(close_df, ts, s, ep) for s, ep in zip(_syms, _eps)]+ )+ total_unrealized = float(np.sum(_dirs * _sizes * (_cps - _eps)))+ else:+ total_unrealized = 0.0+ for p in self.positions.values():+ cp = self._safe_price(close_df, ts, p.symbol, p.entry_price)+ total_unrealized += self._calc_pnl(p.symbol, p.direction, p.size, p.entry_price, cp)self.equity_snapshots.append(EquitySnapshot(timestamp=ts,capital=self.capital,@@ -548,7 +559,32 @@ class BaseEngine(ABC):self._close_position(c, price, last_ts, "end_of_backtest")def _calc_equity(self, close_df: pd.DataFrame, ts: pd.Timestamp) -> float:- """Total equity = free cash + sum(margin + unrealised) per position."""+ """Total equity = free cash + sum(margin + unrealised) per position.++ Uses vectorized numpy path when _calc_pnl/_calc_margin are not+ overridden by a subclass (FuturesBaseEngine, CompositeEngine).+ """+ if not self.positions:+ return self.capital++ _base_pnl = type(self)._calc_pnl is BaseEngine._calc_pnl+ _base_margin = type(self)._calc_margin is BaseEngine._calc_margin++ if _base_pnl and _base_margin:+ syms = list(self.positions.keys())+ sizes = np.array([p.size for p in self.positions.values()])+ entry_prices = np.array([p.entry_price for p in self.positions.values()])+ directions = np.array([p.direction for p in self.positions.values()])+ leverages = np.array([p.leverage for p in self.positions.values()])++ current_prices = np.array(+ [self._safe_price(close_df, ts, s, ep) for s, ep in zip(syms, entry_prices)]+ )++ margins = sizes * entry_prices / leverages+ pnls = directions * sizes * (current_prices - entry_prices)+ return self.capital + float(np.sum(margins + pnls))+equity = self.capitalfor sym, pos in self.positions.items():cp = self._safe_price(close_df, ts, sym, pos.entry_price)diff --git a/agent/scripts/bench_performance.py b/agent/scripts/bench_performance.pynew file mode 100644index 000000000..be8ea085c--- /dev/null+++ b/agent/scripts/bench_performance.py@@ -0,0 +1,131 @@+"""Performance benchmark: compare old vs new operator/equity paths.++Development-only script — not included in the package.+Run: python agent/scripts/bench_performance.py+"""++from __future__ import annotations++import os+import sys+import time++import numpy as np+import pandas as pd++sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))+++def bench_operators():+ """Benchmark factor operators: old pandas vs new fast paths."""+ from src.factors.base import decay_linear, ts_argmax, ts_argmin, ts_rank++ np.random.seed(42)+ df = pd.DataFrame(np.random.randn(5000, 100))+ n = 20++ print("=== Operator Benchmarks (5000 rows × 100 cols, window=20) ===\n")++ ops = [+ ("ts_rank", lambda: ts_rank(df, n)),+ ("ts_argmax", lambda: ts_argmax(df, n)),+ ("ts_argmin", lambda: ts_argmin(df, n)),+ ("decay_linear", lambda: decay_linear(df, n)),+ ]++ for name, fn in ops:+ _ = fn()+ t0 = time.perf_counter()+ for _ in range(3):+ fn()+ elapsed = (time.perf_counter() - t0) / 3+ print(f" {name:20s}: {elapsed:.3f}s")++ print()+++def bench_equity():+ """Benchmark _calc_equity: vectorized vs loop."""+ from backtest.engines.base import BaseEngine+ from backtest.models import Position++ class _Stub(BaseEngine):+ def can_execute(self, *a):+ return True++ def round_size(self, s, p):+ return s++ def calc_commission(self, *a):+ return 0.0++ def apply_slippage(self, p, d):+ return p++ np.random.seed(42)+ n_symbols = 50+ n_days = 1000+ symbols = [f"SYM{i:03d}" for i in range(n_symbols)]+ dates = pd.date_range("2020-01-01", periods=n_days, freq="B")+ close_df = pd.DataFrame(+ np.cumsum(np.random.randn(n_days, n_symbols), axis=0) + 100,+ index=dates,+ columns=symbols,+ )++ engine = _Stub({"initial_cash": 10_000_000})+ engine.capital = 5_000_000+ for i, sym in enumerate(symbols):+ engine.positions[sym] = Position(+ symbol=sym,+ direction=1 if i % 2 == 0 else -1,+ size=100.0 + i * 10,+ entry_price=95.0 + i,+ leverage=1.0,+ entry_time=dates[0],+ )++ ts = dates[500]++ _ = engine._calc_equity(close_df, ts)+ t0 = time.perf_counter()+ for _ in range(1000):+ engine._calc_equity(close_df, ts)+ vec_time = (time.perf_counter() - t0) / 1000++ # Force loop path by monkey-patching+ original_pnl = type(engine)._calc_pnl++ def _loop_pnl(self, *a):+ return original_pnl(self, *a)++ type(engine)._calc_pnl = _loop_pnl+ _ = engine._calc_equity(close_df, ts)+ t0 = time.perf_counter()+ for _ in range(1000):+ engine._calc_equity(close_df, ts)+ loop_time = (time.perf_counter() - t0) / 1000+ type(engine)._calc_pnl = original_pnl++ speedup = loop_time / vec_time if vec_time > 0 else float("inf")++ print("=== Equity Calculation (50 positions, 1000 iterations) ===\n")+ print(f" Vectorized: {vec_time * 1e6:.1f} µs/call")+ print(f" Loop: {loop_time * 1e6:.1f} µs/call")+ print(f" Speedup: {speedup:.1f}x")+ print()+++if __name__ == "__main__":+ print("Vibe-Trading Performance Benchmark")+ print("=" * 50)+ print()++ from src.factors._backend import HAS_BOTTLENECK++ print(f"Bottleneck available: {HAS_BOTTLENECK}")+ print(f"VIBE_TRADING_DISABLE_BOTTLENECK: {os.environ.get('VIBE_TRADING_DISABLE_BOTTLENECK', '0')}")+ print()++ bench_operators()+ bench_equity()diff --git a/agent/src/factors/_backend.py b/agent/src/factors/_backend.pynew file mode 100644index 000000000..e01eff5b6--- /dev/null+++ b/agent/src/factors/_backend.py@@ -0,0 +1,35 @@+"""Graceful bottleneck import with env-var override.++Bottleneck provides C-compiled moving-window operators (move_argmax,+move_argmin) that are 100-350x faster than pandas rolling().apply().++When bottleneck is unavailable or disabled via env var, the operators+fall back to the original pandas path — identical results, slower speed.++Note: ``bn.move_rank`` uses a fundamentally different normalization+(Spearman rank correlation) than our ``ts_rank`` (percentile rank),+so ``ts_rank`` uses numpy ``sliding_window_view`` instead.+"""++from __future__ import annotations++import os++_DISABLE = os.environ.get("VIBE_TRADING_DISABLE_BOTTLENECK", "0") == "1"++HAS_BOTTLENECK: bool = False+bn = None++if not _DISABLE:+ try:+ import bottleneck as _bn++ bn = _bn+ HAS_BOTTLENECK = True+ except ImportError:+ pass++# numpy sliding_window_view — always available (numpy >= 1.20)+from numpy.lib.stride_tricks import sliding_window_view # noqa: E402++__all__ = ["HAS_BOTTLENECK", "bn", "sliding_window_view"]diff --git a/agent/src/factors/base.py b/agent/src/factors/base.pyindex 72ac40443..43c63678f 100644--- a/agent/src/factors/base.py+++ b/agent/src/factors/base.py@@ -21,6 +21,8 @@ from typing import Any, Protocol, runtime_checkableimport numpy as npimport pandas as pd+from src.factors._backend import HAS_BOTTLENECK, bn, sliding_window_view+class Market(str, Enum):"""Market identifier used by ``vwap`` for market-specific formulas."""@@ -79,6 +81,10 @@ def ts_rank(df: pd.DataFrame, n: int) -> pd.DataFrame:Warmup (first ``n-1`` rows per column) returns NaN. Result is a percentilein [0, 1] so it is compositionally compatible with cross-sectional rank.++ Uses numpy ``sliding_window_view`` for vectorized computation (~45x faster+ than pandas rolling().apply()). Note: ``bottleneck.move_rank`` computes+ Spearman rank correlation, not percentile rank, so it is not used here."""if n < 1:raise ValueError(f"ts_rank window must be >= 1, got {n}")@@ -98,7 +104,30 @@ def ts_rank(df: pd.DataFrame, n: int) -> pd.DataFrame:rank_avg = less + 0.5 * (eq + 1)return float(rank_avg / valid.size)- return df.rolling(window=n, min_periods=n).apply(_last_rank, raw=True)+ arr = df.to_numpy(dtype=np.float64)+ T, C = arr.shape+ if T < n:+ return df.rolling(window=n, min_periods=n).apply(_last_rank, raw=True)++ windows = sliding_window_view(arr, window_shape=n, axis=0) # (T-n+1, C, n)+ last_vals = windows[:, :, -1] # (T-n+1, C)+ nan_last = np.isnan(last_vals)+ nan_count = np.isnan(windows).sum(axis=2)+ valid_count = n - nan_count++ last_expanded = last_vals[:, :, np.newaxis]+ valid_mask = ~np.isnan(windows) & ~nan_last[:, :, np.newaxis]+ less = np.sum(np.where(valid_mask, windows < last_expanded, 0), axis=2)+ eq = np.sum(np.where(valid_mask, windows == last_expanded, 0), axis=2)+ rank_avg = less + 0.5 * (eq + 1)+ with np.errstate(divide="ignore", invalid="ignore"):+ pct = rank_avg / valid_count+ # min_periods=n: any NaN in window → NaN output+ pct[nan_last | (nan_count > 0)] = np.nan++ result = np.full((T, C), np.nan)+ result[n - 1 :] = pct+ return pd.DataFrame(result, index=df.index, columns=df.columns)def ts_corr(x: pd.DataFrame, y: pd.DataFrame, n: int) -> pd.DataFrame:@@ -176,16 +205,36 @@ def _argmin_last(arr: np.ndarray) -> float:def ts_argmax(df: pd.DataFrame, n: int) -> pd.DataFrame:- """Rolling argmax (0-based index into the window), warmup → NaN."""+ """Rolling argmax (0-based index into the window), warmup → NaN.++ Uses ``bottleneck.move_argmax`` when available (~350x faster).+ Correction: ``bn.move_argmax`` returns distance from window end,+ so we convert via ``(n - 1) - bn_result`` to get 0-based index from start.+ """if n < 1:raise ValueError(f"ts_argmax window must be >= 1, got {n}")+ if HAS_BOTTLENECK:+ arr = df.to_numpy(dtype=np.float64)+ raw = bn.move_argmax(arr, window=n, min_count=n, axis=0)+ corrected = (n - 1) - raw+ return pd.DataFrame(corrected, index=df.index, columns=df.columns)return df.rolling(window=n, min_periods=n).apply(_argmax_last, raw=True)def ts_argmin(df: pd.DataFrame, n: int) -> pd.DataFrame:- """Rolling argmin (0-based index into the window), warmup → NaN."""+ """Rolling argmin (0-based index into the window), warmup → NaN.++ Uses ``bottleneck.move_argmin`` when available (~350x faster).+ Correction: ``bn.move_argmin`` returns distance from window end,+ so we convert via ``(n - 1) - bn_result`` to get 0-based index from start.+ """if n < 1:raise ValueError(f"ts_argmin window must be >= 1, got {n}")+ if HAS_BOTTLENECK:+ arr = df.to_numpy(dtype=np.float64)+ raw = bn.move_argmin(arr, window=n, min_count=n, axis=0)+ corrected = (n - 1) - raw+ return pd.DataFrame(corrected, index=df.index, columns=df.columns)return df.rolling(window=n, min_periods=n).apply(_argmin_last, raw=True)@@ -203,6 +252,10 @@ def decay_linear(df: pd.DataFrame, n: int) -> pd.DataFrame:"""Linear decay-weighted moving average, weights ``n, n-1, ..., 1`` normalized.Warmup (first ``n-1`` rows) → NaN.++ Uses numpy ``sliding_window_view`` + ``einsum`` for vectorized computation+ (~40x faster than pandas rolling().apply()). Causal alignment is guaranteed:+ output[i] depends only on input[i-n+1:i+1]."""if n < 1:raise ValueError(f"decay_linear window must be >= 1, got {n}")@@ -214,7 +267,19 @@ def decay_linear(df: pd.DataFrame, n: int) -> pd.DataFrame:return np.nanreturn float(np.dot(arr, weights))- return df.rolling(window=n, min_periods=n).apply(_apply, raw=True)+ arr = df.to_numpy(dtype=np.float64)+ T, C = arr.shape+ if T < n:+ return df.rolling(window=n, min_periods=n).apply(_apply, raw=True)++ windows = sliding_window_view(arr, window_shape=n, axis=0) # (T-n+1, C, n)+ nan_mask = np.isnan(windows).any(axis=2) # (T-n+1, C)+ weighted = np.where(nan_mask[..., np.newaxis], 0.0, windows)+ dot = np.einsum("ijk,k->ij", weighted, weights)++ result = np.full((T, C), np.nan)+ result[n - 1 :] = np.where(nan_mask, np.nan, dot)+ return pd.DataFrame(result, index=df.index, columns=df.columns)def signed_power(df: pd.DataFrame, p: float) -> pd.DataFrame:diff --git a/agent/src/factors/bench_runner.py b/agent/src/factors/bench_runner.pyindex c957f4927..1f26627f2 100644--- a/agent/src/factors/bench_runner.py+++ b/agent/src/factors/bench_runner.py@@ -17,7 +17,9 @@ from __future__ import annotationsimport loggingimport math+import osimport time+from concurrent.futures import ProcessPoolExecutor, as_completedfrom typing import Any, Callable, Iterablefrom src.factors.factor_analysis_core import compute_ic_series@@ -35,6 +37,60 @@ logger = logging.getLogger(__name__)ProgressCb = Callable[[int, int, str], None]"""Signature: ``on_progress(n_done, n_total, current_alpha_id)``."""+_WORKER_PANEL: dict[str, Any] | None = None+_WORKER_RETURN_DF: Any | None = None+++def _init_bench_worker(panel: dict[str, Any], return_df: Any) -> None:+ """Store large bench inputs once per worker process."""+ global _WORKER_PANEL, _WORKER_RETURN_DF+ _WORKER_PANEL = panel+ _WORKER_RETURN_DF = return_df+++def _compute_single_alpha(args: Any) -> dict[str, Any]:+ """Picklable worker for parallel bench.++ Normal parallel execution passes only an alpha id after ``_init_bench_worker``+ has stored the large panel and return matrix once per worker. The tuple+ form is kept for direct unit tests and small one-off calls.+ """+ if isinstance(args, tuple):+ alpha_id, panel, return_df = args+ else:+ alpha_id = str(args)+ panel = _WORKER_PANEL+ return_df = _WORKER_RETURN_DF+ if panel is None or return_df is None:+ return {"skip": {"id": alpha_id, "reason": "worker inputs not initialized", "kind": "unexpected"}}++ reg = get_default_registry()+ try:+ factor_df = reg.compute(alpha_id, panel)+ ic = compute_ic_series(factor_df, return_df)+ if ic.empty:+ return {"skip": {"id": alpha_id, "reason": "empty IC series", "kind": "typed"}}+ ic_mean = float(ic.mean())+ ic_std = float(ic.std())+ ir = ic_mean / ic_std if ic_std > 0 else 0.0+ meta = reg.get(alpha_id).meta or {}+ return {+ "row": {+ "id": alpha_id,+ "ic_mean": round(ic_mean, 6),+ "ic_std": round(ic_std, 6),+ "ir": round(ir, 4),+ "ic_positive_ratio": round(float((ic > 0).mean()), 4),+ "ic_count": int(len(ic)),+ "theme": meta.get("theme", []),+ "formula_latex": meta.get("formula_latex", ""),+ }+ }+ except (SkipAlpha, RegistryError, RuntimeError, KeyError, ValueError) as exc:+ return {"skip": {"id": alpha_id, "reason": str(exc), "kind": "typed"}}+ except Exception as exc: # noqa: BLE001+ return {"skip": {"id": alpha_id, "reason": f"unexpected: {exc}", "kind": "unexpected"}}+def t_stat(ic_mean: float, ic_std: float, n: int) -> float:"""Two-sided t-statistic of the IC series."""@@ -147,44 +203,97 @@ def run_bench(rows: list[dict[str, Any]] = []skipped: list[dict[str, Any]] = []n_total = len(alpha_ids)- for idx, aid in enumerate(alpha_ids, start=1):++ try:+ n_workers = int(os.environ.get("VIBE_TRADING_BENCH_WORKERS", "0") or os.cpu_count() or 1)+ except ValueError:+ logger.warning("invalid VIBE_TRADING_BENCH_WORKERS; falling back to sequential")+ n_workers = 1+ n_workers = max(1, min(n_workers, n_total))+ use_parallel = registry is None and n_workers > 1 and n_total > 1++ if use_parallel:+ ctx_kwargs: dict[str, Any] = {}try:- factor_df = reg.compute(aid, panel)- ic = compute_ic_series(factor_df, return_df)- if ic.empty:+ import multiprocessing++ ctx = multiprocessing.get_context("fork")+ ctx_kwargs["mp_context"] = ctx+ except (ImportError, ValueError):+ pass++ future_to_id: dict[Any, str] = {}+ with ProcessPoolExecutor(+ max_workers=n_workers,+ initializer=_init_bench_worker,+ initargs=(panel, return_df),+ **ctx_kwargs,+ ) as pool:+ for aid in alpha_ids:+ fut = pool.submit(_compute_single_alpha, aid)+ future_to_id[fut] = aid++ n_done = 0+ for fut in as_completed(future_to_id):+ n_done += 1+ aid = future_to_id[fut]+ try:+ result = fut.result()+ except Exception as exc: # noqa: BLE001+ logger.exception("bench: worker crash on %s", aid)+ skipped.append({"id": aid, "reason": f"worker crash: {exc}", "kind": "unexpected"})+ result = None++ if result is not None:+ if "row" in result:+ rows.append(result["row"])+ elif "skip" in result:+ skipped.append(result["skip"])++ if on_progress is not None:+ try:+ on_progress(n_done, n_total, aid)+ except Exception: # noqa: BLE001+ logger.exception("on_progress callback raised; ignoring")+ else:+ for idx, aid in enumerate(alpha_ids, start=1):+ try:+ factor_df = reg.compute(aid, panel)+ ic = compute_ic_series(factor_df, return_df)+ if ic.empty:+ skipped.append(+ {"id": aid, "reason": "empty IC series", "kind": "typed"}+ )+ else:+ ic_mean = float(ic.mean())+ ic_std = float(ic.std())+ ir = ic_mean / ic_std if ic_std > 0 else 0.0+ meta = reg.get(aid).meta or {}+ rows.append(+ {+ "id": aid,+ "ic_mean": round(ic_mean, 6),+ "ic_std": round(ic_std, 6),+ "ir": round(ir, 4),+ "ic_positive_ratio": round(float((ic > 0).mean()), 4),+ "ic_count": int(len(ic)),+ "theme": meta.get("theme", []),+ "formula_latex": meta.get("formula_latex", ""),+ }+ )+ except (SkipAlpha, RegistryError, RuntimeError, KeyError, ValueError) as exc:+ skipped.append({"id": aid, "reason": str(exc), "kind": "typed"})+ except Exception as exc: # noqa: BLE001+ logger.exception("bench: unexpected failure on %s", aid)skipped.append(- {"id": aid, "reason": "empty IC series", "kind": "typed"}+ {"id": aid, "reason": f"unexpected: {exc}", "kind": "unexpected"})- else:- ic_mean = float(ic.mean())- ic_std = float(ic.std())- ir = ic_mean / ic_std if ic_std > 0 else 0.0- meta = reg.get(aid).meta or {}- rows.append(- {- "id": aid,- "ic_mean": round(ic_mean, 6),- "ic_std": round(ic_std, 6),- "ir": round(ir, 4),- "ic_positive_ratio": round(float((ic > 0).mean()), 4),- "ic_count": int(len(ic)),- "theme": meta.get("theme", []),- "formula_latex": meta.get("formula_latex", ""),- }- )- except (SkipAlpha, RegistryError, RuntimeError, KeyError, ValueError) as exc:- skipped.append({"id": aid, "reason": str(exc), "kind": "typed"})- except Exception as exc: # noqa: BLE001- logger.exception("bench: unexpected failure on %s", aid)- skipped.append(- {"id": aid, "reason": f"unexpected: {exc}", "kind": "unexpected"}- )- if on_progress is not None:- try:- on_progress(idx, n_total, aid)- except Exception: # noqa: BLE001 — never let progress break the loop- logger.exception("on_progress callback raised; ignoring")+ if on_progress is not None:+ try:+ on_progress(idx, n_total, aid)+ except Exception: # noqa: BLE001+ logger.exception("on_progress callback raised; ignoring")for row in rows:row["_category"] = categorise(row)diff --git a/agent/tests/test_bench_parallel.py b/agent/tests/test_bench_parallel.pynew file mode 100644index 000000000..e85716fe6--- /dev/null+++ b/agent/tests/test_bench_parallel.py@@ -0,0 +1,149 @@+"""Tests for parallel bench runner (ProcessPoolExecutor path)."""++from __future__ import annotations++from unittest.mock import MagicMock, patch++import numpy as np+import pandas as pd++from src.factors.bench_runner import _compute_single_alpha, _init_bench_worker+++def _make_mock_panel(n_symbols: int = 10, n_days: int = 100):+ np.random.seed(42)+ dates = pd.date_range("2020-01-01", periods=n_days, freq="B")+ symbols = [f"SYM{i:03d}" for i in range(n_symbols)]+ close = pd.DataFrame(+ np.cumsum(np.random.randn(n_days, n_symbols), axis=0) + 100,+ index=dates,+ columns=symbols,+ )+ return {"close": close, "open": close, "high": close, "low": close, "volume": close}+++class TestComputeSingleAlpha:+ def test_returns_result_dict(self):+ panel = _make_mock_panel()+ close = panel["close"]+ return_df = close.pct_change().shift(-1).iloc[:-1]++ with patch("src.factors.bench_runner.get_default_registry") as mock_reg:+ reg = MagicMock()+ mock_reg.return_value = reg+ reg.compute.return_value = close * np.random.randn(*close.shape)+ reg.get.return_value = MagicMock(meta={"theme": ["test"]})++ result = _compute_single_alpha(("alpha_0", panel, return_df))+ assert "row" in result or "skip" in result++ def test_uses_initialized_worker_inputs(self):+ panel = _make_mock_panel()+ close = panel["close"]+ return_df = close.pct_change().shift(-1).iloc[:-1]+ _init_bench_worker(panel, return_df)++ with patch("src.factors.bench_runner.get_default_registry") as mock_reg:+ reg = MagicMock()+ mock_reg.return_value = reg+ reg.compute.return_value = close * np.random.randn(*close.shape)+ reg.get.return_value = MagicMock(meta={"theme": ["test"]})++ result = _compute_single_alpha("alpha_0")+ assert "row" in result or "skip" in result++ def test_returns_skip_on_exception(self):+ panel = _make_mock_panel()+ return_df = pd.DataFrame()++ with patch("src.factors.bench_runner.get_default_registry") as mock_reg:+ reg = MagicMock()+ mock_reg.return_value = reg+ reg.compute.side_effect = RuntimeError("test error")++ result = _compute_single_alpha(("alpha_0", panel, return_df))+ assert "skip" in result+ assert "test error" in result["skip"]["reason"]+++class TestParallelBench:+ def _setup_mocks(self, monkeypatch, n_alphas=5):+ panel = _make_mock_panel()+ return_df = panel["close"].pct_change().shift(-1).iloc[:-1]+ alpha_ids = [f"alpha_{i}" for i in range(n_alphas)]++ mock_reg = MagicMock()+ mock_reg.list.return_value = alpha_ids+ mock_reg.get.return_value = MagicMock(meta={"theme": ["test"], "formula_latex": ""})+ mock_reg.compute.side_effect = lambda aid, p: p["close"] * np.random.randn(*p["close"].shape)++ monkeypatch.setattr("src.factors.bench_runner._load_universe_panel", lambda u, p: panel)+ monkeypatch.setattr("src.factors.bench_runner._compute_forward_returns", lambda p: return_df)+ monkeypatch.setattr("src.factors.bench_runner.get_default_registry", lambda: mock_reg)+ return mock_reg++ def test_parallel_matches_sequential(self, monkeypatch):+ from src.factors.bench_runner import run_bench++ mock_reg = self._setup_mocks(monkeypatch)++ monkeypatch.setenv("VIBE_TRADING_BENCH_WORKERS", "1")+ seq = run_bench("test_zoo", "mock", "2020-2021")++ monkeypatch.setenv("VIBE_TRADING_BENCH_WORKERS", "2")+ par = run_bench("test_zoo", "mock", "2020-2021")++ assert seq["status"] == "ok"+ assert par["status"] == "ok"+ assert seq["n_alphas_tested"] == par["n_alphas_tested"]++ def test_progress_callback_fires(self, monkeypatch):+ from src.factors.bench_runner import run_bench++ mock_reg = self._setup_mocks(monkeypatch, n_alphas=3)+ monkeypatch.setenv("VIBE_TRADING_BENCH_WORKERS", "2")++ calls = []+ result = run_bench(+ "test_zoo", "mock", "2020-2021",+ registry=mock_reg,+ on_progress=lambda n, t, a: calls.append((n, t, a)),+ )+ assert result["status"] == "ok"+ assert len(calls) == 3++ def test_only_filter_with_parallel(self, monkeypatch):+ from src.factors.bench_runner import run_bench++ mock_reg = self._setup_mocks(monkeypatch, n_alphas=5)+ monkeypatch.setenv("VIBE_TRADING_BENCH_WORKERS", "2")++ result = run_bench(+ "test_zoo", "mock", "2020-2021",+ registry=mock_reg,+ only=["alpha_0", "alpha_2"],+ )+ assert result["status"] == "ok"+ tested_ids = {r["id"] for r in result["rows"]}+ assert tested_ids <= {"alpha_0", "alpha_2"}++ def test_custom_registry_forces_sequential(self, monkeypatch):+ from src.factors.bench_runner import run_bench++ mock_reg = self._setup_mocks(monkeypatch, n_alphas=2)+ monkeypatch.setenv("VIBE_TRADING_BENCH_WORKERS", "2")++ result = run_bench("test_zoo", "mock", "2020-2021", registry=mock_reg)++ assert result["status"] == "ok"+ assert mock_reg.compute.call_count == 2++ def test_invalid_worker_env_falls_back(self, monkeypatch):+ from src.factors.bench_runner import run_bench++ mock_reg = self._setup_mocks(monkeypatch, n_alphas=2)+ monkeypatch.setenv("VIBE_TRADING_BENCH_WORKERS", "not-an-int")++ result = run_bench("test_zoo", "mock", "2020-2021", registry=mock_reg)++ assert result["status"] == "ok"diff --git a/agent/tests/test_equity_regression.py b/agent/tests/test_equity_regression.pynew file mode 100644index 000000000..1c10ab856--- /dev/null+++ b/agent/tests/test_equity_regression.py@@ -0,0 +1,117 @@+"""Regression test: vectorized vs loop _calc_equity produce identical results."""++from __future__ import annotations++import numpy as np+import pandas as pd++from backtest.engines.base import BaseEngine+from backtest.models import Position+++class _StubEngine(BaseEngine):+ """Minimal concrete BaseEngine for testing _calc_equity."""++ def can_execute(self, symbol, direction, bar):+ return True++ def round_size(self, raw_size, price):+ return raw_size++ def calc_commission(self, size, price, direction, is_open):+ return 0.0++ def apply_slippage(self, price, direction):+ return price+++def _make_close_df(symbols, n_days=50):+ """Create a close price DataFrame."""+ np.random.seed(42)+ dates = pd.date_range("2020-01-01", periods=n_days, freq="B")+ prices = {}+ for s in symbols:+ prices[s] = np.cumsum(np.random.randn(n_days)) + 100+ return pd.DataFrame(prices, index=dates)+++class TestEquityVectorization:+ def test_empty_positions(self):+ """No positions → equity = capital."""+ engine = _StubEngine({"initial_cash": 1_000_000})+ close_df = _make_close_df(["A", "B"])+ ts = close_df.index[10]+ assert engine._calc_equity(close_df, ts) == 1_000_000++ def test_single_position(self):+ """Single long position: equity matches manual calculation."""+ engine = _StubEngine({"initial_cash": 1_000_000})+ close_df = _make_close_df(["AAPL"])+ ts = close_df.index[10]++ entry_price = 100.0+ size = 50.0+ engine.positions["AAPL"] = Position(+ symbol="AAPL", direction=1, size=size,+ entry_price=entry_price, leverage=1.0, entry_time=ts,+ )+ engine.capital = 1_000_000 - size * entry_price++ equity = engine._calc_equity(close_df, ts)+ cp = float(close_df.at[ts, "AAPL"])+ expected = engine.capital + size * entry_price + 1 * size * (cp - entry_price)+ assert abs(equity - expected) < 1e-8++ def test_multiple_positions(self):+ """Multiple positions: vectorized matches loop."""+ engine = _StubEngine({"initial_cash": 1_000_000})+ symbols = ["AAPL", "MSFT", "GOOG", "AMZN", "TSLA"]+ close_df = _make_close_df(symbols)+ ts = close_df.index[20]++ engine.capital = 500_000+ for i, sym in enumerate(symbols):+ direction = 1 if i % 2 == 0 else -1+ engine.positions[sym] = Position(+ symbol=sym, direction=direction, size=10.0 + i * 5,+ entry_price=95.0 + i * 2, leverage=1.0 + i * 0.5,+ entry_time=ts,+ )++ equity = engine._calc_equity(close_df, ts)++ loop_equity = engine.capital+ for sym, pos in engine.positions.items():+ cp = engine._safe_price(close_df, ts, sym, pos.entry_price)+ margin = pos.size * pos.entry_price / pos.leverage+ pnl = pos.direction * pos.size * (cp - pos.entry_price)+ loop_equity += margin + pnl++ assert abs(equity - loop_equity) < 1e-8++ def test_mixed_leverage(self):+ """Different leverage values produce correct margin calculations."""+ engine = _StubEngine({"initial_cash": 1_000_000})+ close_df = _make_close_df(["A", "B"])+ ts = close_df.index[10]++ engine.capital = 800_000+ engine.positions["A"] = Position(+ symbol="A", direction=1, size=100.0,+ entry_price=50.0, leverage=2.0, entry_time=ts,+ )+ engine.positions["B"] = Position(+ symbol="B", direction=-1, size=50.0,+ entry_price=80.0, leverage=1.0, entry_time=ts,+ )++ equity = engine._calc_equity(close_df, ts)++ cp_a = float(close_df.at[ts, "A"])+ cp_b = float(close_df.at[ts, "B"])+ expected = (+ 800_000+ + (100 * 50 / 2.0 + 1 * 100 * (cp_a - 50))+ + (50 * 80 / 1.0 + (-1) * 50 * (cp_b - 80))+ )+ assert abs(equity - expected) < 1e-8diff --git a/agent/tests/test_factor_operators.py b/agent/tests/test_factor_operators.pynew file mode 100644index 000000000..cb6fe4802--- /dev/null+++ b/agent/tests/test_factor_operators.py@@ -0,0 +1,298 @@+"""Equivalence tests for optimized factor operators.++Tests verify that the fast paths (bottleneck / numpy stride) produce+identical results to the original pandas rolling().apply() fallback.+"""++from __future__ import annotations++import importlib+import os+import sys+import warnings++import numpy as np+import pandas as pd+import pytest++# ── Helpers to force fallback path ──+++def _reload_base_with_bottleneck(enabled: bool):+ """Reload base.py with bottleneck enabled or disabled."""+ os.environ["VIBE_TRADING_DISABLE_BOTTLENECK"] = "0" if enabled else "1"+ # Force reimport of _backend and base+ if "src.factors._backend" in sys.modules:+ del sys.modules["src.factors._backend"]+ if "src.factors.base" in sys.modules:+ del sys.modules["src.factors.base"]+ mod = importlib.import_module("src.factors.base")+ return mod+++# ── Reference implementations (original pandas path) ──+++def _ref_ts_rank(df: pd.DataFrame, n: int) -> pd.DataFrame:+ def _last_rank(arr: np.ndarray) -> float:+ if np.isnan(arr).all():+ return np.nan+ last = arr[-1]+ if np.isnan(last):+ return np.nan+ valid = arr[~np.isnan(arr)]+ if valid.size == 0:+ return np.nan+ less = (valid < last).sum()+ eq = (valid == last).sum()+ rank_avg = less + 0.5 * (eq + 1)+ return float(rank_avg / valid.size)++ return df.rolling(window=n, min_periods=n).apply(_last_rank, raw=True)+++def _ref_ts_argmax(df: pd.DataFrame, n: int) -> pd.DataFrame:+ def _argmax_last(arr: np.ndarray) -> float:+ if np.isnan(arr).all():+ return np.nan+ arr_filled = np.where(np.isnan(arr), -np.inf, arr)+ return float(np.argmax(arr_filled))++ return df.rolling(window=n, min_periods=n).apply(_argmax_last, raw=True)+++def _ref_ts_argmin(df: pd.DataFrame, n: int) -> pd.DataFrame:+ def _argmin_last(arr: np.ndarray) -> float:+ if np.isnan(arr).all():+ return np.nan+ arr_filled = np.where(np.isnan(arr), np.inf, arr)+ return float(np.argmin(arr_filled))++ return df.rolling(window=n, min_periods=n).apply(_argmin_last, raw=True)+++def _ref_decay_linear(df: pd.DataFrame, n: int) -> pd.DataFrame:+ weights = np.arange(n, 0, -1, dtype=np.float64)+ weights /= weights.sum()++ def _apply(arr: np.ndarray) -> float:+ if np.isnan(arr).any():+ return np.nan+ return float(np.dot(arr, weights))++ return df.rolling(window=n, min_periods=n).apply(_apply, raw=True)+++# ── Fixtures ──+++def random_df():+ """100 rows × 10 columns random DataFrame."""+ np.random.seed(42)+ return pd.DataFrame(np.random.randn(100, 10))+++def random_df_with_nan():+ """100 rows × 10 columns with scattered NaN values."""+ np.random.seed(42)+ df = pd.DataFrame(np.random.randn(100, 10))+ df.iloc[10, 2] = np.nan+ df.iloc[30, 5] = np.nan+ df.iloc[50, 0] = np.nan+ df.iloc[70, 8] = np.nan+ return df+++# ── ts_rank tests ──+++class TestTsRank:+ @pytest.mark.parametrize("n", [3, 5, 10, 20])+ def test_equivalence_clean(self, random_df, n):+ """Fast path matches pandas reference on clean data."""+ base = _reload_base_with_bottleneck(True)+ result = base.ts_rank(random_df, n)+ expected = _ref_ts_rank(random_df, n)+ pd.testing.assert_frame_equal(result, expected, atol=1e-12)++ @pytest.mark.parametrize("n", [5, 10])+ def test_equivalence_with_nan(self, random_df_with_nan, n):+ """Fast path matches pandas reference with NaN values."""+ base = _reload_base_with_bottleneck(True)+ result = base.ts_rank(random_df_with_nan, n)+ expected = _ref_ts_rank(random_df_with_nan, n)+ pd.testing.assert_frame_equal(result, expected, atol=1e-12)++ def test_warmup_is_nan(self, random_df):+ """First n-1 rows must be NaN."""+ base = _reload_base_with_bottleneck(True)+ n = 10+ result = base.ts_rank(random_df, n)+ assert result.iloc[: n - 1].isna().all().all()++ def test_fallback_path(self, random_df):+ """Fallback (bottleneck disabled) still works correctly."""+ base = _reload_base_with_bottleneck(False)+ result = base.ts_rank(random_df, 5)+ expected = _ref_ts_rank(random_df, 5)+ pd.testing.assert_frame_equal(result, expected, atol=1e-12)++ def test_all_nan_window_emits_no_runtime_warning(self):+ """All-NaN windows stay NaN without divide-by-zero noise."""+ base = _reload_base_with_bottleneck(True)+ df = pd.DataFrame(np.nan, index=range(12), columns=list("abc"))+ with warnings.catch_warnings():+ warnings.simplefilter("error", RuntimeWarning)+ result = base.ts_rank(df, 5)++ assert result.isna().all().all()++ def test_constant_window(self):+ """All-same values: rank should be (n+1)/(2n) for average rank."""+ base = _reload_base_with_bottleneck(True)+ df = pd.DataFrame(np.ones((20, 3)))+ result = base.ts_rank(df, 5)+ # For 5 identical values: less=0, eq=5, rank_avg=0+0.5*(5+1)=3, pct=3/5=0.6+ expected_val = 0.6+ assert np.allclose(result.iloc[4:].values, expected_val)++ def test_invalid_window(self):+ base = _reload_base_with_bottleneck(True)+ with pytest.raises(ValueError, match="window must be >= 1"):+ base.ts_rank(pd.DataFrame(), 0)+++# ── ts_argmax tests ──+++class TestTsArgmax:+ @pytest.mark.parametrize("n", [3, 5, 10, 20])+ def test_equivalence_clean(self, random_df, n):+ base = _reload_base_with_bottleneck(True)+ result = base.ts_argmax(random_df, n)+ expected = _ref_ts_argmax(random_df, n)+ pd.testing.assert_frame_equal(result, expected)++ def test_warmup_is_nan(self, random_df):+ base = _reload_base_with_bottleneck(True)+ n = 10+ result = base.ts_argmax(random_df, n)+ assert result.iloc[: n - 1].isna().all().all()++ def test_fallback_path(self, random_df):+ base = _reload_base_with_bottleneck(False)+ result = base.ts_argmax(random_df, 5)+ expected = _ref_ts_argmax(random_df, 5)+ pd.testing.assert_frame_equal(result, expected)++ def test_integer_output(self, random_df):+ """argmax returns integer indices (0-based), not floats."""+ base = _reload_base_with_bottleneck(True)+ result = base.ts_argmax(random_df, 5)+ valid = result.iloc[4:]+ assert (valid == valid.astype(int)).all().all()++ def test_invalid_window(self):+ base = _reload_base_with_bottleneck(True)+ with pytest.raises(ValueError, match="window must be >= 1"):+ base.ts_argmax(pd.DataFrame(), 0)+++# ── ts_argmin tests ──+++class TestTsArgmin:+ @pytest.mark.parametrize("n", [3, 5, 10, 20])+ def test_equivalence_clean(self, random_df, n):+ base = _reload_base_with_bottleneck(True)+ result = base.ts_argmin(random_df, n)+ expected = _ref_ts_argmin(random_df, n)+ pd.testing.assert_frame_equal(result, expected)++ def test_warmup_is_nan(self, random_df):+ base = _reload_base_with_bottleneck(True)+ n = 10+ result = base.ts_argmin(random_df, n)+ assert result.iloc[: n - 1].isna().all().all()++ def test_fallback_path(self, random_df):+ base = _reload_base_with_bottleneck(False)+ result = base.ts_argmin(random_df, 5)+ expected = _ref_ts_argmin(random_df, 5)+ pd.testing.assert_frame_equal(result, expected)++ def test_invalid_window(self):+ base = _reload_base_with_bottleneck(True)+ with pytest.raises(ValueError, match="window must be >= 1"):+ base.ts_argmin(pd.DataFrame(), 0)+++# ── decay_linear tests ──+++class TestDecayLinear:+ @pytest.mark.parametrize("n", [3, 5, 10, 20])+ def test_equivalence_clean(self, random_df, n):+ base = _reload_base_with_bottleneck(True)+ result = base.decay_linear(random_df, n)+ expected = _ref_decay_linear(random_df, n)+ pd.testing.assert_frame_equal(result, expected, atol=1e-10)++ @pytest.mark.parametrize("n", [5, 10])+ def test_equivalence_with_nan(self, random_df_with_nan, n):+ base = _reload_base_with_bottleneck(True)+ result = base.decay_linear(random_df_with_nan, n)+ expected = _ref_decay_linear(random_df_with_nan, n)+ pd.testing.assert_frame_equal(result, expected, atol=1e-10)++ def test_warmup_is_nan(self, random_df):+ base = _reload_base_with_bottleneck(True)+ n = 10+ result = base.decay_linear(random_df, n)+ assert result.iloc[: n - 1].isna().all().all()++ def test_no_lookahead(self, random_df):+ """Modifying future values must not change past outputs."""+ base = _reload_base_with_bottleneck(True)+ n = 10+ df_mod = random_df.copy()+ df_mod.iloc[50:] = 999.0+ result_orig = base.decay_linear(random_df, n)+ result_mod = base.decay_linear(df_mod, n)+ # Output at row 49 (index 49) should be identical+ pd.testing.assert_series_equal(+ result_orig.iloc[49], result_mod.iloc[49], atol=1e-10+ )++ def test_fallback_path(self, random_df):+ base = _reload_base_with_bottleneck(False)+ result = base.decay_linear(random_df, 5)+ expected = _ref_decay_linear(random_df, 5)+ pd.testing.assert_frame_equal(result, expected, atol=1e-10)++ def test_invalid_window(self):+ base = _reload_base_with_bottleneck(True)+ with pytest.raises(ValueError, match="window must be >= 1"):+ base.decay_linear(pd.DataFrame(), 0)+++# ── Backend detection tests ──+++class TestBackend:+ def test_bottleneck_available(self):+ """bottleneck should be available in test environment."""+ from src.factors._backend import HAS_BOTTLENECK++ assert HAS_BOTTLENECK is True++ def test_disable_env_var(self):+ """VIBE_TRADING_DISABLE_BOTTLENECK=1 should disable bottleneck."""+ _reload_base_with_bottleneck(False)+ from src.factors._backend import HAS_BOTTLENECK++ assert HAS_BOTTLENECK is False+ # Restore+ _reload_base_with_bottleneck(True)diff --git a/pyproject.toml b/pyproject.tomlindex fa0acc92c..b485b4085 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -36,6 +36,7 @@ dependencies = ["Pillow>=10.0.0","numpy>=1.24.0","scipy>=1.10.0",+ "bottleneck>=1.3.7","duckdb>=1.2.0","scikit-learn>=1.3.0","joblib>=1.3.0",