"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(factor): bound artifact discovery and payloads
Haozhe Wuee10dac39902
diff --git a/agent/src/api/runs_routes.py b/agent/src/api/runs_routes.pyindex be94281a2..27161373e 100644--- a/agent/src/api/runs_routes.py+++ b/agent/src/api/runs_routes.py@@ -7,10 +7,13 @@ from __future__ import annotationsimport csvimport json+import math+import osimport statistics+from collections import dequefrom datetime import datetimefrom pathlib import Path-from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple+from typing import Any, Awaitable, Callable, Deque, Dict, Generator, List, Optional, Tuplefrom fastapi import Depends, FastAPI, HTTPException, Query, statusfrom fastapi.responses import JSONResponse@@ -20,6 +23,16 @@ from fastapi.responses import JSONResponse# Helper functions (module-level; host Pydantic models resolved via sys.modules)# ---------------------------------------------------------------------------+_FACTOR_MAX_RESULTS = 20+_FACTOR_MAX_SCAN_ENTRIES = 4096+_FACTOR_MAX_SCAN_DEPTH = 8+_FACTOR_MAX_FILE_BYTES = 2 * 1024 * 1024+_FACTOR_MAX_SUMMARY_BYTES = 128 * 1024+_FACTOR_MAX_TOTAL_ARTIFACT_BYTES = 8 * 1024 * 1024+_FACTOR_MAX_ROWS_PER_CSV = 5000+_FACTOR_MAX_TOTAL_ROWS = 20_000+_FACTOR_MAX_GROUP_COLUMNS = 100+def _load_json_file(path: Path) -> Optional[Dict[str, Any]]:"""Load JSON from disk if present."""@@ -45,7 +58,74 @@ def _load_csv_to_dict(path: Path, limit: Optional[int] = None) -> List[Dict[str,return []-def _load_ic_series_csv(path: Path) -> List[Dict[str, Any]]:+def _finite_float(value: Any) -> Optional[float]:+ """Parse a finite float, returning ``None`` for invalid values.++ Args:+ value: Candidate numeric value.++ Returns:+ Parsed finite float, or ``None``.+ """+ try:+ parsed = float(value)+ except (TypeError, ValueError, OverflowError):+ return None+ return parsed if math.isfinite(parsed) else None+++def _sanitize_finite_json(value: Any) -> Any:+ """Replace non-finite JSON numeric leaves with ``None`` recursively.++ Args:+ value: Parsed JSON value.++ Returns:+ JSON-compatible value without NaN or infinities.+ """+ if isinstance(value, float):+ return value if math.isfinite(value) else None+ if isinstance(value, dict):+ return {key: _sanitize_finite_json(item) for key, item in value.items()}+ if isinstance(value, list):+ return [_sanitize_finite_json(item) for item in value]+ return value+++def _claim_factor_artifact(+ path: Path,+ *,+ max_file_bytes: int,+ remaining_bytes: int,+) -> Tuple[bool, int, bool]:+ """Check whether an artifact can be read inside the response byte budget.++ Symlinks are rejected so companion files cannot escape the discovered+ bundle. The returned tuple is ``(readable, charged_bytes, degraded)``;+ missing optional files are not considered degraded.++ Args:+ path: Candidate artifact path.+ max_file_bytes: Per-file byte ceiling.+ remaining_bytes: Remaining aggregate byte budget.++ Returns:+ Tuple of readability, charged bytes, and degraded status.+ """+ try:+ if path.is_symlink():+ return False, 0, True+ if not path.is_file():+ return False, 0, False+ size = path.stat().st_size+ except OSError:+ return False, 0, True+ if size < 0 or size > max_file_bytes or size > remaining_bytes:+ return False, 0, True+ return True, size, False+++def _load_ic_series_csv(path: Path, row_limit: int) -> Tuple[List[Dict[str, Any]], bool]:"""Load an ``ic_series.csv`` file into ``{"date", "ic"}`` rows.The first CSV column is treated as the date column regardless of its@@ -54,35 +134,43 @@ def _load_ic_series_csv(path: Path) -> List[Dict[str, Any]]:Args:path: Path to the ic_series.csv file.+ row_limit: Maximum source rows to parse.Returns:- List of rows with raw string dates and float IC values.+ Tuple of rows with raw string dates and finite IC values plus a flag+ indicating that the source was truncated or could not be parsed."""+ if row_limit <= 0:+ return [], Truetry:- if not path.exists():- return []with path.open("r", encoding="utf-8", newline="") as handle:reader = csv.DictReader(handle)fieldnames = reader.fieldnamesif not fieldnames or fieldnames[0] is None:- return []+ return [], Truedate_col = fieldnames[0]rows: List[Dict[str, Any]] = []- for row in reader:+ truncated = False+ for source_index, row in enumerate(reader):+ if source_index >= row_limit:+ truncated = True+ breakdate_value = row.get(date_col)if date_value is None:continue- try:- ic_value = float(row.get("IC"))- except (TypeError, ValueError):+ ic_value = _finite_float(row.get("IC"))+ if ic_value is None:continuerows.append({"date": date_value, "ic": ic_value})- return rows+ return rows, truncatedexcept Exception:- return []+ return [], True-def _load_group_equity_csv(path: Path) -> Tuple[List[Dict[str, Any]], List[str]]:+def _load_group_equity_csv(+ path: Path,+ row_limit: int,+) -> Tuple[List[Dict[str, Any]], List[str], bool]:"""Load a ``group_equity.csv`` file into dated rows of float group values.The first column is the date; every remaining column is kept in file@@ -90,71 +178,205 @@ def _load_group_equity_csv(path: Path) -> Tuple[List[Dict[str, Any]], List[str]]Args:path: Path to the group_equity.csv file.+ row_limit: Maximum source rows to parse.Returns:- Tuple of (rows, value column names in file order).+ Tuple of (rows, value column names in file order, truncated/degraded)."""+ if row_limit <= 0:+ return [], [], Truetry:- if not path.exists():- return [], []with path.open("r", encoding="utf-8", newline="") as handle:reader = csv.DictReader(handle)fieldnames = reader.fieldnamesif not fieldnames or fieldnames[0] is None or len(fieldnames) < 2:- return [], []+ return [], [], Truedate_col = fieldnames[0]- value_cols = [col for col in fieldnames[1:] if col]+ all_value_cols = [col for col in fieldnames[1:] if col]+ value_cols = all_value_cols[:_FACTOR_MAX_GROUP_COLUMNS]+ truncated = len(value_cols) < len(all_value_cols)rows: List[Dict[str, Any]] = []- for row in reader:+ for source_index, row in enumerate(reader):+ if source_index >= row_limit:+ truncated = True+ breakdate_value = row.get(date_col)if date_value is None:continueparsed: Dict[str, Any] = {"date": date_value}for col in value_cols:- try:- parsed[col] = float(row.get(col))- except (TypeError, ValueError):- continue+ numeric_value = _finite_float(row.get(col))+ if numeric_value is not None:+ parsed[col] = numeric_valuerows.append(parsed)- return rows, value_cols+ return rows, value_cols, truncatedexcept Exception:- return [], []+ return [], [], True-def _scan_factor_results(run_dir: Path, limit: int = 20) -> List[Dict[str, Any]]:+def _load_factor_summary(path: Path) -> Tuple[Optional[Dict[str, Any]], bool]:+ """Load a factor summary while removing non-finite numeric leaves.++ Args:+ path: Path to ``ic_summary.json``.++ Returns:+ Sanitized summary and whether parsing degraded.+ """+ try:+ payload = json.loads(path.read_text(encoding="utf-8"))+ if not isinstance(payload, dict):+ return None, True+ return _sanitize_finite_json(payload), False+ except (OSError, UnicodeError, ValueError, RecursionError):+ return None, True+++def _iter_factor_series_files(+ run_dir: Path,+ *,+ max_results: int,+) -> Generator[Path, None, None]:+ """Yield bounded, non-symlinked ``ic_series.csv`` paths.++ Directory entries, nesting depth, and result count are all capped. Unlike+ ``Path.rglob()``, this iterator never constructs the complete match list+ and never follows a symlinked directory.++ Args:+ run_dir: Root directory of the run.+ max_results: Maximum factor marker paths to yield.++ Yields:+ Safe paths to factor IC-series artifacts.+ """+ artifacts_dir = run_dir / "artifacts"+ if not artifacts_dir.is_dir() or artifacts_dir.is_symlink() or max_results <= 0:+ return++ pending: Deque[Tuple[Path, int]] = deque([(artifacts_dir, 0)])+ entries_seen = 0+ yielded = 0+ while pending and entries_seen < _FACTOR_MAX_SCAN_ENTRIES and yielded < max_results:+ directory, depth = pending.popleft()+ child_directories: List[Path] = []+ try:+ with os.scandir(directory) as scan:+ iterator = iter(scan)+ while entries_seen < _FACTOR_MAX_SCAN_ENTRIES:+ try:+ entry = next(iterator)+ except StopIteration:+ break+ entries_seen += 1+ if entry.name.startswith("."):+ continue+ try:+ if entry.is_symlink():+ continue+ if entry.name == "ic_series.csv" and entry.is_file(follow_symlinks=False):+ yield Path(entry.path)+ yielded += 1+ if yielded >= max_results:+ return+ elif depth < _FACTOR_MAX_SCAN_DEPTH and entry.is_dir(follow_symlinks=False):+ child_directories.append(Path(entry.path))+ except OSError:+ continue+ except OSError:+ continue+ child_directories.sort(key=lambda path: path.name)+ pending.extend((path, depth + 1) for path in child_directories)+++def _has_factor_artifacts(run_dir: Path) -> bool:+ """Return whether a bounded directory-entry scan finds a factor bundle."""+ candidates = _iter_factor_series_files(run_dir, max_results=1)+ try:+ return next(candidates, None) is not None+ finally:+ candidates.close()+++def _scan_factor_results(run_dir: Path) -> List[Dict[str, Any]]:"""Scan a run directory for factor-analysis artifact bundles.A factor result is any directory under ``run_dir/artifacts`` (recursive)- that contains an ``ic_series.csv`` file. A bundle sitting directly in- ``artifacts/`` is named ``factor_analysis``; otherwise the containing- directory name is used. Paths with ``..`` or hidden components are- skipped, and results are capped to bound recursion over hostile layouts.+ that contains an ``ic_series.csv`` file. Traversal, nesting, factor count,+ file sizes, source rows, columns, and aggregate response inputs are all+ bounded. Symlinked directories and files are ignored.Args:run_dir: Root directory of the run.- limit: Maximum number of factor results to return.-Returns:Factor result dicts sorted by name ascending."""artifacts_dir = run_dir / "artifacts"- if not artifacts_dir.is_dir():- return []- try:- candidates = list(artifacts_dir.rglob("ic_series.csv"))- except OSError:- return []results: List[Dict[str, Any]] = []- for csv_path in candidates:+ remaining_bytes = _FACTOR_MAX_TOTAL_ARTIFACT_BYTES+ remaining_rows = _FACTOR_MAX_TOTAL_ROWS+ for csv_path in _iter_factor_series_files(run_dir, max_results=_FACTOR_MAX_RESULTS):try:relative_dir = csv_path.parent.relative_to(run_dir)except ValueError:continue- if any(part == ".." or part.startswith(".") for part in relative_dir.parts):- continuedirectory = csv_path.parentname = "factor_analysis" if directory == artifacts_dir else directory.name- equity_rows, equity_cols = _load_group_equity_csv(directory / "group_equity.csv")++ truncated: Dict[str, bool] = {}+ ic_rows: List[Dict[str, Any]] = []+ ic_readable, ic_size, ic_degraded = _claim_factor_artifact(+ csv_path,+ max_file_bytes=_FACTOR_MAX_FILE_BYTES,+ remaining_bytes=remaining_bytes,+ )+ if ic_readable:+ remaining_bytes -= ic_size+ ic_rows, ic_rows_truncated = _load_ic_series_csv(+ csv_path,+ min(_FACTOR_MAX_ROWS_PER_CSV, remaining_rows),+ )+ remaining_rows -= len(ic_rows)+ if ic_rows_truncated:+ truncated["ic_series"] = True+ elif ic_degraded:+ truncated["ic_series"] = True++ summary: Optional[Dict[str, Any]] = None+ summary_path = directory / "ic_summary.json"+ summary_readable, summary_size, summary_degraded = _claim_factor_artifact(+ summary_path,+ max_file_bytes=_FACTOR_MAX_SUMMARY_BYTES,+ remaining_bytes=remaining_bytes,+ )+ if summary_readable:+ remaining_bytes -= summary_size+ summary, summary_parse_degraded = _load_factor_summary(summary_path)+ if summary_parse_degraded:+ truncated["ic_stats"] = True+ elif summary_degraded:+ truncated["ic_stats"] = True++ equity_rows: List[Dict[str, Any]] = []+ equity_cols: List[str] = []+ equity_path = directory / "group_equity.csv"+ equity_readable, equity_size, equity_degraded = _claim_factor_artifact(+ equity_path,+ max_file_bytes=_FACTOR_MAX_FILE_BYTES,+ remaining_bytes=remaining_bytes,+ )+ if equity_readable:+ remaining_bytes -= equity_size+ equity_rows, equity_cols, equity_rows_truncated = _load_group_equity_csv(+ equity_path,+ min(_FACTOR_MAX_ROWS_PER_CSV, remaining_rows),+ )+ remaining_rows -= len(equity_rows)+ if equity_rows_truncated:+ truncated["group_equity"] = True+ elif equity_degraded:+ truncated["group_equity"] = True+group_cols = [col for col in equity_cols if col.startswith("Group_")]spread_cols = group_cols or equity_colslong_short_spread: Optional[float] = None@@ -164,23 +386,26 @@ def _scan_factor_results(run_dir: Path, limit: int = 20) -> List[Dict[str, Any]]first_value = last_row.get(spread_cols[0])last_value = last_row.get(spread_cols[-1])if first_value is not None and last_value is not None:- long_short_spread = round(last_value - first_value, 6)+ spread = last_value - first_value+ if math.isfinite(spread):+ long_short_spread = round(spread, 6)group_final_equity = {col: last_row[col] for col in equity_cols if col in last_row}entry: Dict[str, Any] = {"name": name,"path": relative_dir.as_posix(),- "ic_series": _load_ic_series_csv(csv_path),+ "ic_series": ic_rows,}- summary = _load_json_file(directory / "ic_summary.json")if isinstance(summary, dict):entry["ic_stats"] = summaryentry["group_equity"] = equity_rowsentry["n_groups"] = len(group_cols)entry["long_short_spread"] = long_short_spreadentry["group_final_equity"] = group_final_equity+ if truncated:+ entry["truncated"] = truncatedresults.append(entry)- results.sort(key=lambda item: str(item["name"]))- return results[:limit]+ results.sort(key=lambda item: (str(item["name"]), str(item["path"])))+ return resultsdef _pearson_correlation(x_values: List[float], y_values: List[float]) -> float:@@ -194,9 +419,12 @@ def _pearson_correlation(x_values: List[float], y_values: List[float]) -> float:Pearson correlation in [-1, 1], or 0.0 when a variance is zero."""try:- return statistics.correlation(x_values, y_values)- except (statistics.StatisticsError, ValueError):+ correlation = statistics.correlation(x_values, y_values)+ except (statistics.StatisticsError, ValueError, OverflowError, ZeroDivisionError):+ return 0.0+ if not math.isfinite(correlation):return 0.0+ return max(-1.0, min(1.0, correlation))def _factor_ic_correlation(factors: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]:@@ -330,7 +558,7 @@ def _build_response_from_run_dir())- response.has_factor_artifacts = bool(_scan_factor_results(run_dir, limit=1))+ response.has_factor_artifacts = _has_factor_artifacts(run_dir)equity_path = run_dir / "artifacts" / "equity.csv"if equity_path.exists():diff --git a/agent/tests/test_factor_api.py b/agent/tests/test_factor_api.pyindex 5b39e7e21..9b1130633 100644--- a/agent/tests/test_factor_api.py+++ b/agent/tests/test_factor_api.py@@ -8,6 +8,7 @@ from pathlib import Pathfrom fastapi.testclient import TestClientimport api_server+from src.api import runs_routesdef _client(tmp_path: Path, monkeypatch) -> TestClient:@@ -183,3 +184,163 @@ def test_run_detail_has_factor_artifacts_flag(tmp_path: Path, monkeypatch) -> Noresponse_without = client.get("/runs/run_without_factor")assert response_without.status_code == 200assert response_without.json()["has_factor_artifacts"] is False+++def test_run_detail_factor_flag_does_not_load_payload_files(tmp_path: Path, monkeypatch) -> None:+ """The lightweight detail flag must only inspect directory entries."""+ client = _client(tmp_path, monkeypatch)+ run_dir = tmp_path / "runs" / "run_probe_only"+ _write_factor_bundle(+ run_dir,+ "momentum_20d",+ "date,IC\n2024-01-02,0.02\n",+ _summary(1),+ "date,Group_1,Group_2\n2024-01-02,1.0,1.1\n",+ )++ def fail_payload_read(*_args, **_kwargs):+ raise AssertionError("run detail existence probe opened factor payload")++ monkeypatch.setattr(runs_routes, "_load_ic_series_csv", fail_payload_read)+ monkeypatch.setattr(runs_routes, "_load_group_equity_csv", fail_payload_read)+ monkeypatch.setattr(runs_routes, "_load_factor_summary", fail_payload_read)++ response = client.get("/runs/run_probe_only")++ assert response.status_code == 200+ assert response.json()["has_factor_artifacts"] is True+++def test_factor_scan_caps_directory_entries(tmp_path: Path, monkeypatch) -> None:+ """A hostile wide tree cannot force an unbounded recursive traversal."""+ run_dir = tmp_path / "run_wide"+ artifacts_dir = run_dir / "artifacts"+ for index in range(40):+ (artifacts_dir / f"branch_{index:03d}").mkdir(parents=True)++ entry_limit = 7+ monkeypatch.setattr(runs_routes, "_FACTOR_MAX_SCAN_ENTRIES", entry_limit)+ real_scandir = runs_routes.os.scandir+ entries_seen = 0++ class GuardedScandir:+ def __init__(self, path: Path) -> None:+ self._context = real_scandir(path)+ self._iterator = None++ def __enter__(self):+ self._iterator = iter(self._context.__enter__())+ return self++ def __exit__(self, exc_type, exc_value, traceback):+ return self._context.__exit__(exc_type, exc_value, traceback)++ def __iter__(self):+ return self++ def __next__(self):+ nonlocal entries_seen+ assert self._iterator is not None+ entry = next(self._iterator)+ entries_seen += 1+ assert entries_seen <= entry_limit+ return entry++ monkeypatch.setattr(runs_routes.os, "scandir", GuardedScandir)++ assert runs_routes._has_factor_artifacts(run_dir) is False+ assert entries_seen == entry_limit+++def test_factor_scan_caps_nesting_depth(tmp_path: Path, monkeypatch) -> None:+ """A factor marker below the configured depth is never traversed."""+ run_dir = tmp_path / "run_deep"+ directory = run_dir / "artifacts"+ monkeypatch.setattr(runs_routes, "_FACTOR_MAX_SCAN_DEPTH", 2)+ for name in ("one", "two", "three"):+ directory = directory / name+ directory.mkdir(parents=True)+ (directory / "ic_series.csv").write_text("date,IC\n2024-01-02,0.1\n", encoding="utf-8")++ assert runs_routes._has_factor_artifacts(run_dir) is False+++def test_factor_endpoint_removes_non_finite_values(tmp_path: Path, monkeypatch) -> None:+ """NaN and infinities in every supported artifact never reach JSON."""+ client = _client(tmp_path, monkeypatch)+ run_dir = tmp_path / "runs" / "run_non_finite"+ bundle = _write_factor_bundle(+ run_dir,+ "unsafe_factor",+ "date,IC\n2024-01-02,NaN\n2024-01-03,Infinity\n2024-01-04,-Infinity\n2024-01-05,0.125\n",+ None,+ "date,Group_1,Group_2\n2024-01-02,NaN,1.1\n2024-01-03,0.9,Infinity\n2024-01-04,-Infinity,1.2\n",+ )+ (bundle / "ic_summary.json").write_text(+ '{"ic_mean": NaN, "ic_std": Infinity, "ir": -Infinity, "ic_count": 4, '+ '"nested": [1.0, NaN, {"value": Infinity}]}',+ encoding="utf-8",+ )++ response = client.get("/runs/run_non_finite/factor")++ assert response.status_code == 200+ assert "NaN" not in response.text+ assert "Infinity" not in response.text+ factor = response.json()["factors"][0]+ assert factor["ic_series"] == [{"date": "2024-01-05", "ic": 0.125}]+ assert factor["ic_stats"] == {+ "ic_mean": None,+ "ic_std": None,+ "ir": None,+ "ic_count": 4,+ "nested": [1.0, None, {"value": None}],+ }+ assert factor["group_equity"] == [+ {"date": "2024-01-02", "Group_2": 1.1},+ {"date": "2024-01-03", "Group_1": 0.9},+ {"date": "2024-01-04", "Group_2": 1.2},+ ]+ assert factor["long_short_spread"] is None+ assert factor["group_final_equity"] == {"Group_2": 1.2}+++def test_factor_endpoint_enforces_row_budgets(tmp_path: Path, monkeypatch) -> None:+ client = _client(tmp_path, monkeypatch)+ run_dir = tmp_path / "runs" / "run_row_budget"+ _write_factor_bundle(+ run_dir,+ "bounded_factor",+ "date,IC\n2024-01-01,0.1\n2024-01-02,0.2\n2024-01-03,0.3\n",+ _summary(3),+ "date,Group_1,Group_2\n2024-01-01,1.0,1.1\n2024-01-02,1.1,1.2\n2024-01-03,1.2,1.3\n",+ )+ monkeypatch.setattr(runs_routes, "_FACTOR_MAX_ROWS_PER_CSV", 2)+ monkeypatch.setattr(runs_routes, "_FACTOR_MAX_TOTAL_ROWS", 3)++ response = client.get("/runs/run_row_budget/factor")++ assert response.status_code == 200+ factor = response.json()["factors"][0]+ assert len(factor["ic_series"]) == 2+ assert len(factor["group_equity"]) == 1+ assert factor["truncated"] == {"ic_series": True, "group_equity": True}+++def test_factor_endpoint_rejects_oversized_summary(tmp_path: Path, monkeypatch) -> None:+ client = _client(tmp_path, monkeypatch)+ run_dir = tmp_path / "runs" / "run_large_summary"+ _write_factor_bundle(+ run_dir,+ "large_summary",+ "date,IC\n2024-01-02,0.1\n",+ {"padding": "x" * 100},+ )+ monkeypatch.setattr(runs_routes, "_FACTOR_MAX_SUMMARY_BYTES", 32)++ response = client.get("/runs/run_large_summary/factor")++ assert response.status_code == 200+ factor = response.json()["factors"][0]+ assert "ic_stats" not in factor+ assert factor["truncated"] == {"ic_stats": True}diff --git a/frontend/src/components/charts/FactorResearchPanel.tsx b/frontend/src/components/charts/FactorResearchPanel.tsxindex 9c04e2404..977e5735e 100644--- a/frontend/src/components/charts/FactorResearchPanel.tsx+++ b/frontend/src/components/charts/FactorResearchPanel.tsx@@ -236,7 +236,7 @@ export function FactorResearchPanel({ report }: { report: FactorReportPayload })<RunCardStat label={t("factor.icStd")} value={fixed(stats?.ic_std)} /><RunCardStat label={t("factor.ir")} value={fixed(stats?.ir)} /><RunCardStat label={t("factor.icPositiveRatio")} value={pct(stats?.ic_positive_ratio)} />- <RunCardStat label={t("factor.icCount")} value={stats ? String(stats.ic_count) : "—"} />+ <RunCardStat label={t("factor.icCount")} value={stats?.ic_count != null ? String(stats.ic_count) : "—"} /><RunCardStat label={t("factor.longShortSpread")} value={fixed(selected.long_short_spread)} /><RunCardStat label={t("factor.nGroups")} value={selected.n_groups ? String(selected.n_groups) : "—"} /></div>diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex c33510326..e7328a6a2 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -613,11 +613,12 @@ export interface RebalanceNotesPayload {}export interface FactorIcStats {- ic_mean: number;- ic_std: number;- ir: number;- ic_positive_ratio: number;- ic_count: number;+ ic_mean?: number | null;+ ic_std?: number | null;+ ir?: number | null;+ ic_positive_ratio?: number | null;+ ic_count?: number | null;+ [key: string]: unknown;}export interface FactorResult {@@ -629,6 +630,11 @@ export interface FactorResult {n_groups: number;long_short_spread: number | null;group_final_equity: Record<string, number>;+ truncated?: {+ ic_series?: boolean;+ ic_stats?: boolean;+ group_equity?: boolean;+ };}export interface FactorReportPayload {