Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(factors): fundamental factor layer Phase 1 — PIT-safe SEC fundamentals as daily panels

Haozhe Wu9c128a65445b
diff --git a/agent/backtest/loaders/_fundamental_schema.py b/agent/backtest/loaders/_fundamental_schema.py
new file mode 100644
index 000000000..c6612849f
--- /dev/null
+++ b/agent/backtest/loaders/_fundamental_schema.py
@@ -0,0 +1,226 @@
+"""Unified fundamental field schema and SEC XBRL concept aliases.
+
+This module is deliberately metadata-only. Callers use ``SEC_CONCEPT_MAP`` to
+extract sparse reported facts; when no concept hits, the caller must emit NaN
+for that field and log the missing alias coverage. This module does not log or
+fabricate fallback values.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from typing import Literal
+
+import pandas as pd
+
+FieldKind = Literal["raw", "derived"]
+RawFieldSpec = dict[str, object]
+DerivedCompute = Callable[[dict[str, pd.Series]], pd.Series]
+DerivedFieldSpec = dict[str, object]
+
+
+def _safe_divide(numerator: pd.Series, denominator: pd.Series) -> pd.Series:
+ """Divide two aligned series, returning NaN where the denominator is zero."""
+ clean_denominator = denominator.astype("float64").mask(denominator == 0)
+ return numerator.astype("float64") / clean_denominator
+
+
+RAW_FIELDS: dict[str, RawFieldSpec] = {
+ "revenue": {
+ "statement": "IS",
+ "description": "Revenue / net sales.",
+ },
+ "cogs": {
+ "statement": "IS",
+ "description": "Cost of goods sold or cost of revenue.",
+ },
+ "gross_profit": {
+ "statement": "IS",
+ "description": "Gross profit; derived as revenue minus cogs when not directly reported.",
+ "dependencies": ["revenue", "cogs"],
+ "compute": lambda data: data["revenue"] - data["cogs"],
+ },
+ "operating_income": {
+ "statement": "IS",
+ "description": "Operating income or loss.",
+ },
+ "net_income": {
+ "statement": "IS",
+ "description": "Net income or loss attributable to the reporting entity.",
+ },
+ "total_assets": {
+ "statement": "BS",
+ "description": "Total assets.",
+ },
+ "total_equity": {
+ "statement": "BS",
+ "description": "Total shareholders' equity.",
+ },
+ "total_debt": {
+ "statement": "BS",
+ "description": "Interest-bearing debt; aggregate debt concept when present, otherwise loader may union current and noncurrent debt concepts.",
+ },
+ "cash": {
+ "statement": "BS",
+ "description": "Cash and cash equivalents.",
+ },
+ "shares_diluted": {
+ "statement": "IS/cover",
+ "description": "Weighted-average diluted shares outstanding.",
+ },
+ "cfo": {
+ "statement": "CF",
+ "description": "Net cash provided by or used in operating activities.",
+ },
+ "capex": {
+ "statement": "CF",
+ "description": "Capital expenditures for property, plant, equipment, and similar productive assets.",
+ },
+}
+
+
+# Ordered by priority. SEC extraction should union concepts across aliases, then
+# keep the first filed value per period_end for PIT safety. The revenue order is
+# intentionally new-standard first: recent AAPL filings report revenue under
+# RevenueFromContractWithCustomer... rather than the old Revenues concept.
+SEC_CONCEPT_MAP: dict[str, list[str]] = {
+ "revenue": [
+ "RevenueFromContractWithCustomerExcludingAssessedTax",
+ "RevenueFromContractWithCustomerIncludingAssessedTax",
+ "Revenues",
+ "SalesRevenueNet",
+ ],
+ "cogs": [
+ "CostOfGoodsAndServicesSold",
+ "CostOfRevenue",
+ "CostOfGoodsSold",
+ ],
+ "gross_profit": [
+ "GrossProfit",
+ ],
+ "operating_income": [
+ "OperatingIncomeLoss",
+ ],
+ "net_income": [
+ "NetIncomeLoss",
+ "ProfitLoss",
+ ],
+ "total_assets": [
+ "Assets",
+ ],
+ "total_equity": [
+ "StockholdersEquity",
+ "StockholdersEquityIncludingPortionAttributableToNoncontrollingInterest",
+ ],
+ # US-GAAP has both aggregate and split debt concepts. Prefer aggregate debt
+ # when reported; otherwise a future loader should combine current and
+ # noncurrent concepts instead of treating one leg as total debt.
+ "total_debt": [
+ "LongTermDebtAndFinanceLeaseObligations",
+ "LongTermDebtAndCapitalLeaseObligations",
+ "LongTermDebt",
+ "LongTermDebtNoncurrent",
+ "LongTermDebtCurrent",
+ "DebtCurrent",
+ "ShortTermBorrowings",
+ ],
+ # Cash concept choice varies by industry and restricted-cash presentation.
+ # The first concept is the common operating-company aggregate; the rest keep
+ # banks and restricted-cash filers from hard-missing in Phase 1.
+ "cash": [
+ "CashAndCashEquivalentsAtCarryingValue",
+ "CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents",
+ "Cash",
+ "CashAndDueFromBanks",
+ ],
+ "shares_diluted": [
+ "WeightedAverageNumberOfDilutedSharesOutstanding",
+ "WeightedAverageDilutedSharesOutstanding",
+ ],
+ "cfo": [
+ "NetCashProvidedByUsedInOperatingActivities",
+ "NetCashProvidedByUsedInOperatingActivitiesContinuingOperations",
+ ],
+ # Capex is usually reported as PPE purchases. Some filers include broader
+ # productive-asset or PPE-plus-intangibles concepts; they are lower priority
+ # because they may not be strictly comparable to plain PPE capex.
+ "capex": [
+ "PaymentsToAcquirePropertyPlantAndEquipment",
+ "PaymentsToAcquireProductiveAssets",
+ "PaymentsToAcquirePropertyPlantAndEquipmentAndIntangibleAssets",
+ "CapitalExpendituresIncurredButNotYetPaid",
+ ],
+}
+
+
+DERIVED_FIELDS: dict[str, DerivedFieldSpec] = {
+ "roe": {
+ "dependencies": ["net_income", "total_equity"],
+ "compute": lambda data: _safe_divide(data["net_income"], data["total_equity"]),
+ },
+ "roa": {
+ "dependencies": ["net_income", "total_assets"],
+ "compute": lambda data: _safe_divide(data["net_income"], data["total_assets"]),
+ },
+ "gross_profitability": {
+ "dependencies": ["gross_profit", "total_assets"],
+ "compute": lambda data: _safe_divide(data["gross_profit"], data["total_assets"]),
+ },
+ # Annual semantics: input is one observation per annual period_end, sorted by
+ # period_end. Growth is period-over-period, value / value.shift(1) - 1.
+ # Quarterly or TTM callers must pre-aggregate before applying this formula.
+ "asset_growth": {
+ "dependencies": ["total_assets"],
+ "compute": lambda data: data["total_assets"].astype("float64")
+ / data["total_assets"].astype("float64").shift(1)
+ - 1,
+ },
+ "accruals": {
+ "dependencies": ["net_income", "cfo", "total_assets"],
+ "compute": lambda data: _safe_divide(
+ data["net_income"] - data["cfo"],
+ data["total_assets"],
+ ),
+ },
+ "leverage": {
+ "dependencies": ["total_debt", "total_equity"],
+ "compute": lambda data: _safe_divide(data["total_debt"], data["total_equity"]),
+ },
+}
+
+# Price-dependent value factors need market_cap = price * shares and therefore
+# live in factor files after fundamental and price panels have been aligned.
+# Do not add earnings_yield or book_to_market to DERIVED_FIELDS here.
+
+
+def resolve_field(field: str) -> tuple[FieldKind, RawFieldSpec | DerivedFieldSpec]:
+ """Resolve a supported fundamental field to its schema entry.
+
+ Args:
+ field: Unified fundamental field name.
+
+ Returns:
+ A ``("raw", spec)`` or ``("derived", spec)`` tuple.
+
+ Raises:
+ ValueError: If ``field`` is not part of the unified schema.
+ """
+ if field in RAW_FIELDS:
+ return "raw", RAW_FIELDS[field]
+ if field in DERIVED_FIELDS:
+ return "derived", DERIVED_FIELDS[field]
+ raise ValueError(f"unknown fundamental field: {field}")
+
+
+def list_supported_fields() -> list[str]:
+ """Return all supported raw and schema-derived fundamental field names."""
+ return sorted(set(RAW_FIELDS) | set(DERIVED_FIELDS))
+
+
+__all__ = [
+ "DERIVED_FIELDS",
+ "RAW_FIELDS",
+ "SEC_CONCEPT_MAP",
+ "list_supported_fields",
+ "resolve_field",
+]
diff --git a/agent/backtest/loaders/fundamentals_loader.py b/agent/backtest/loaders/fundamentals_loader.py
new file mode 100644
index 000000000..ba2318c85
--- /dev/null
+++ b/agent/backtest/loaders/fundamentals_loader.py
@@ -0,0 +1,479 @@
+"""Translate sparse SEC facts into PIT-safe daily fundamental panels.
+
+The loader's core invariant is point-in-time safety: values become visible on
+their SEC ``filed`` date, never on ``period_end``. Phase 1 implements the SEC
+branch only. ``freq="ttm"`` uses a pragmatic Phase-1 approximation: known
+income-statement and cash-flow concepts are rolling four-quarter sums keyed by
+``period_end`` and anchored by the latest ``filed`` date in the rolling window;
+balance-sheet and share-count concepts use the latest quarterly value. SEC
+companyfacts can mix true-quarter, year-to-date, and annual facts, so upstream
+schema normalization may still be needed for issuer-specific precision.
+"""
+
+from __future__ import annotations
+
+import importlib
+import logging
+from collections.abc import Iterable
+from typing import Any
+
+import pandas as pd
+
+from backtest.loaders import sec_edgar_client
+from backtest.loaders.base import cached_loader_fetch, validate_date_range
+
+logger = logging.getLogger(__name__)
+
+_VALID_FREQS = {"annual", "quarterly", "ttm"}
+_ANNUAL_FORMS = {"10-K"}
+_QUARTERLY_FORMS = {"10-Q", "10-K"}
+
+_FLOW_CONCEPTS = {
+ "RevenueFromContractWithCustomerExcludingAssessedTax",
+ "RevenueFromContractWithCustomerIncludingAssessedTax",
+ "Revenues",
+ "SalesRevenueNet",
+ "CostOfGoodsAndServicesSold",
+ "CostOfRevenue",
+ "OperatingIncomeLoss",
+ "NetIncomeLoss",
+ "ProfitLoss",
+ "NetCashProvidedByUsedInOperatingActivities",
+ "PaymentsToAcquirePropertyPlantAndEquipment",
+}
+
+
+def _extract_concept_series(
+ facts: dict[str, Any],
+ concepts: list[str],
+ freq: str,
+ *,
+ pit: bool = True,
+) -> pd.DataFrame:
+ """Extract a sparse ``period_end``/``filed``/``value`` series.
+
+ Args:
+ facts: SEC companyfacts payload.
+ concepts: Ordered us-gaap concept aliases to union.
+ freq: ``"annual"``, ``"quarterly"``, or ``"ttm"``.
+ pit: When true, duplicate ``period_end`` rows keep the earliest filing;
+ when false, they keep the latest filing for research mode.
+
+ Returns:
+ DataFrame with ``period_end``, ``filed``, and ``value`` columns.
+
+ Raises:
+ ValueError: If ``freq`` is unsupported.
+ """
+ if freq not in _VALID_FREQS:
+ raise ValueError(f"unsupported fundamental freq: {freq}")
+
+ rows: list[dict[str, Any]] = []
+ us_gaap = facts.get("facts", {}).get("us-gaap", {})
+ for concept_order, concept in enumerate(concepts):
+ concept_node = us_gaap.get(concept, {})
+ units = concept_node.get("units", {}) if isinstance(concept_node, dict) else {}
+ if not isinstance(units, dict):
+ continue
+ for unit_items in units.values():
+ if not isinstance(unit_items, list):
+ continue
+ for item in unit_items:
+ if not isinstance(item, dict):
+ continue
+ if not _form_allowed(str(item.get("form", "")), freq):
+ continue
+ rows.append(
+ {
+ "period_start": item.get("start"),
+ "period_end": item.get("end"),
+ "filed": item.get("filed"),
+ "value": item.get("val"),
+ "_concept_order": concept_order,
+ }
+ )
+
+ columns = ["period_end", "filed", "value"]
+ if not rows:
+ return pd.DataFrame(columns=columns)
+
+ df = pd.DataFrame(rows)
+ df["period_start"] = pd.to_datetime(df["period_start"], errors="coerce").dt.normalize()
+ df["period_end"] = pd.to_datetime(df["period_end"], errors="coerce").dt.normalize()
+ df["filed"] = pd.to_datetime(df["filed"], errors="coerce").dt.normalize()
+ df["value"] = pd.to_numeric(df["value"], errors="coerce")
+ df = df.dropna(subset=["period_end", "filed", "value"])
+ if df.empty:
+ return pd.DataFrame(columns=columns)
+
+ keep = "first" if pit else "last"
+ if _is_flow_concept_series(concepts):
+ # Duration entries mix true quarters, year-to-date frames sharing the
+ # same end date, and full-year frames; summing them blindly double
+ # counts. Select by (start, end) span before any dedupe or rolling.
+ df = df.dropna(subset=["period_start"])
+ df = df.sort_values(["period_start", "period_end", "filed", "_concept_order"])
+ df = df.drop_duplicates(subset=["period_start", "period_end"], keep=keep)
+ duration = (df["period_end"] - df["period_start"]).dt.days
+ if freq == "annual":
+ df = df[duration.between(330, 380)]
+ else:
+ df = _quarterly_flow_frames(df, duration)
+ else:
+ df = df.sort_values(["period_end", "filed", "_concept_order"])
+
+ df = df.drop_duplicates(subset=["period_end"], keep=keep).sort_values("period_end")
+
+ if freq == "ttm" and _is_flow_concept_series(concepts):
+ df = _to_ttm_flow_series(df)
+
+ return df.loc[:, columns].sort_values("period_end").reset_index(drop=True)
+
+
+def _quarterly_flow_frames(df: pd.DataFrame, duration: pd.Series) -> pd.DataFrame:
+ """Return true-quarter flow frames, deriving fiscal Q4 from 10-K full years.
+
+ Filers like AAPL report Q4 only inside the 10-K full-year frame, so a
+ missing quarter ending at the fiscal year end is synthesized as
+ ``FY - (Q1 + Q2 + Q3)``. The synthesized row is anchored on the 10-K
+ ``filed`` date, which keeps it PIT-safe.
+ """
+ quarters = df[duration.between(60, 120)].copy()
+ annuals = df[duration.between(330, 380)]
+ quarter_ends = set(quarters["period_end"])
+ synthesized: list[dict[str, Any]] = []
+ for annual in annuals.to_dict("records"):
+ if annual["period_end"] in quarter_ends:
+ continue
+ inside = quarters[
+ (quarters["period_start"] >= annual["period_start"])
+ & (quarters["period_end"] < annual["period_end"])
+ ]
+ if len(inside) != 3:
+ continue
+ synthesized.append(
+ {
+ "period_start": inside["period_end"].max(),
+ "period_end": annual["period_end"],
+ "filed": max(annual["filed"], inside["filed"].max()),
+ "value": annual["value"] - inside["value"].sum(),
+ "_concept_order": annual["_concept_order"],
+ }
+ )
+ if synthesized:
+ quarters = pd.concat([quarters, pd.DataFrame(synthesized)], ignore_index=True)
+ return quarters
+
+
+def _ffill_pit(series: pd.DataFrame, index: pd.DatetimeIndex) -> pd.Series:
+ """Forward-fill sparse values onto ``index`` using ``filed`` as the anchor.
+
+ Args:
+ series: DataFrame containing ``filed`` and ``value`` columns.
+ index: Target dates.
+
+ Returns:
+ Dense Series indexed like ``index``.
+ """
+ target_index = pd.DatetimeIndex(index)
+ if series.empty:
+ return pd.Series(index=target_index, dtype="float64")
+
+ sparse = series.copy()
+ sparse["filed"] = pd.to_datetime(sparse["filed"], errors="coerce").dt.normalize()
+ sparse["value"] = pd.to_numeric(sparse["value"], errors="coerce")
+ sparse = sparse.dropna(subset=["filed", "value"]).sort_values("filed")
+ if sparse.empty:
+ return pd.Series(index=target_index, dtype="float64")
+
+ values = sparse.set_index("filed")["value"].sort_index()
+ values = values[~values.index.duplicated(keep="last")]
+ aligned_index = values.index.union(target_index)
+ return values.reindex(aligned_index).ffill().reindex(target_index)
+
+
+def load_fundamental_panel(
+ symbols: list[str],
+ fields: list[str],
+ start: str,
+ end: str,
+ freq: str = "ttm",
+ pit: bool = True,
+ source: str = "auto",
+ index: pd.DatetimeIndex | None = None,
+) -> dict[str, pd.DataFrame]:
+ """Load SEC fundamental fields as dense date-by-symbol panels.
+
+ Args:
+ symbols: Tickers to load.
+ fields: Unified schema field names, raw or derived.
+ start: Inclusive start date.
+ end: Inclusive end date.
+ freq: ``"annual"``, ``"quarterly"``, or ``"ttm"``.
+ pit: True keeps first filed facts per period; false keeps latest filed.
+ source: ``"auto"`` or ``"sec"``. Phase 1 routes both to SEC.
+ index: Optional target date index. When omitted, calendar days from
+ ``start`` through ``end`` are used.
+
+ Returns:
+ Mapping ``field -> DataFrame(index=dates, columns=symbols)``.
+
+ Raises:
+ ValueError: If source or frequency is unsupported.
+ RuntimeError: If the fundamental schema module is unavailable.
+ """
+ validate_date_range(start, end)
+ if freq not in _VALID_FREQS:
+ raise ValueError(f"unsupported fundamental freq: {freq}")
+ if source not in {"auto", "sec"}:
+ raise ValueError("Phase 1 fundamentals loader supports source='auto' or 'sec' only")
+
+ target_index = _target_index(start, end, index)
+ schema = _load_schema()
+ requested_fields = [_resolve_field_name(schema, field) for field in fields]
+ raw_fields = sorted(_collect_raw_fields(schema, requested_fields))
+ symbol_list = list(symbols)
+
+ ciks = _resolve_ciks(symbol_list)
+ symbol_raw_frames = {
+ symbol: _load_symbol_raw_frame(
+ symbol=symbol,
+ cik=ciks.get(symbol),
+ raw_fields=raw_fields,
+ schema=schema,
+ start=start,
+ end=end,
+ freq=freq,
+ pit=pit,
+ index=target_index,
+ )
+ for symbol in symbol_list
+ }
+
+ panels: dict[str, pd.DataFrame] = {}
+ for field in raw_fields:
+ panels[field] = pd.DataFrame(
+ {symbol: symbol_raw_frames[symbol][field] for symbol in symbol_list},
+ index=target_index,
+ columns=symbol_list,
+ )
+
+ def panel_for(field: str) -> pd.DataFrame:
+ if field in panels:
+ return panels[field]
+ derived = _derived_field(schema, field)
+ if derived is None:
+ panels[field] = _empty_panel(target_index, symbol_list)
+ return panels[field]
+ deps = {
+ _resolve_field_name(schema, dep): panel_for(_resolve_field_name(schema, dep))
+ for dep in _derived_dependencies(derived)
+ }
+ computed = _compute_derived(derived, deps)
+ panels[field] = computed.reindex(index=target_index, columns=symbol_list)
+ return panels[field]
+
+ return {field: panel_for(field) for field in requested_fields}
+
+
+def _form_allowed(form: str, freq: str) -> bool:
+ if freq == "annual":
+ return form in _ANNUAL_FORMS
+ if freq in {"quarterly", "ttm"}:
+ return form in _QUARTERLY_FORMS
+ return False
+
+
+def _is_flow_concept_series(concepts: Iterable[str]) -> bool:
+ return any(concept in _FLOW_CONCEPTS for concept in concepts)
+
+
+def _to_ttm_flow_series(df: pd.DataFrame) -> pd.DataFrame:
+ ttm = df.sort_values("period_end").copy()
+ ttm["value"] = ttm["value"].rolling(window=4, min_periods=4).sum()
+ filed_values = list(ttm["filed"])
+ ttm["filed"] = [
+ pd.NaT if pos < 3 else max(filed_values[pos - 3 : pos + 1])
+ for pos in range(len(filed_values))
+ ]
+ return ttm.dropna(subset=["filed", "value"])
+
+
+def _target_index(
+ start: str,
+ end: str,
+ index: pd.DatetimeIndex | None,
+) -> pd.DatetimeIndex:
+ if index is not None:
+ return pd.DatetimeIndex(index)
+ return pd.date_range(pd.Timestamp(start), pd.Timestamp(end), freq="D")
+
+
+def _load_schema() -> Any:
+ try:
+ return importlib.import_module("backtest.loaders._fundamental_schema")
+ except ModuleNotFoundError as exc:
+ raise RuntimeError(
+ "backtest.loaders._fundamental_schema is required for fundamentals loading"
+ ) from exc
+
+
+def _resolve_field_name(schema: Any, field: str) -> str:
+ normalized = str(field).removeprefix("fund:")
+ resolver = getattr(schema, "resolve_field", None)
+ if not callable(resolver):
+ return normalized
+ resolved = resolver(normalized)
+ if isinstance(resolved, str):
+ return resolved.removeprefix("fund:")
+ name = getattr(resolved, "name", None)
+ if isinstance(name, str):
+ return name.removeprefix("fund:")
+ return normalized
+
+
+def _collect_raw_fields(schema: Any, fields: Iterable[str]) -> set[str]:
+ raw: set[str] = set()
+ visiting: set[str] = set()
+
+ def visit(field: str) -> None:
+ if field in visiting:
+ raise ValueError(f"cyclic derived fundamental field: {field}")
+ derived = _derived_field(schema, field)
+ if derived is None:
+ raw.add(field)
+ return
+ visiting.add(field)
+ for dep in _derived_dependencies(derived):
+ visit(_resolve_field_name(schema, dep))
+ visiting.remove(field)
+
+ for field in fields:
+ visit(field)
+ return raw
+
+
+def _derived_field(schema: Any, field: str) -> Any | None:
+ return getattr(schema, "DERIVED_FIELDS", {}).get(field)
+
+
+def _spec_get(derived: Any, key: str) -> Any:
+ """Read a derived-field spec entry from either a mapping or an object."""
+ if isinstance(derived, dict):
+ return derived.get(key)
+ return getattr(derived, key, None)
+
+
+def _derived_dependencies(derived: Any) -> list[str]:
+ deps = _spec_get(derived, "dependencies") or ()
+ return [str(dep) for dep in deps]
+
+
+def _compute_derived(derived: Any, dependencies: dict[str, pd.DataFrame]) -> pd.DataFrame:
+ compute = _spec_get(derived, "compute")
+ if not callable(compute):
+ raise ValueError(f"derived field has no callable compute: {derived!r}")
+ try:
+ result = compute(dependencies)
+ except TypeError:
+ result = compute(**dependencies)
+ if not isinstance(result, pd.DataFrame):
+ result = pd.DataFrame(result)
+ return result
+
+
+def _resolve_ciks(symbols: list[str]) -> dict[str, str | None]:
+ ciks: dict[str, str | None] = {}
+ missing: list[str] = []
+ for symbol in symbols:
+ cik = sec_edgar_client.cik_for(symbol)
+ ciks[symbol] = cik
+ if cik is None:
+ missing.append(symbol)
+ if missing:
+ logger.warning("No SEC CIK for symbols: %s", ", ".join(missing))
+ return ciks
+
+
+def _load_symbol_raw_frame(
+ *,
+ symbol: str,
+ cik: str | None,
+ raw_fields: list[str],
+ schema: Any,
+ start: str,
+ end: str,
+ freq: str,
+ pit: bool,
+ index: pd.DatetimeIndex,
+) -> pd.DataFrame:
+ if cik is None:
+ return _empty_field_frame(index, raw_fields)
+
+ def fetch() -> pd.DataFrame:
+ return _fetch_symbol_raw_frame(
+ symbol=symbol,
+ cik=cik,
+ raw_fields=raw_fields,
+ schema=schema,
+ freq=freq,
+ pit=pit,
+ index=index,
+ )
+
+ cached = cached_loader_fetch(
+ source="sec_fundamentals",
+ symbol=symbol,
+ timeframe=f"{freq}:pit={int(pit)}",
+ start_date=start,
+ end_date=end,
+ fields=raw_fields,
+ fetch=fetch,
+ )
+ if cached is None:
+ return _empty_field_frame(index, raw_fields)
+ return cached.reindex(index=index, columns=raw_fields)
+
+
+def _fetch_symbol_raw_frame(
+ *,
+ symbol: str,
+ cik: str,
+ raw_fields: list[str],
+ schema: Any,
+ freq: str,
+ pit: bool,
+ index: pd.DatetimeIndex,
+) -> pd.DataFrame:
+ try:
+ facts = sec_edgar_client.get_company_facts(cik)
+ except Exception as exc: # noqa: BLE001 - one bad symbol should not abort the panel
+ logger.warning("SEC companyfacts failed for %s: %s", symbol, exc)
+ return _empty_field_frame(index, raw_fields)
+
+ frame = _empty_field_frame(index, raw_fields)
+ concept_map = getattr(schema, "SEC_CONCEPT_MAP", {})
+ for field in raw_fields:
+ concepts = list(concept_map.get(field, ()))
+ if not concepts:
+ logger.warning("SEC concept miss for %s field %s: no aliases configured", symbol, field)
+ continue
+ sparse = _extract_concept_series(facts, concepts, freq, pit=pit)
+ if sparse.empty:
+ logger.warning(
+ "SEC concept miss for %s field %s: aliases=%s",
+ symbol,
+ field,
+ ",".join(concepts),
+ )
+ continue
+ frame[field] = _ffill_pit(sparse, index)
+ return frame
+
+
+def _empty_field_frame(index: pd.DatetimeIndex, fields: list[str]) -> pd.DataFrame:
+ return pd.DataFrame(index=index, columns=fields, dtype="float64")
+
+
+def _empty_panel(index: pd.DatetimeIndex, symbols: list[str]) -> pd.DataFrame:
+ return pd.DataFrame(index=index, columns=symbols, dtype="float64")
diff --git a/agent/backtest/runner.py b/agent/backtest/runner.py
index c1265fb56..1b850b84b 100644
--- a/agent/backtest/runner.py
+++ b/agent/backtest/runner.py
@@ -14,7 +14,7 @@ import json
import logging
import sys
from pathlib import Path
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, Iterable, List, Optional
import pandas as pd
from pydantic import BaseModel, ConfigDict, model_validator, field_validator
@@ -48,6 +48,8 @@ logger = logging.getLogger(__name__)
_VALID_INTERVALS = {"1m", "5m", "15m", "30m", "1H", "4H", "1D"}
_VALID_ENGINES = {"daily", "options"}
+_PRICE_PANEL_COLUMNS = ("open", "high", "low", "close", "volume", "vwap", "amount")
+_FUND_PREFIX = "fund:"
class BacktestConfigSchema(BaseModel):
@@ -386,6 +388,242 @@ def _normalize_codes(codes: List[str], source: str) -> List[str]:
return codes
+def _columns_required_from_factor_spec(spec: Any) -> list[str]:
+ """Extract ``columns_required`` from supported factor spec shapes.
+
+ Args:
+ spec: Factor metadata as a dict, an Alpha-like object with ``meta``, an
+ object with ``columns_required``, or a raw string alpha id.
+
+ Returns:
+ Declared panel columns, or an empty list when the shape has none.
+ """
+ if isinstance(spec, dict):
+ meta = spec.get("meta")
+ if isinstance(meta, dict):
+ return [str(c) for c in meta.get("columns_required", [])]
+ return [str(c) for c in spec.get("columns_required", [])]
+ meta = getattr(spec, "meta", None)
+ if isinstance(meta, dict):
+ return [str(c) for c in meta.get("columns_required", [])]
+ columns = getattr(spec, "columns_required", None)
+ if columns is not None:
+ return [str(c) for c in columns]
+ return []
+
+
+def _selected_factor_specs(config: dict) -> list[Any]:
+ """Return selected factor metadata configured for the run.
+
+ The current runner has no dedicated factor-zoo execution path, so this
+ accepts the shapes used by callers that already know factor metadata
+ (``selected_factors``/``factors``/``alpha_metas``) and alpha-id lists that
+ can be resolved through the registry.
+
+ Args:
+ config: Backtest config.
+
+ Returns:
+ Factor specs or metadata dictionaries.
+ """
+ specs: list[Any] = []
+ for key in ("selected_factors", "factors", "alpha_metas"):
+ raw = config.get(key)
+ if isinstance(raw, list):
+ specs.extend(raw)
+ elif raw:
+ specs.append(raw)
+
+ alpha_ids: list[str] = []
+ for key in ("alpha_ids", "factor_ids", "alphas"):
+ raw = config.get(key)
+ if raw is None:
+ continue
+ if isinstance(raw, str):
+ alpha_ids.append(raw)
+ else:
+ alpha_ids.extend(str(item) for item in raw)
+
+ if alpha_ids:
+ from src.factors.registry import get_default_registry
+
+ registry = get_default_registry()
+ for alpha_id in alpha_ids:
+ try:
+ specs.append(registry.get(alpha_id).meta)
+ except KeyError:
+ logger.warning("selected alpha_id %r is not registered; skipping", alpha_id)
+ return specs
+
+
+def _fund_columns_required(selected_factors: Iterable[Any]) -> list[str]:
+ """Collect requested ``fund:*`` panel columns from selected factors.
+
+ Args:
+ selected_factors: Factor metadata/spec objects.
+
+ Returns:
+ Stable, de-duplicated ``fund:*`` column names.
+ """
+ seen: set[str] = set()
+ out: list[str] = []
+ for spec in selected_factors:
+ for column in _columns_required_from_factor_spec(spec):
+ if not column.startswith(_FUND_PREFIX) or column in seen:
+ continue
+ seen.add(column)
+ out.append(column)
+ return out
+
+
+def _build_price_panel(data_map: dict[str, pd.DataFrame]) -> dict[str, pd.DataFrame]:
+ """Convert ``code -> OHLCV frame`` rows into the factor panel shape.
+
+ Args:
+ data_map: Backtest loader output.
+
+ Returns:
+ ``column -> dates x symbols`` panel for price columns present in the
+ data map.
+ """
+ panel: dict[str, pd.DataFrame] = {}
+ for column in _PRICE_PANEL_COLUMNS:
+ series_by_symbol = {
+ symbol: frame[column]
+ for symbol, frame in data_map.items()
+ if column in frame.columns
+ }
+ if series_by_symbol:
+ panel[column] = pd.DataFrame(series_by_symbol)
+ return panel
+
+
+def _nan_fundamental_frame(
+ index: pd.DatetimeIndex,
+ symbols: list[str],
+) -> pd.DataFrame:
+ """Build an all-NaN fundamental panel frame."""
+ return pd.DataFrame(float("nan"), index=index, columns=symbols)
+
+
+def _inject_fundamental_panel(
+ panel: dict[str, pd.DataFrame],
+ *,
+ symbols: list[str],
+ fund_columns: Iterable[str],
+ start: str,
+ end: str,
+ freq: str = "ttm",
+ pit: bool = True,
+ source: str = "auto",
+ index: pd.DatetimeIndex | None = None,
+) -> dict[str, pd.DataFrame]:
+ """Inject required fundamental fields into a factor panel.
+
+ Args:
+ panel: Existing factor panel keyed by column name.
+ symbols: Symbols to load.
+ fund_columns: Requested ``fund:*`` columns.
+ start: Start date string.
+ end: End date string.
+ freq: Fundamental frequency. Defaults to ``ttm``.
+ pit: Whether point-in-time loading is enforced.
+ source: Fundamental data source route.
+ index: Optional price index to align to. Defaults to ``panel["close"]``.
+
+ Returns:
+ The same panel dictionary with ``fund:<field>`` frames added.
+ """
+ fields = [column[len(_FUND_PREFIX):] for column in fund_columns if column.startswith(_FUND_PREFIX)]
+ fields = list(dict.fromkeys(fields))
+ if not fields:
+ return panel
+
+ price_index = index
+ if price_index is None:
+ close = panel.get("close")
+ price_index = close.index if close is not None else pd.DatetimeIndex([])
+
+ try:
+ from backtest.loaders.fundamentals_loader import load_fundamental_panel
+
+ loaded = load_fundamental_panel(
+ symbols=symbols,
+ fields=fields,
+ start=start,
+ end=end,
+ freq=freq,
+ pit=pit,
+ source=source,
+ index=price_index,
+ )
+ except Exception as exc: # noqa: BLE001 - data-source failure must not kill backtest
+ logger.warning(
+ "fundamental panel load failed for fields=%s symbols=%s: %s; injecting NaN frames",
+ fields,
+ symbols,
+ exc,
+ exc_info=True,
+ )
+ loaded = {}
+
+ for field in fields:
+ frame = loaded.get(field)
+ if not isinstance(frame, pd.DataFrame):
+ frame = _nan_fundamental_frame(price_index, symbols)
+ else:
+ frame = frame.reindex(index=price_index, columns=symbols)
+ panel[f"{_FUND_PREFIX}{field}"] = frame
+ return panel
+
+
+def _project_panel_fields_to_data_map(
+ data_map: dict[str, pd.DataFrame],
+ panel: dict[str, pd.DataFrame],
+ fund_columns: Iterable[str],
+) -> dict[str, pd.DataFrame]:
+ """Copy injected panel fields back to per-symbol backtest frames."""
+ out = {symbol: frame.copy() for symbol, frame in data_map.items()}
+ for column in fund_columns:
+ frame = panel.get(column)
+ if frame is None:
+ continue
+ for symbol, symbol_frame in out.items():
+ if symbol in frame.columns:
+ symbol_frame[column] = frame[symbol].reindex(symbol_frame.index)
+ else:
+ symbol_frame[column] = float("nan")
+ return out
+
+
+def _maybe_inject_fundamentals_for_factor_panel(
+ data_map: dict[str, pd.DataFrame],
+ config: dict,
+) -> dict[str, pd.DataFrame]:
+ """Inject ``fund:*`` factor dependencies when selected factors request them."""
+ selected_factors = _selected_factor_specs(config)
+ fund_columns = _fund_columns_required(selected_factors)
+ if not fund_columns:
+ return data_map
+
+ panel = _build_price_panel(data_map)
+ close = panel.get("close")
+ price_index = close.index if close is not None else pd.DatetimeIndex([])
+ symbols = list(data_map)
+ _inject_fundamental_panel(
+ panel,
+ symbols=symbols,
+ fund_columns=fund_columns,
+ start=config.get("start_date", ""),
+ end=config.get("end_date", ""),
+ freq="ttm",
+ pit=True,
+ source="auto",
+ index=price_index,
+ )
+ return _project_panel_fields_to_data_map(data_map, panel, fund_columns)
+
+
# --- Main entry ---
def main(run_dir: Path) -> None:
@@ -507,6 +745,7 @@ def main(run_dir: Path) -> None:
if not data_map:
print(json.dumps({"error": "No data fetched"}))
sys.exit(1)
+ data_map = _maybe_inject_fundamentals_for_factor_panel(data_map, config)
if source == "auto":
config["_run_card_effective_sources"] = sorted(_group_codes_by_source(codes))
diff --git a/agent/src/factors/base.py b/agent/src/factors/base.py
index 43c63678f..2ed030775 100644
--- a/agent/src/factors/base.py
+++ b/agent/src/factors/base.py
@@ -65,6 +65,18 @@ def rank(df: pd.DataFrame) -> pd.DataFrame:
return df.rank(axis=1, method="average", pct=True, na_option="keep")
+def zscore(df: pd.DataFrame) -> pd.DataFrame:
+ """Cross-sectional z-score per row (axis=1, sample std).
+
+ Rows with zero or NaN standard deviation become NaN — never silent zero.
+ """
+ df = _as_float(df)
+ mean = df.mean(axis=1, skipna=True)
+ std = df.std(axis=1, ddof=1, skipna=True)
+ result = df.sub(mean, axis=0).div(std.where(std > 0), axis=0)
+ return result.replace([np.inf, -np.inf], np.nan)
+
+
def scale(df: pd.DataFrame, a: float = 1.0) -> pd.DataFrame:
"""Per-row L1 normalize so sum of absolute values equals ``a``.
diff --git a/agent/src/factors/registry.py b/agent/src/factors/registry.py
index 77dfbf393..98a857bd2 100644
--- a/agent/src/factors/registry.py
+++ b/agent/src/factors/registry.py
@@ -35,7 +35,7 @@ from typing import Any, Literal
import numpy as np
import pandas as pd
-from pydantic import BaseModel, ConfigDict, Field, ValidationError
+from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
from src.factors.base import Alpha
@@ -59,11 +59,31 @@ Theme = Literal[
"leverage",
]
-PanelColumn = Literal["open", "high", "low", "close", "volume", "vwap", "amount"]
+_PRICE_COLS = {"open", "high", "low", "close", "volume", "vwap", "amount"}
+
+PanelColumn = str
Universe = Literal["equity_us", "equity_cn", "equity_hk", "crypto", "futures"]
+def validate_columns_required(cols: list[str]) -> None:
+ """Validate required panel columns for alpha metadata.
+
+ Args:
+ cols: Declared panel columns from ``__alpha_meta__``.
+
+ Raises:
+ ValueError: If a column is neither a known price column nor a
+ ``fund:``-prefixed fundamental column.
+ """
+ for column in cols:
+ if column in _PRICE_COLS:
+ continue
+ if column.startswith("fund:"):
+ continue
+ raise ValueError(f"unknown panel column: {column}")
+
+
class AlphaMeta(BaseModel):
"""Strict metadata schema; matches the ``__alpha_meta__`` dict literal."""
@@ -78,10 +98,32 @@ class AlphaMeta(BaseModel):
requires_sector: bool = False
universe: list[Universe]
frequency: list[str]
- decay_horizon: int = Field(ge=0, le=60)
+ decay_horizon: int = Field(ge=0, le=512)
min_warmup_bars: int = Field(ge=0)
notes: str = ""
+ @field_validator("columns_required")
+ @classmethod
+ def validate_columns_required(cls, v: list[str]) -> list[str]:
+ """Validate factor panel dependencies.
+
+ Price columns are fixed, while fundamental fields are an open namespace
+ under the ``fund:`` prefix. The runtime loader decides whether a
+ particular fundamental field can be populated.
+
+ Args:
+ v: Declared panel columns.
+
+ Returns:
+ The validated column list.
+
+ Raises:
+ ValueError: If any column is outside the price set and the
+ ``fund:`` namespace.
+ """
+ validate_columns_required(v)
+ return v
+
class SkipAlpha(Exception):
"""Raised when an alpha's preconditions (sector, columns) are not met."""
diff --git a/agent/src/factors/zoo/fundamental/__init__.py b/agent/src/factors/zoo/fundamental/__init__.py
new file mode 100644
index 000000000..98eb8ae92
--- /dev/null
+++ b/agent/src/factors/zoo/fundamental/__init__.py
@@ -0,0 +1 @@
+"""Fundamental alpha zoo — PIT-safe factors over the ``fund:*`` panel columns."""
diff --git a/agent/src/factors/zoo/fundamental/asset_growth.py b/agent/src/factors/zoo/fundamental/asset_growth.py
new file mode 100644
index 000000000..9d0ef958c
--- /dev/null
+++ b/agent/src/factors/zoo/fundamental/asset_growth.py
@@ -0,0 +1,29 @@
+"""Fundamental asset-growth investment factor."""
+
+from __future__ import annotations
+
+import pandas as pd
+
+from src.factors.base import zscore
+
+__alpha_meta__ = {
+ "id": "fund_asset_growth",
+ "nickname": "Asset growth - inverse investment factor",
+ "theme": ["growth"],
+ "formula_latex": r"-\mathrm{zscore}_{x}(\Delta \mathrm{total\_assets}_{YoY})",
+ "columns_required": ["fund:asset_growth"],
+ "universe": ["equity_us", "equity_cn", "equity_hk"],
+ "frequency": ["1d"],
+ "decay_horizon": 252,
+ "min_warmup_bars": 1,
+ "notes": (
+ "Inverse PIT-safe asset-growth factor. High asset growth is treated as "
+ "aggressive investment and receives lower scores; low/negative growth "
+ "receives higher scores."
+ ),
+}
+
+
+def compute(panel: dict[str, pd.DataFrame]) -> pd.DataFrame:
+ """Return negative cross-sectional z-scored asset growth."""
+ return -zscore(panel["fund:asset_growth"])
diff --git a/agent/src/factors/zoo/fundamental/earnings_yield.py b/agent/src/factors/zoo/fundamental/earnings_yield.py
new file mode 100644
index 000000000..f55996888
--- /dev/null
+++ b/agent/src/factors/zoo/fundamental/earnings_yield.py
@@ -0,0 +1,36 @@
+"""Fundamental earnings-yield value factor."""
+
+from __future__ import annotations
+
+import pandas as pd
+
+from src.factors.base import safe_div
+from src.factors.base import zscore
+
+__alpha_meta__ = {
+ "id": "fund_earnings_yield",
+ "nickname": "Earnings yield - net income over market cap",
+ "theme": ["value"],
+ "formula_latex": (
+ r"\mathrm{zscore}_{x}\left("
+ r"\frac{\mathrm{net\_income}}{\mathrm{close}\times\mathrm{shares\_diluted}}"
+ r"\right)"
+ ),
+ "columns_required": ["close", "fund:net_income", "fund:shares_diluted"],
+ "universe": ["equity_us", "equity_cn", "equity_hk"],
+ "frequency": ["1d"],
+ "decay_horizon": 252,
+ "min_warmup_bars": 1,
+ "notes": (
+ "Hybrid value factor using PIT-safe net income and shares diluted "
+ "aligned to the daily close panel. Division by zero/non-finite market "
+ "cap becomes NaN before cross-sectional scoring."
+ ),
+}
+
+
+def compute(panel: dict[str, pd.DataFrame]) -> pd.DataFrame:
+ """Return cross-sectional z-scored earnings yield."""
+ market_cap = panel["close"] * panel["fund:shares_diluted"]
+ earnings_yield = safe_div(panel["fund:net_income"], market_cap)
+ return zscore(earnings_yield)
diff --git a/agent/src/factors/zoo/fundamental/gross_profitability.py b/agent/src/factors/zoo/fundamental/gross_profitability.py
new file mode 100644
index 000000000..3045ca599
--- /dev/null
+++ b/agent/src/factors/zoo/fundamental/gross_profitability.py
@@ -0,0 +1,28 @@
+"""Fundamental gross-profitability quality factor."""
+
+from __future__ import annotations
+
+import pandas as pd
+
+from src.factors.base import zscore
+
+__alpha_meta__ = {
+ "id": "fund_gross_profitability",
+ "nickname": "Gross profitability - gross profit over total assets",
+ "theme": ["quality"],
+ "formula_latex": r"\mathrm{zscore}_{x}(\mathrm{gross\_profit}/\mathrm{total\_assets})",
+ "columns_required": ["fund:gross_profitability"],
+ "universe": ["equity_us", "equity_cn", "equity_hk"],
+ "frequency": ["1d"],
+ "decay_horizon": 252,
+ "min_warmup_bars": 1,
+ "notes": (
+ "PIT-safe Novy-Marx style gross profitability from the fundamental "
+ "panel; cross-sectional z-score per date with missing issuers excluded."
+ ),
+}
+
+
+def compute(panel: dict[str, pd.DataFrame]) -> pd.DataFrame:
+ """Return cross-sectional z-scored gross profitability."""
+ return zscore(panel["fund:gross_profitability"])
diff --git a/agent/src/factors/zoo/fundamental/roe.py b/agent/src/factors/zoo/fundamental/roe.py
new file mode 100644
index 000000000..4910d27e8
--- /dev/null
+++ b/agent/src/factors/zoo/fundamental/roe.py
@@ -0,0 +1,29 @@
+"""Fundamental ROE quality factor."""
+
+from __future__ import annotations
+
+import pandas as pd
+
+from src.factors.base import zscore
+
+__alpha_meta__ = {
+ "id": "fund_roe",
+ "nickname": "ROE - return on equity (PIT-safe fundamentals)",
+ "theme": ["quality"],
+ "formula_latex": r"\mathrm{zscore}_{x}(\mathrm{ROE})",
+ "columns_required": ["fund:roe"],
+ "universe": ["equity_us", "equity_cn", "equity_hk"],
+ "frequency": ["1d"],
+ "decay_horizon": 252,
+ "min_warmup_bars": 1,
+ "notes": (
+ "PIT-safe return on equity from the fundamental panel; cross-sectional "
+ "z-score per date. Missing statements remain NaN and are excluded from "
+ "that date's cross-section."
+ ),
+}
+
+
+def compute(panel: dict[str, pd.DataFrame]) -> pd.DataFrame:
+ """Return cross-sectional z-scored ROE."""
+ return zscore(panel["fund:roe"])
diff --git a/agent/src/tools/get_fundamentals_tool.py b/agent/src/tools/get_fundamentals_tool.py
new file mode 100644
index 000000000..ca2bda35c
--- /dev/null
+++ b/agent/src/tools/get_fundamentals_tool.py
@@ -0,0 +1,202 @@
+"""Read-only fundamental panel facade backed by the loader layer."""
+
+from __future__ import annotations
+
+import json
+import logging
+import math
+from typing import Any
+
+import pandas as pd
+
+from src.agent.tools import BaseTool
+
+logger = logging.getLogger(__name__)
+
+_VALID_FREQS = ("annual", "quarterly", "ttm")
+_VALID_SOURCES = ("auto", "sec", "eastmoney", "tushare")
+
+
+def _error(message: str) -> str:
+ """Build the failure envelope as a JSON string.
+
+ Args:
+ message: Human-readable error description.
+
+ Returns:
+ A strict JSON ``{"ok": false, "error": ...}`` string.
+ """
+ return json.dumps({"ok": False, "error": message}, ensure_ascii=False)
+
+
+def _json_safe(value: Any) -> Any:
+ """Convert provider/scalar values to strict-JSON-safe values."""
+ if hasattr(value, "isoformat"):
+ return value.isoformat()
+ if hasattr(value, "item"):
+ value = value.item()
+ if isinstance(value, float) and not math.isfinite(value):
+ return None
+ return value
+
+
+def _frame_records(df: pd.DataFrame) -> list[dict[str, Any]]:
+ """Serialize a wide fundamental panel DataFrame as JSON-safe records.
+
+ Args:
+ df: Wide DataFrame indexed by date with symbols as columns.
+
+ Returns:
+ Row records matching the existing market-data JSON style.
+ """
+ frame = df.copy()
+ frame.index.name = frame.index.name or "date"
+ records = frame.reset_index().to_dict(orient="records")
+ for row in records:
+ for key, value in row.items():
+ row[key] = _json_safe(value)
+ return records
+
+
+class GetFundamentalsTool(BaseTool):
+ """Fetch PIT-aligned fundamental fields as daily wide panels."""
+
+ name = "get_fundamentals"
+ description = (
+ "Fetch PIT-safe fundamental fields as daily wide panels aligned by filed "
+ "date. Returns {field: date x symbol records}. Fields use the unified "
+ "fundamental schema, e.g. roe, gross_profitability, net_income, "
+ "shares_diluted. Default freq is ttm and PIT mode is on."
+ )
+ parameters = {
+ "type": "object",
+ "properties": {
+ "symbols": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": 'Symbols such as ["AAPL.US", "600519.SH", "00700.HK"].',
+ },
+ "fields": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": 'Unified schema fields, e.g. ["roe", "net_income"].',
+ },
+ "start": {
+ "type": "string",
+ "description": "Start date in YYYY-MM-DD format.",
+ },
+ "end": {
+ "type": "string",
+ "description": "End date in YYYY-MM-DD format.",
+ },
+ "freq": {
+ "type": "string",
+ "enum": list(_VALID_FREQS),
+ "description": "Reporting cadence: annual, quarterly, or ttm.",
+ "default": "ttm",
+ },
+ "pit": {
+ "type": "boolean",
+ "description": "Use point-in-time filed-date alignment.",
+ "default": True,
+ },
+ "source": {
+ "type": "string",
+ "enum": list(_VALID_SOURCES),
+ "description": "Fundamental source router.",
+ "default": "auto",
+ },
+ "index": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": "Optional trading-date index to align to.",
+ },
+ },
+ "required": ["symbols", "fields", "start", "end"],
+ }
+
+ def execute(self, **kwargs: Any) -> str:
+ """Validate inputs, call the loader, and return a JSON envelope.
+
+ Args:
+ **kwargs: ``symbols``, ``fields``, ``start``, ``end``, optional
+ ``freq``, ``pit``, ``source``, and ``index``.
+
+ Returns:
+ Strict JSON envelope with serialized field panels or an error.
+ """
+ symbols = kwargs.get("symbols")
+ if not isinstance(symbols, list) or not symbols:
+ return _error("symbols must be a non-empty list of strings")
+ if any(not isinstance(symbol, str) or not symbol.strip() for symbol in symbols):
+ return _error("every symbol must be a non-empty string")
+ symbols = [symbol.strip() for symbol in symbols]
+
+ fields = kwargs.get("fields")
+ if not isinstance(fields, list) or not fields:
+ return _error("fields must be a non-empty list of strings")
+ if any(not isinstance(field, str) or not field.strip() for field in fields):
+ return _error("every field must be a non-empty string")
+ fields = [field.strip() for field in fields]
+
+ start = kwargs.get("start")
+ end = kwargs.get("end")
+ if not isinstance(start, str) or not start.strip():
+ return _error("start must be a non-empty YYYY-MM-DD string")
+ if not isinstance(end, str) or not end.strip():
+ return _error("end must be a non-empty YYYY-MM-DD string")
+
+ freq = kwargs.get("freq", "ttm")
+ if freq not in _VALID_FREQS:
+ return _error(f"freq must be one of {list(_VALID_FREQS)}")
+
+ pit = kwargs.get("pit", True)
+ if not isinstance(pit, bool):
+ return _error("pit must be a boolean")
+
+ source = kwargs.get("source", "auto")
+ if source not in _VALID_SOURCES:
+ return _error(f"source must be one of {list(_VALID_SOURCES)}")
+
+ index_arg = kwargs.get("index")
+ if index_arg is None or isinstance(index_arg, pd.DatetimeIndex):
+ index = index_arg
+ elif isinstance(index_arg, list):
+ index = pd.DatetimeIndex(index_arg)
+ else:
+ return _error("index must be a list of date strings or a DatetimeIndex")
+
+ try:
+ from backtest.loaders.fundamentals_loader import load_fundamental_panel
+
+ panel = load_fundamental_panel(
+ symbols=symbols,
+ fields=fields,
+ start=start.strip(),
+ end=end.strip(),
+ freq=freq,
+ pit=pit,
+ source=source,
+ index=index,
+ )
+ data: dict[str, list[dict[str, Any]]] = {}
+ for field, frame in panel.items():
+ if not isinstance(frame, pd.DataFrame):
+ raise TypeError(
+ f"loader returned {type(frame).__name__} for field {field!r}, expected DataFrame"
+ )
+ data[str(field)] = _frame_records(frame)
+ except Exception as exc: # noqa: BLE001 - tool facade must envelope failures
+ logger.warning("get_fundamentals failed: %s", exc)
+ return _error(str(exc))
+
+ envelope = {
+ "ok": True,
+ "source": source,
+ "freq": freq,
+ "pit": pit,
+ "symbols": symbols,
+ "fields": fields,
+ "data": data,
+ }
+ return json.dumps(envelope, ensure_ascii=False, indent=2, allow_nan=False)
diff --git a/agent/tests/fixtures/sec/aapl_like_companyfacts.json b/agent/tests/fixtures/sec/aapl_like_companyfacts.json
new file mode 100644
index 000000000..5c77739be
--- /dev/null
+++ b/agent/tests/fixtures/sec/aapl_like_companyfacts.json
@@ -0,0 +1,30 @@
+{
+ "facts": {
+ "us-gaap": {
+ "RevenueFromContractWithCustomerExcludingAssessedTax": {
+ "units": {
+ "USD": [
+ {
+ "end": "2023-09-30",
+ "filed": "2023-11-03",
+ "val": 383285000000,
+ "form": "10-K"
+ }
+ ]
+ }
+ },
+ "NetIncomeLoss": {
+ "units": {
+ "USD": [
+ {
+ "end": "2023-09-30",
+ "filed": "2023-11-03",
+ "val": 96995000000,
+ "form": "10-K"
+ }
+ ]
+ }
+ }
+ }
+ }
+}
diff --git a/agent/tests/fixtures/sec/old_standard_companyfacts.json b/agent/tests/fixtures/sec/old_standard_companyfacts.json
new file mode 100644
index 000000000..1f3abe78c
--- /dev/null
+++ b/agent/tests/fixtures/sec/old_standard_companyfacts.json
@@ -0,0 +1,30 @@
+{
+ "facts": {
+ "us-gaap": {
+ "Revenues": {
+ "units": {
+ "USD": [
+ {
+ "end": "2017-12-31",
+ "filed": "2018-02-15",
+ "val": 1250000000,
+ "form": "10-K"
+ }
+ ]
+ }
+ },
+ "NetIncomeLoss": {
+ "units": {
+ "USD": [
+ {
+ "end": "2017-12-31",
+ "filed": "2018-02-15",
+ "val": 120000000,
+ "form": "10-K"
+ }
+ ]
+ }
+ }
+ }
+ }
+}
diff --git a/agent/tests/test_factor_gate_fund_prefix.py b/agent/tests/test_factor_gate_fund_prefix.py
new file mode 100644
index 000000000..8bddf4f71
--- /dev/null
+++ b/agent/tests/test_factor_gate_fund_prefix.py
@@ -0,0 +1,203 @@
+"""Fundamental factor panel gate and runner injection tests."""
+
+from __future__ import annotations
+
+import sys
+import types
+from typing import Any
+
+import pandas as pd
+import pytest
+
+from backtest import runner
+from src.factors.registry import AlphaMeta
+
+
+def _meta(**overrides: Any) -> dict[str, Any]:
+ base = {
+ "id": "test_alpha",
+ "theme": ["quality"],
+ "formula_latex": "x",
+ "columns_required": ["close"],
+ "universe": ["equity_us"],
+ "frequency": ["1d"],
+ "decay_horizon": 1,
+ "min_warmup_bars": 1,
+ }
+ base.update(overrides)
+ return base
+
+
+def test_panel_column_gate_accepts_price_and_fund_prefix() -> None:
+ meta = AlphaMeta(**_meta(columns_required=["close", "fund:roe"]))
+
+ assert meta.columns_required == ["close", "fund:roe"]
+
+
+def test_panel_column_gate_accepts_unknown_fund_field() -> None:
+ meta = AlphaMeta(**_meta(columns_required=["fund:whatever"]))
+
+ assert meta.columns_required == ["fund:whatever"]
+
+
+def test_panel_column_gate_rejects_unknown_non_prefixed_column() -> None:
+ with pytest.raises(ValueError, match="unknown panel column: garbage"):
+ AlphaMeta(**_meta(columns_required=["garbage"]))
+
+
+def test_decay_horizon_accepts_annual_report_scale_window() -> None:
+ meta = AlphaMeta(**_meta(decay_horizon=400))
+
+ assert meta.decay_horizon == 400
+
+
+def test_runner_injects_requested_fundamental_panel(monkeypatch: pytest.MonkeyPatch) -> None:
+ index = pd.bdate_range("2024-01-02", periods=3)
+ panel = {
+ "close": pd.DataFrame(
+ {"AAPL.US": [100.0, 101.0, 102.0]},
+ index=index,
+ )
+ }
+ captured: dict[str, Any] = {}
+
+ def fake_load_fundamental_panel(**kwargs: Any) -> dict[str, pd.DataFrame]:
+ captured.update(kwargs)
+ return {
+ "roe": pd.DataFrame(
+ {"AAPL.US": [0.1, 0.2, 0.3]},
+ index=index,
+ )
+ }
+
+ module = types.ModuleType("backtest.loaders.fundamentals_loader")
+ module.load_fundamental_panel = fake_load_fundamental_panel
+ monkeypatch.setitem(sys.modules, "backtest.loaders.fundamentals_loader", module)
+
+ runner._inject_fundamental_panel(
+ panel,
+ symbols=["AAPL.US"],
+ fund_columns=["fund:roe"],
+ start="2024-01-01",
+ end="2024-01-31",
+ )
+
+ assert captured["symbols"] == ["AAPL.US"]
+ assert captured["fields"] == ["roe"]
+ assert captured["start"] == "2024-01-01"
+ assert captured["end"] == "2024-01-31"
+ assert captured["freq"] == "ttm"
+ assert captured["pit"] is True
+ assert captured["source"] == "auto"
+ assert captured["index"] is index
+ pd.testing.assert_frame_equal(
+ panel["fund:roe"],
+ pd.DataFrame({"AAPL.US": [0.1, 0.2, 0.3]}, index=index),
+ )
+
+
+def test_runner_does_not_import_loader_without_fund_factor(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ index = pd.bdate_range("2024-01-02", periods=2)
+ data_map = {
+ "AAPL.US": pd.DataFrame(
+ {
+ "open": [100.0, 101.0],
+ "high": [101.0, 102.0],
+ "low": [99.0, 100.0],
+ "close": [100.5, 101.5],
+ "volume": [1000, 1100],
+ },
+ index=index,
+ )
+ }
+ calls: list[dict[str, Any]] = []
+
+ def fake_load_fundamental_panel(**kwargs: Any) -> dict[str, pd.DataFrame]:
+ calls.append(kwargs)
+ return {}
+
+ module = types.ModuleType("backtest.loaders.fundamentals_loader")
+ module.load_fundamental_panel = fake_load_fundamental_panel
+ monkeypatch.setitem(sys.modules, "backtest.loaders.fundamentals_loader", module)
+
+ result = runner._maybe_inject_fundamentals_for_factor_panel(
+ data_map,
+ {"selected_factors": [{"columns_required": ["close"]}]},
+ )
+
+ assert result is data_map
+ assert calls == []
+
+
+def test_runner_selected_fund_factor_projects_panel_back_to_data_map(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ index = pd.bdate_range("2024-01-02", periods=2)
+ data_map = {
+ "AAPL.US": pd.DataFrame(
+ {
+ "open": [100.0, 101.0],
+ "high": [101.0, 102.0],
+ "low": [99.0, 100.0],
+ "close": [100.5, 101.5],
+ "volume": [1000, 1100],
+ },
+ index=index,
+ )
+ }
+ captured: dict[str, Any] = {}
+
+ def fake_load_fundamental_panel(**kwargs: Any) -> dict[str, pd.DataFrame]:
+ captured.update(kwargs)
+ return {"roe": pd.DataFrame({"AAPL.US": [0.4, 0.5]}, index=index)}
+
+ module = types.ModuleType("backtest.loaders.fundamentals_loader")
+ module.load_fundamental_panel = fake_load_fundamental_panel
+ monkeypatch.setitem(sys.modules, "backtest.loaders.fundamentals_loader", module)
+
+ result = runner._maybe_inject_fundamentals_for_factor_panel(
+ data_map,
+ {
+ "start_date": "2024-01-01",
+ "end_date": "2024-01-31",
+ "selected_factors": [{"columns_required": ["close", "fund:roe"]}],
+ },
+ )
+
+ assert captured["fields"] == ["roe"]
+ assert captured["index"] is index
+ assert result is not data_map
+ assert result["AAPL.US"]["fund:roe"].tolist() == [0.4, 0.5]
+
+
+def test_runner_injects_nan_fundamental_frame_when_loader_fails(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ index = pd.bdate_range("2024-01-02", periods=2)
+ panel = {
+ "close": pd.DataFrame(
+ {"AAPL.US": [100.0, 101.0], "MSFT.US": [200.0, 201.0]},
+ index=index,
+ )
+ }
+
+ def failing_load_fundamental_panel(**_: Any) -> dict[str, pd.DataFrame]:
+ raise RuntimeError("synthetic provider outage")
+
+ module = types.ModuleType("backtest.loaders.fundamentals_loader")
+ module.load_fundamental_panel = failing_load_fundamental_panel
+ monkeypatch.setitem(sys.modules, "backtest.loaders.fundamentals_loader", module)
+
+ runner._inject_fundamental_panel(
+ panel,
+ symbols=["AAPL.US", "MSFT.US"],
+ fund_columns=["fund:roe"],
+ start="2024-01-01",
+ end="2024-01-31",
+ )
+
+ assert list(panel["fund:roe"].columns) == ["AAPL.US", "MSFT.US"]
+ assert panel["fund:roe"].index is index
+ assert panel["fund:roe"].isna().all().all()
diff --git a/agent/tests/test_fundamental_schema.py b/agent/tests/test_fundamental_schema.py
new file mode 100644
index 000000000..620002051
--- /dev/null
+++ b/agent/tests/test_fundamental_schema.py
@@ -0,0 +1,114 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pandas as pd
+import pytest
+
+from backtest.loaders._fundamental_schema import (
+ DERIVED_FIELDS,
+ RAW_FIELDS,
+ SEC_CONCEPT_MAP,
+ list_supported_fields,
+ resolve_field,
+)
+
+
+EXPECTED_RAW_FIELDS = {
+ "revenue",
+ "cogs",
+ "gross_profit",
+ "operating_income",
+ "net_income",
+ "total_assets",
+ "total_equity",
+ "total_debt",
+ "cash",
+ "shares_diluted",
+ "cfo",
+ "capex",
+}
+
+
+def test_raw_field_schema_and_sec_map_cover_all_raw_fields() -> None:
+ assert set(RAW_FIELDS) == EXPECTED_RAW_FIELDS
+ assert set(SEC_CONCEPT_MAP) == EXPECTED_RAW_FIELDS
+
+ for field, spec in RAW_FIELDS.items():
+ assert spec["statement"]
+ assert spec["description"]
+ assert SEC_CONCEPT_MAP[field], field
+
+
+def test_revenue_concept_priority_keeps_new_standard_first() -> None:
+ assert SEC_CONCEPT_MAP["revenue"][:4] == [
+ "RevenueFromContractWithCustomerExcludingAssessedTax",
+ "RevenueFromContractWithCustomerIncludingAssessedTax",
+ "Revenues",
+ "SalesRevenueNet",
+ ]
+
+
+def test_sec_revenue_fixture_shapes_cover_new_and_old_standard() -> None:
+ fixture_dir = Path(__file__).parent / "fixtures" / "sec"
+ aapl_like = json.loads((fixture_dir / "aapl_like_companyfacts.json").read_text())
+ old_standard = json.loads((fixture_dir / "old_standard_companyfacts.json").read_text())
+
+ aapl_concepts = aapl_like["facts"]["us-gaap"]
+ old_concepts = old_standard["facts"]["us-gaap"]
+
+ assert "RevenueFromContractWithCustomerExcludingAssessedTax" in aapl_concepts
+ assert "Revenues" not in aapl_concepts
+ assert "Revenues" in old_concepts
+ assert "RevenueFromContractWithCustomerExcludingAssessedTax" not in old_concepts
+
+
+def test_derived_formulas_are_numerically_correct() -> None:
+ idx = pd.to_datetime(["2022-12-31", "2023-12-31"])
+ data = {
+ "gross_profit": pd.Series([40.0, 60.0], index=idx),
+ "net_income": pd.Series([10.0, 15.0], index=idx),
+ "total_assets": pd.Series([200.0, 250.0], index=idx),
+ "total_equity": pd.Series([50.0, 75.0], index=idx),
+ "total_debt": pd.Series([100.0, 125.0], index=idx),
+ "cfo": pd.Series([7.0, 12.0], index=idx),
+ }
+
+ expected = {
+ "roe": pd.Series([0.2, 0.2], index=idx),
+ "roa": pd.Series([0.05, 0.06], index=idx),
+ "gross_profitability": pd.Series([0.2, 0.24], index=idx),
+ "accruals": pd.Series([0.015, 0.012], index=idx),
+ "leverage": pd.Series([2.0, 125.0 / 75.0], index=idx),
+ }
+
+ for field, expected_series in expected.items():
+ result = DERIVED_FIELDS[field]["compute"](data)
+ pd.testing.assert_series_equal(result, expected_series, check_names=False)
+
+
+def test_asset_growth_uses_annual_period_over_period_semantics() -> None:
+ idx = pd.to_datetime(["2021-12-31", "2022-12-31", "2023-12-31"])
+ data = {"total_assets": pd.Series([100.0, 120.0, 90.0], index=idx)}
+
+ result = DERIVED_FIELDS["asset_growth"]["compute"](data)
+ expected = pd.Series([float("nan"), 0.2, -0.25], index=idx)
+
+ pd.testing.assert_series_equal(result, expected, check_names=False)
+
+
+def test_resolve_field_and_list_supported_fields() -> None:
+ kind, raw_spec = resolve_field("revenue")
+ assert kind == "raw"
+ assert raw_spec is RAW_FIELDS["revenue"]
+
+ kind, derived_spec = resolve_field("roe")
+ assert kind == "derived"
+ assert derived_spec is DERIVED_FIELDS["roe"]
+
+ supported = list_supported_fields()
+ assert supported == sorted(set(RAW_FIELDS) | set(DERIVED_FIELDS))
+
+ with pytest.raises(ValueError, match="unknown fundamental field"):
+ resolve_field("earnings_yield")
diff --git a/agent/tests/test_fundamentals_pit.py b/agent/tests/test_fundamentals_pit.py
new file mode 100644
index 000000000..c11f54c5f
--- /dev/null
+++ b/agent/tests/test_fundamentals_pit.py
@@ -0,0 +1,328 @@
+from __future__ import annotations
+
+import sys
+from types import ModuleType
+
+import pandas as pd
+import pytest
+
+from backtest.loaders import fundamentals_loader
+
+
+def _install_schema_stub(monkeypatch: pytest.MonkeyPatch) -> None:
+ schema = ModuleType("backtest.loaders._fundamental_schema")
+ schema.SEC_CONCEPT_MAP = {
+ "revenue": [
+ "RevenueFromContractWithCustomerExcludingAssessedTax",
+ "Revenues",
+ ],
+ "net_income": ["NetIncomeLoss"],
+ }
+ schema.DERIVED_FIELDS = {}
+ schema.resolve_field = lambda field: field.removeprefix("fund:")
+ monkeypatch.setitem(sys.modules, "backtest.loaders._fundamental_schema", schema)
+
+
+def _facts(concept_rows: dict[str, list[dict[str, object]]]) -> dict[str, object]:
+ return {
+ "facts": {
+ "us-gaap": {
+ concept: {"units": {"USD": rows}}
+ for concept, rows in concept_rows.items()
+ }
+ }
+ }
+
+
+def _fact_row(
+ end: str,
+ filed: str,
+ value: float,
+ *,
+ form: str = "10-Q",
+ start: str | None = None,
+) -> dict[str, object]:
+ if start is None:
+ # Default to a true-quarter duration so flow-concept frames survive
+ # the loader's start/end span filter.
+ start = (pd.Timestamp(end) - pd.Timedelta(days=91)).strftime("%Y-%m-%d")
+ return {"start": start, "end": end, "filed": filed, "val": value, "form": form}
+
+
+def _patch_sec(
+ monkeypatch: pytest.MonkeyPatch,
+ facts_by_symbol: dict[str, dict[str, object]],
+) -> None:
+ def cik_for(symbol: str) -> str | None:
+ return f"CIK-{symbol}" if symbol in facts_by_symbol else None
+
+ def get_company_facts(cik: str) -> dict[str, object]:
+ symbol = cik.removeprefix("CIK-")
+ return facts_by_symbol[symbol]
+
+ monkeypatch.setattr(fundamentals_loader.sec_edgar_client, "cik_for", cik_for)
+ monkeypatch.setattr(
+ fundamentals_loader.sec_edgar_client,
+ "get_company_facts",
+ get_company_facts,
+ )
+
+
+def test_filed_at_t_plus_30_does_not_appear_before_filed_date(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _install_schema_stub(monkeypatch)
+ _patch_sec(
+ monkeypatch,
+ {
+ "AAA": _facts(
+ {
+ "Revenues": [
+ _fact_row("2023-12-31", "2024-01-30", 100.0),
+ ]
+ }
+ )
+ },
+ )
+ index = pd.date_range("2024-01-01", "2024-02-05", freq="D")
+
+ panel = fundamentals_loader.load_fundamental_panel(
+ ["AAA"],
+ ["revenue"],
+ "2024-01-01",
+ "2024-02-05",
+ freq="quarterly",
+ index=index,
+ )
+
+ revenue = panel["revenue"]["AAA"]
+ assert pd.isna(revenue.loc["2024-01-29"])
+ assert revenue.loc["2024-01-30"] == 100.0
+ assert revenue.loc["2024-02-05"] == 100.0
+
+
+def test_restatement_first_filed_is_pit_and_latest_filed_is_research_mode(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _install_schema_stub(monkeypatch)
+ _patch_sec(
+ monkeypatch,
+ {
+ "AAA": _facts(
+ {
+ "Revenues": [
+ _fact_row("2023-12-31", "2024-01-15", 100.0),
+ _fact_row("2023-12-31", "2024-07-15", 120.0),
+ ]
+ }
+ )
+ },
+ )
+ index = pd.date_range("2024-01-10", "2024-07-20", freq="D")
+
+ pit_panel = fundamentals_loader.load_fundamental_panel(
+ ["AAA"],
+ ["revenue"],
+ "2024-01-10",
+ "2024-07-20",
+ freq="quarterly",
+ pit=True,
+ index=index,
+ )
+ research_panel = fundamentals_loader.load_fundamental_panel(
+ ["AAA"],
+ ["revenue"],
+ "2024-01-10",
+ "2024-07-20",
+ freq="quarterly",
+ pit=False,
+ index=index,
+ )
+
+ assert pit_panel["revenue"].loc["2024-07-20", "AAA"] == 100.0
+ assert research_panel["revenue"].loc["2024-07-14", "AAA"] != 120.0
+ assert research_panel["revenue"].loc["2024-07-15", "AAA"] == 120.0
+
+
+def test_ffill_anchors_on_filed_date_not_period_end(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _install_schema_stub(monkeypatch)
+ _patch_sec(
+ monkeypatch,
+ {
+ "AAA": _facts(
+ {
+ "Revenues": [
+ _fact_row("2024-03-31", "2024-05-01", 77.0),
+ ]
+ }
+ )
+ },
+ )
+ index = pd.to_datetime(["2024-04-15", "2024-05-01"])
+
+ panel = fundamentals_loader.load_fundamental_panel(
+ ["AAA"],
+ ["revenue"],
+ "2024-04-15",
+ "2024-05-01",
+ freq="quarterly",
+ index=index,
+ )
+
+ assert pd.isna(panel["revenue"].loc[pd.Timestamp("2024-04-15"), "AAA"])
+ assert panel["revenue"].loc[pd.Timestamp("2024-05-01"), "AAA"] == 77.0
+
+
+def test_concept_alias_union_resolves_new_standard_revenue_concept(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _install_schema_stub(monkeypatch)
+ _patch_sec(
+ monkeypatch,
+ {
+ "AAA": _facts(
+ {
+ "RevenueFromContractWithCustomerExcludingAssessedTax": [
+ _fact_row("2024-03-31", "2024-04-25", 150.0),
+ ]
+ }
+ )
+ },
+ )
+ index = pd.to_datetime(["2024-04-24", "2024-04-25"])
+
+ panel = fundamentals_loader.load_fundamental_panel(
+ ["AAA"],
+ ["revenue"],
+ "2024-04-24",
+ "2024-04-25",
+ freq="quarterly",
+ index=index,
+ )
+
+ assert pd.isna(panel["revenue"].loc[pd.Timestamp("2024-04-24"), "AAA"])
+ assert panel["revenue"].loc[pd.Timestamp("2024-04-25"), "AAA"] == 150.0
+
+
+def test_panel_shape_aligns_to_given_index_and_missing_cik_is_nan(
+ monkeypatch: pytest.MonkeyPatch,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ _install_schema_stub(monkeypatch)
+ _patch_sec(
+ monkeypatch,
+ {
+ "AAA": _facts(
+ {
+ "Revenues": [
+ _fact_row("2024-03-31", "2024-04-25", 150.0),
+ ]
+ }
+ )
+ },
+ )
+ index = pd.to_datetime(["2024-04-20", "2024-04-25", "2024-04-30"])
+
+ panel = fundamentals_loader.load_fundamental_panel(
+ ["AAA", "MISS"],
+ ["revenue"],
+ "2024-04-01",
+ "2024-04-30",
+ freq="quarterly",
+ index=index,
+ )
+
+ frame = panel["revenue"]
+ assert frame.shape == (3, 2)
+ assert list(frame.index) == list(index)
+ assert list(frame.columns) == ["AAA", "MISS"]
+ assert frame.loc[pd.Timestamp("2024-04-25"), "AAA"] == 150.0
+ assert frame["MISS"].isna().all()
+ assert "No SEC CIK for symbols: MISS" in caplog.text
+
+
+def test_ttm_flow_fields_use_four_quarter_rolling_sum_on_latest_filed_date(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _install_schema_stub(monkeypatch)
+ _patch_sec(
+ monkeypatch,
+ {
+ "AAA": _facts(
+ {
+ "Revenues": [
+ _fact_row("2023-03-31", "2023-04-25", 10.0),
+ _fact_row("2023-06-30", "2023-07-25", 20.0),
+ _fact_row("2023-09-30", "2023-10-25", 30.0),
+ _fact_row("2023-12-31", "2024-01-25", 40.0),
+ ]
+ }
+ )
+ },
+ )
+ index = pd.to_datetime(["2024-01-24", "2024-01-25", "2024-01-26"])
+
+ panel = fundamentals_loader.load_fundamental_panel(
+ ["AAA"],
+ ["revenue"],
+ "2024-01-24",
+ "2024-01-26",
+ index=index,
+ )
+
+ assert pd.isna(panel["revenue"].loc[pd.Timestamp("2024-01-24"), "AAA"])
+ assert panel["revenue"].loc[pd.Timestamp("2024-01-25"), "AAA"] == 100.0
+ assert panel["revenue"].loc[pd.Timestamp("2024-01-26"), "AAA"] == 100.0
+
+
+def test_ytd_and_full_year_frames_are_excluded_and_q4_is_synthesized(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Regression: SEC duration entries mix 3-month, YTD, and full-year frames.
+
+ Live AAPL data produced a ~$1T "TTM revenue" because YTD frames sharing a
+ quarter's end date were rolled into the four-quarter sum. Only true-quarter
+ spans may enter the rolling sum, and the fiscal Q4 (reported only inside
+ the 10-K full-year frame) must be synthesized as FY - (Q1 + Q2 + Q3),
+ anchored on the 10-K filed date.
+ """
+ _install_schema_stub(monkeypatch)
+ _patch_sec(
+ monkeypatch,
+ {
+ "AAPL": _facts(
+ {
+ "Revenues": [
+ # FY2023: three true quarters filed via 10-Qs...
+ _fact_row("2023-03-31", "2023-04-20", 10.0, start="2023-01-01"),
+ _fact_row("2023-06-30", "2023-07-20", 20.0, start="2023-04-01"),
+ # ...plus a YTD frame sharing the Q2 end date (must be ignored)
+ _fact_row("2023-06-30", "2023-07-20", 30.0, start="2023-01-01"),
+ _fact_row("2023-09-30", "2023-10-20", 30.0, start="2023-07-01"),
+ # 10-K: full-year frame only (no explicit Q4) => Q4 = 100-60 = 40
+ _fact_row("2023-12-31", "2024-02-01", 100.0, form="10-K", start="2023-01-01"),
+ ]
+ }
+ )
+ },
+ )
+ index = pd.to_datetime(["2024-01-31", "2024-02-01", "2024-02-02"])
+ panel = fundamentals_loader.load_fundamental_panel(
+ ["AAPL"],
+ ["revenue"],
+ "2024-01-31",
+ "2024-02-02",
+ freq="ttm",
+ pit=True,
+ source="sec",
+ index=index,
+ )
+ series = panel["revenue"]["AAPL"]
+ # Before the 10-K filing there is no complete four-quarter window.
+ assert pd.isna(series.loc[pd.Timestamp("2024-01-31")])
+ # From the 10-K filed date: TTM = 10 + 20 + 30 + synthesized Q4 (40) = 100,
+ # NOT values inflated by the 30.0 YTD frame or the 100.0 full-year frame.
+ assert series.loc[pd.Timestamp("2024-02-01")] == 100.0
+ assert series.loc[pd.Timestamp("2024-02-02")] == 100.0
diff --git a/agent/tests/test_get_fundamentals_tool.py b/agent/tests/test_get_fundamentals_tool.py
new file mode 100644
index 000000000..9fd63e52e
--- /dev/null
+++ b/agent/tests/test_get_fundamentals_tool.py
@@ -0,0 +1,141 @@
+"""Tests for the fundamental data tool facade and first fundamental factors."""
+
+from __future__ import annotations
+
+import json
+import sys
+import types
+
+import numpy as np
+import pandas as pd
+import pytest
+
+from src.tools.get_fundamentals_tool import GetFundamentalsTool
+
+
+def _install_loader(monkeypatch: pytest.MonkeyPatch, func) -> None:
+ module = types.ModuleType("backtest.loaders.fundamentals_loader")
+ module.load_fundamental_panel = func
+ monkeypatch.setitem(sys.modules, "backtest.loaders.fundamentals_loader", module)
+
+
+def test_get_fundamentals_tool_success_envelope(monkeypatch: pytest.MonkeyPatch) -> None:
+ def load_fundamental_panel(**kwargs):
+ assert kwargs["symbols"] == ["AAPL.US", "MSFT.US"]
+ assert kwargs["fields"] == ["roe"]
+ assert kwargs["freq"] == "ttm"
+ assert kwargs["pit"] is True
+ assert kwargs["source"] == "auto"
+ assert kwargs["index"] is None
+ idx = pd.to_datetime(["2026-01-02", "2026-01-03"])
+ return {
+ "roe": pd.DataFrame(
+ {
+ "AAPL.US": [0.21, np.nan],
+ "MSFT.US": [np.inf, 0.18],
+ },
+ index=idx,
+ )
+ }
+
+ _install_loader(monkeypatch, load_fundamental_panel)
+
+ payload = GetFundamentalsTool().execute(
+ symbols=["AAPL.US", "MSFT.US"],
+ fields=["roe"],
+ start="2026-01-01",
+ end="2026-01-31",
+ )
+ parsed = json.loads(payload)
+
+ assert parsed["ok"] is True
+ assert parsed["source"] == "auto"
+ assert parsed["freq"] == "ttm"
+ assert parsed["pit"] is True
+ assert parsed["symbols"] == ["AAPL.US", "MSFT.US"]
+ assert parsed["fields"] == ["roe"]
+ assert parsed["data"]["roe"] == [
+ {"date": "2026-01-02T00:00:00", "AAPL.US": 0.21, "MSFT.US": None},
+ {"date": "2026-01-03T00:00:00", "AAPL.US": None, "MSFT.US": 0.18},
+ ]
+
+
+def test_get_fundamentals_tool_loader_error_envelope(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ def load_fundamental_panel(**kwargs):
+ raise RuntimeError("fixture loader exploded")
+
+ _install_loader(monkeypatch, load_fundamental_panel)
+
+ payload = GetFundamentalsTool().execute(
+ symbols=["AAPL.US"],
+ fields=["roe"],
+ start="2026-01-01",
+ end="2026-01-31",
+ )
+ parsed = json.loads(payload)
+
+ assert parsed["ok"] is False
+ assert "fixture loader exploded" in parsed["error"]
+
+
+def _panel(values: list[list[float]], columns: list[str] | None = None) -> pd.DataFrame:
+ return pd.DataFrame(
+ values,
+ index=pd.to_datetime(["2026-01-02", "2026-01-03"]),
+ columns=columns or ["A", "B", "C"],
+ dtype=float,
+ )
+
+
+def _assert_row_zscore_properties(result: pd.DataFrame) -> None:
+ assert np.allclose(result.mean(axis=1), 0.0, atol=1e-12)
+ assert np.allclose(result.std(axis=1, ddof=1), 1.0, atol=1e-12)
+
+
+def test_fund_roe_compute_cross_sectional_zscore() -> None:
+ from src.factors.zoo.fundamental.roe import compute
+
+ result = compute({"fund:roe": _panel([[1.0, 2.0, 3.0], [2.0, 4.0, 6.0]])})
+
+ _assert_row_zscore_properties(result)
+ assert result.iloc[0].tolist() == [-1.0, 0.0, 1.0]
+
+
+def test_fund_gross_profitability_compute_cross_sectional_zscore() -> None:
+ from src.factors.zoo.fundamental.gross_profitability import compute
+
+ result = compute(
+ {"fund:gross_profitability": _panel([[3.0, 6.0, 9.0], [4.0, 8.0, 12.0]])}
+ )
+
+ _assert_row_zscore_properties(result)
+ assert result.iloc[1].tolist() == [-1.0, 0.0, 1.0]
+
+
+def test_fund_asset_growth_compute_is_inverted_zscore() -> None:
+ from src.factors.zoo.fundamental.asset_growth import compute
+
+ result = compute(
+ {"fund:asset_growth": _panel([[0.01, 0.02, 0.03], [0.10, 0.20, 0.30]])}
+ )
+
+ _assert_row_zscore_properties(result)
+ assert np.allclose(result.iloc[0], [1.0, 0.0, -1.0], atol=1e-12)
+
+
+def test_fund_earnings_yield_compute_hybrid_zscore_and_safe_division() -> None:
+ from src.factors.zoo.fundamental.earnings_yield import compute
+
+ result = compute(
+ {
+ "close": _panel([[10.0, 10.0, 10.0], [0.0, 10.0, 10.0]]),
+ "fund:net_income": _panel([[10.0, 20.0, 30.0], [5.0, 20.0, 30.0]]),
+ "fund:shares_diluted": _panel([[10.0, 10.0, 10.0], [10.0, 10.0, 10.0]]),
+ }
+ )
+
+ _assert_row_zscore_properties(result)
+ assert np.allclose(result.iloc[0], [-1.0, 0.0, 1.0], atol=1e-12)
+ assert np.isnan(result.loc[pd.Timestamp("2026-01-03"), "A"])