MacroLens / code /methods /llm.py
itouchz's picture
Upload methods/ (18-method baseline panel implementations)
02412f8 verified
Raw
History Blame Contribute Delete
50.9 kB
"""Frontier-LLM methods (family 7 ZS) — OpenAI-compatible HTTP rewrite.
Three classes, one per HF model id, all sharing a single OpenAI-compatible
HTTP client (talking to a ``vllm serve``-hosted endpoint) that is
**dependency-injected** by the runner. One engine per HF model id is
constructed once and reused across method instances. The classes
themselves own only the task-specific prompt templates and response
parsers.
| Class | name | tasks | config_class |
|--------------|----------------|--------------------|--------------------|
| LlamaScout | llama_scout | T1..T7 | LlamaScoutConfig |
| Gemma4 | gemma4 | T1..T7 | Gemma4Config |
| Qwen35 | qwen35 | T1..T7 | Qwen35Config |
Per-task ``predict`` output (per plan §9 method × task matrix):
T1 : (N, horizon) np.ndarray float32 — close trajectory
T2 : (N,) np.ndarray float64 — predicted equity_value
T3 : pd.DataFrame [ticker, fiscal_year, field, pred] long-form
T4 : (N,) np.ndarray float32 — predicted return_pct
T5 : (N,) np.ndarray float64 — predicted equity_value
T6 : pd.DataFrame [ticker, fiscal_year, field, pred] long-form
T7 : pd.DataFrame [address, pred_rent, pred_price]
Hard rules (enforced by ``tests/test_layer_isolation.py``):
- Zero IO of benchmark data.
- Zero eval imports.
- Zero ``meta`` consumption.
- Engine NOT instantiated in ``__init__``; the runner injects it.
Engine protocol (see :mod:`methods._openai_engine`):
- ``engine.chat_complete(messages, max_tokens, temperature, top_p) -> str``
- ``engine.chat_complete_batch(batched_messages, max_tokens, ...) -> list[str]``
Chat-template formatting is no longer applied client-side: ``vllm serve``
applies the model's chat template server-side from the structured
``messages`` payload, so this module passes
``[{"role": "user", "content": prompt}]`` directly.
Dry-run mode (``config.dry_run=True`` AND ``engine is None``): a
:class:`methods._openai_engine.DryRunEngine` is instantiated internally so
``predict`` can be exercised without a live vLLM endpoint (the path the
``test_method_contract`` and sanity-matrix smoke tests use).
Prompt templates and response parsers are lifted **verbatim** from
``baselines/llm_baseline.py`` (the legacy code path); the only changes
are removing benchmark IO, canonical-index joins, and result packaging
(those concerns moved to ``dataloader/`` and ``eval.py``).
"""
from __future__ import annotations
import json
import logging
import re
from typing import Any, ClassVar
import numpy as np
import pandas as pd
logger = logging.getLogger(__name__)
from ._config import (
Gemma4Config,
LlamaScoutConfig,
LLMConfig,
Qwen35Config,
)
from ._openai_engine import DryRunEngine
from ._registry import register
from .base import Method, _HFSaveMixin
# ── Task-set covered by every LLM in this file ──────────────────────────
_LLM_TASKS = frozenset({"T1", "T2", "T3", "T4", "T5", "T6", "T7"})
# ── Lifted-verbatim helpers from baselines/llm_baseline.py ──────────────
_THINK_RE = re.compile(r"<think>.*?</think>", re.DOTALL)
_NUM_PATTERNS = [
# Keyword-prefixed: "Prediction: $1.23 billion"
r"\*?\*?(?:final\s+answer|final\s+prediction|prediction|forecast|estimate|"
r"answer|price|value|market\s+cap(?:italization)?|return|equity|valuation)"
r"[:\s]*\$?\s*([-\d,]+(?:\.\d+)?(?:[eE][-+]?\d+)?)\s*"
r"(billion|million|thousand|trillion)?",
# Number with magnitude suffix (spelled-out only — 'B'/'M' alone are too ambiguous):
r"\$?\s*([-\d,]+(?:\.\d+)?(?:[eE][-+]?\d+)?)\s+(billion|million|thousand|trillion)\b",
# Fallback: any plain number with optional $.
r"\$?([-\d,]+(?:\.\d+)?(?:[eE][-+]?\d+)?)",
]
_MAGNITUDE_MAP = {
"thousand": 1e3,
"million": 1e6,
"billion": 1e9,
"trillion": 1e12,
}
def _strip_thinking(response: str) -> str:
"""Remove ``<think>...</think>`` reasoning blocks from a response.
Preserves the legacy behaviour: also handles unclosed ``<think>``
fragments by taking the trailing portion.
"""
response = _THINK_RE.sub("", response).strip()
m = re.search(r"<think>(.*)", response, flags=re.DOTALL)
if m and "</think>" not in response:
response = m.group(1).strip()
return response
def _extract_json_object(response: str) -> dict | None:
"""Extract a structured ``{field: value}`` map from an LLM response.
Two paths:
1. **JSON object**: legacy support for replies like
``{"Revenues": 1000000, "Assets": 5000000}``. Slices from the first
``{`` to the last ``}`` and tries ``json.loads``.
2. **Plain-text key/value**: line-oriented format ``<Field>: <number>``
which is what current prompts request. Each line is matched by
regex; numbers may use ``$``, commas, scientific notation. This is
the natural LLM output mode and avoids JSON parse failures.
Returns ``None`` if neither path yields any field/value pair.
"""
if not response:
return None
# Path 1: legacy JSON object.
start = response.find("{")
end = response.rfind("}")
if start >= 0 and end > start:
try:
j = json.loads(response[start:end + 1])
if isinstance(j, dict):
return j
except json.JSONDecodeError:
pass
depth = 0
for i in range(start, len(response)):
ch = response[i]
if ch == "{":
depth += 1
elif ch == "}":
depth -= 1
if depth == 0:
try:
j = json.loads(response[start:i + 1])
if isinstance(j, dict):
return j
except json.JSONDecodeError:
break
# Path 2: plain-text "<Field>: <number>" lines (one or many).
out: dict[str, float] = {}
line_re = re.compile(
r"\*?\*?\s*([A-Za-z][A-Za-z0-9_]*)\s*:\s*\$?\s*"
r"(-?\d[\d,]*(?:\.\d+)?(?:[eE][-+]?\d+)?)"
)
for m in line_re.finditer(response):
field = m.group(1)
num_str = m.group(2).replace(",", "")
try:
out[field] = float(num_str)
except ValueError:
continue
return out or None
def _parse_number(text: str) -> float | None:
"""Extract the first plausible number from an LLM response.
Strips ``<think>...</think>`` blocks, list-numbered prefixes
(``1. ``, ``2. ``), and CoT step markers before number extraction.
Honors magnitude suffixes (B / billion, M / million, K / thousand,
T / trillion). Returns ``None`` only when no number is found.
"""
if not text:
return None
# Strip CoT thinking blocks first
text = _strip_thinking(text)
# Drop "Thinking Process:" / "Reasoning:" / "Step N:" prefix sections by
# taking the trailing portion after a "Final answer" / "Therefore" cue.
for cue in ["Final answer:", "Final Answer:", "FINAL ANSWER:",
"Therefore,", "So, ", "Answer:", "answer:"]:
idx = text.rfind(cue)
if idx >= 0:
text = text[idx + len(cue):]
break
# Strip list-numbered prefixes like "1. " at start of lines so the
# parser doesn't pick up step indices instead of values.
text = re.sub(r"(?m)^\s*\d+\.\s+", "", text)
for pat in _NUM_PATTERNS:
match = re.search(pat, text, re.IGNORECASE)
if match:
num_str = match.group(1).replace(",", "")
mag_str = (
match.group(2) if match.lastindex and match.lastindex >= 2
else None
)
try:
v = float(num_str)
except ValueError:
continue
if mag_str:
v *= _MAGNITUDE_MAP.get(mag_str.lower(), 1.0)
return v
return None
def _parse_horizon_list(response: str, horizon: int) -> np.ndarray | None:
"""Extract a list of floats representing a forecast trajectory.
Strategy: try a bracketed JSON-array slice first; otherwise extract
every numeric token from the whole response. Plain-text replies like
``"123.45, 124.10, 125.00, ..."`` or ``"123.45\\n124.10\\n..."`` parse
just as well as JSON.
Returns a ``(horizon,)`` float32 ndarray, padding with the last value
when the parsed list is shorter and truncating when longer. Returns
``None`` only when zero numeric tokens are found.
"""
if not response:
return None
# Strip CoT thinking blocks (this is a known issue for chain-of-thought
# models; the safe pattern.) Do NOT strip "N. " line prefixes — that
# regex was too aggressive and dropped real digits in some outputs.
response = _strip_thinking(response)
# Prefer a bracketed slice if present (still works for legacy JSON output).
start = response.find("[")
end = response.rfind("]")
candidate = response[start : end + 1] if start >= 0 and end > start else response
parsed: list[Any] | None = None
if start >= 0 and end > start:
try:
j = json.loads(candidate)
if isinstance(j, list):
parsed = j
except json.JSONDecodeError:
parsed = None
if parsed is None:
# Plain-text fallback: extract every signed/decimal/scientific number.
tokens = re.findall(r"[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?", candidate)
if not tokens:
return None
try:
parsed = [float(t) for t in tokens]
except ValueError:
return None
vals: list[float] = []
for v in parsed:
try:
f = float(v)
except (TypeError, ValueError):
continue
if not (f != f): # not NaN
vals.append(f)
if not vals:
return None
if len(vals) >= horizon:
out = np.asarray(vals[:horizon], dtype=np.float32)
else:
pad = [vals[-1]] * (horizon - len(vals))
out = np.asarray(vals + pad, dtype=np.float32)
return out
def _safe_float(v: Any, default: float = 0.0) -> float:
"""Coerce ``v`` to float; fall back to ``default`` on missing / non-numeric."""
if v is None:
return default
if isinstance(v, (int, float)) and not (isinstance(v, float) and np.isnan(v)):
return float(v)
try:
if pd.isna(v): # type: ignore[arg-type]
return default
except (TypeError, ValueError):
pass
try:
return float(v)
except (TypeError, ValueError):
return default
def _format_macro_snapshot(row: pd.Series) -> str:
"""Render the at-anchor macro snapshot for T2/T5 prompts.
Picks four widely-recognised series whose level is itself meaningful
(rates / vol / index level) so the LLM does not need to derive a YoY
change from a single observation. Lines are silently dropped when a
column is missing or NaN, so the prompt stays compact when the macro
join failed.
"""
items: list[str] = []
series = {
"10-Year Treasury Yield (DGS10, %)": row.get("fred_DGS10"),
"Fed Funds Rate (FEDFUNDS, %)": row.get("fred_FEDFUNDS"),
"VIX (VIXCLS, equity vol)": row.get("fred_VIXCLS"),
"CPI Headline Level (CPIAUCSL)": row.get("fred_CPIAUCSL"),
}
for label, val in series.items():
if val is None:
continue
try:
if pd.isna(val):
continue
items.append(f"{label}: {float(val):,.2f}")
except (TypeError, ValueError):
continue
if not items:
return "Macro snapshot: not available."
return "Macro snapshot at anchor date:\n" + "\n".join(items)
def _find_close_idx_from_array(X: np.ndarray) -> int:
"""Heuristic close-column finder when feature_names are unavailable.
Matches ``methods.llm.FrontierLLM`` from the legacy file: pick a
feature column whose values are all-positive across observed
timesteps and whose median magnitude is in the price-shaped range
[1, 5000]; tie-break by closeness to the median magnitude in
log-space. Falls back to column 0.
"""
if X.ndim != 3 or X.shape[2] == 0:
return 0
samples = X.reshape(-1, X.shape[2])
pos_mask = (samples >= 0).all(axis=0)
if not pos_mask.any():
return 0
medians = np.median(np.abs(samples), axis=0)
candidates = np.where(pos_mask & (medians >= 1.0) & (medians <= 5000.0))[0]
if len(candidates) == 0:
return 0
cand_meds = medians[candidates]
log_cand = np.log10(cand_meds + 1e-9)
target = np.median(log_cand)
return int(candidates[np.argmin(np.abs(log_cand - target))])
# ── Default XBRL field panel for T3/T6 when y_train is unavailable ──────
_DEFAULT_T3_T6_FIELDS = (
# MUST match dataloader.load._T3_DENSE_FIELDS exactly (the eval-side
# canonical field set). Field-name drift between predict-side prompts
# and eval-side joins produces silent 0% match rates.
"Revenues",
"NetIncomeLoss",
"Assets",
"Liabilities",
"StockholdersEquity",
"OperatingIncomeLoss",
"CashAndCashEquivalentsAtCarryingValue",
"PropertyPlantAndEquipmentNet",
"LongTermDebt",
"ResearchAndDevelopmentExpense",
"NetCashProvidedByUsedInOperatingActivities",
)
# LLMs frequently emit common-English variants of XBRL canonical names;
# accept these aliases at parse time so predictions are usable instead of
# being forced to predict_failed on every field-name drift.
_T3_T6_FIELD_ALIASES: dict[str, list[str]] = {
"Revenues": ["revenues","revenue","totalrevenue","totalrevenues","sales","totalsales","netrevenue","netrevenues","stmt_revenue"],
"NetIncomeLoss": ["netincomeloss","netincome","netearnings","netprofit","income","earnings","stmt_net_income"],
"Assets": ["assets","totalassets","stmt_total_assets"],
"Liabilities": ["liabilities","totalliabilities","stmt_total_liabilities"],
"StockholdersEquity": ["stockholdersequity","totalstockholdersequity","shareholdersequity","totalshareholdersequity","totalequity","equity","stmt_total_equity","bookvalue"],
"OperatingIncomeLoss": ["operatingincomeloss","operatingincome","operatingprofit","operatingearnings","ebit","stmt_operating_income"],
"CashAndCashEquivalentsAtCarryingValue": ["cashandcashequivalentsatcarryingvalue","cashandcashequivalents","cashequivalents","cash","stmt_cash","cashandshortterminvestments"],
"PropertyPlantAndEquipmentNet": ["propertyplantandequipmentnet","propertyplantandequipment","ppe","netppe","ppenet","fixedassets","stmt_ppe_net"],
"LongTermDebt": ["longtermdebt","longtermborrowings","noncurrentdebt","longtermliabilities","stmt_lt_debt"],
"ResearchAndDevelopmentExpense": ["researchanddevelopmentexpense","researchanddevelopment","rd","rnd","rdexpense","rndexpense"],
"NetCashProvidedByUsedInOperatingActivities": ["netcashprovidedbyusedinoperatingactivities","operatingcashflow","cashfromoperations","operatingcash","netcashoperating","stmt_operating_cashflow"],
}
def _resolve_canonical_field(parsed: dict | None, canon_field: str) -> Any:
"""Resolve ``canon_field`` from a parsed LLM dict using a canonical-name
alias map. Lookup is case- and underscore-insensitive. Returns ``None``
when ``parsed`` is None or no alias matches.
"""
if parsed is None:
return None
aliases = _T3_T6_FIELD_ALIASES.get(canon_field, [canon_field.lower()])
norm = {
str(k).lower().replace(" ", "").replace("_", ""): v
for k, v in parsed.items()
}
for alias in [canon_field.lower(), *aliases]:
key = alias.replace(" ", "").replace("_", "")
if key in norm:
return norm[key]
return None
# ── Shared base class ───────────────────────────────────────────────────
class _LLMBase(_HFSaveMixin, Method):
"""Shared scaffolding for the four frontier-LLM methods.
Subclasses set ``name``, ``family``, ``tasks``, and ``_config_class``
via the ``@register`` decorator. The engine — an
:class:`methods._openai_engine.OpenAIChatEngine` exposing
``chat_complete`` / ``chat_complete_batch`` — is **injected** by the
runner via the ``engine=`` ctor kwarg.
When ``engine is None`` AND ``config.dry_run=True``, a
:class:`methods._openai_engine.DryRunEngine` is instantiated lazily on
first ``predict`` so smoke tests can run without a live HTTP endpoint.
Chat-template formatting is delegated to the vLLM server (it sees
structured ``messages`` and applies the model's tokenizer chat
template before generation), so this class no longer needs a
tokenizer kwarg or a client-side ``apply_chat_template`` step.
"""
family: ClassVar[str] = "llm"
tasks: ClassVar[frozenset[str]] = _LLM_TASKS
schema_version: ClassVar[int] = 1
_config_class: ClassVar[type[LLMConfig]] = LLMConfig
def __init__(
self,
*,
task: str,
config: LLMConfig | None = None,
engine: Any = None,
**kwargs: Any,
) -> None:
if task not in self.tasks:
raise ValueError(
f"{type(self).__name__} does not support task {task!r}; "
f"supported: {sorted(self.tasks)}"
)
self.task: str = task
self.config: LLMConfig = config or self._config_class(**kwargs)
# Runner-managed shared resource. One OpenAIChatEngine per HF
# model id; many method instances share it.
self.engine: Any = engine
# Populated by ``fit``: in-context examples (when in_context_k>0)
# and the long-form fitted-fields set for T3/T6 (per plan §7b.1).
self._y_train: Any = None
self._X_train: Any = None
self._fitted_fields_per_ticker: dict[str, list[str]] = {}
self._fitted_fields_global: list[str] = []
# Populated after each predict call.
self.last_predict_meta: dict[str, Any] = {}
# Resolved at fit time when the runner provides feature_names via
# ``set_feature_names``; T1 falls back to the magnitude heuristic.
self._t1_close_idx: int | None = None
self._t1_horizon: int | None = None
# ── default_config plumbed by @register if absent ─────────────────
@classmethod
def default_config(cls) -> LLMConfig:
return cls._config_class()
# ── Optional setter mirroring the TSFM pattern ────────────────────
def set_feature_names(self, feature_names: list[str]) -> None:
"""T1 close-column resolver. Optional; runner may or may not call."""
if "close" in feature_names:
self._t1_close_idx = feature_names.index("close")
else:
self._t1_close_idx = None # fall back to heuristic at predict time
# ── fit: zero-shot, but record the fitted field set for T3/T6 ────
def fit(self, X: Any, y: Any, *, seed: int = 42) -> "_LLMBase":
"""Zero-shot fit.
For T3/T6 we record the unique field set per ticker (and global)
from ``y`` so ``predict`` emits one row per ``(ticker, fiscal_year,
field)`` for every fitted field — matching the plan's per-task
long-form contract.
For T1 we capture the horizon from ``y.shape[1]`` so the prompt
wording and the output tile width are consistent.
For ``config.in_context_k > 0`` we additionally retain ``X`` and
``y`` so ``predict`` can build in-context examples (currently a
thin handle; the IC builder is task-specific and can be added
without breaking the API).
"""
if self.config.in_context_k > 0:
self._X_train = X
self._y_train = y
if self.task == "T1":
if isinstance(y, np.ndarray) and y.ndim == 2:
self._t1_horizon = int(y.shape[1])
if self.task in ("T3", "T6"):
if isinstance(y, pd.DataFrame) and not y.empty and "field" in y.columns:
# Per-ticker fitted fields
self._fitted_fields_per_ticker = {
str(t): sorted(grp["field"].astype(str).unique().tolist())
for t, grp in y.groupby("ticker", sort=False)
}
# Global fitted-field set (used as fallback when a test
# ticker is unseen in training)
self._fitted_fields_global = sorted(
y["field"].astype(str).unique().tolist()
)
return self
# ── predict: dispatch on self.task ───────────────────────────────
def predict(self, X: Any) -> np.ndarray | pd.DataFrame:
"""Emit predictions for ``X``. Shape is per the plan §9 matrix."""
# Engine-availability check: dry_run lets the smoke test pass
# without a real vLLM engine.
if self.engine is None and not self.config.dry_run:
raise RuntimeError(
f"{type(self).__name__}.predict: no engine was injected and "
f"config.dry_run=False; the runner must inject a vLLM engine "
f"(or set dry_run=True for CI smoke tests)."
)
if self.task == "T1":
return self._predict_t1(X)
if self.task in ("T2", "T5"):
return self._predict_t2_t5(X, task=self.task)
if self.task in ("T3", "T6"):
return self._predict_t3_t6(X, task=self.task)
if self.task == "T4":
return self._predict_t4(X)
if self.task == "T7":
return self._predict_t7(X)
raise ValueError(f"Unknown task: {self.task!r}") # pragma: no cover
# ── HF save/load hooks (manifest only — model weights live in HF cache) ─
def _hf_save(self, path: Any) -> None: # noqa: ARG002 -- manifest-only
"""No-op: frontier model weights are too large; the HF cache is
the SSOT. ``manifest.json`` written by the mixin records the
``model_id`` so ``load`` can re-use the same shared engine.
"""
return None
def _hf_load(self, path: Any) -> None: # noqa: ARG002 -- manifest-only
"""No-op counterpart to :meth:`_hf_save`. The runner is
responsible for re-injecting the engine after construction.
"""
return None
# ── Engine call (OpenAI-compatible HTTP, batched via thread-pool) ─
def _ensure_engine(self) -> Any:
"""Return the injected engine, instantiating a DryRunEngine when
``engine is None`` and ``config.dry_run=True``.
"""
if self.engine is not None:
return self.engine
if self.config.dry_run:
self.engine = DryRunEngine(horizon=int(self._t1_horizon or 21))
return self.engine
raise RuntimeError(
f"{type(self).__name__}.predict: no engine was injected and "
f"config.dry_run=False; the runner must inject an "
f"OpenAIChatEngine (or set dry_run=True for CI smoke tests)."
)
def _call_batch(
self,
prompts: list[str],
*,
max_tokens: int | None = None,
) -> list[str]:
"""Batched LLM inference via the injected OpenAI-compatible engine.
Each prompt becomes a one-message ``[{"role": "user", ...}]``
payload. ``vllm serve`` applies the model's chat template
server-side, so no client-side tokenizer is needed.
"""
if not prompts:
return []
engine = self._ensure_engine()
# Qwen3.5 has thinking enabled by default in the chat template;
# the upstream Qwen team document /no_think as the in-prompt switch
# to disable it for direct-answer generation. Honor LLMConfig.enable_thinking=False.
prefix = ""
if not bool(getattr(self.config, "enable_thinking", False)):
mid = str(getattr(self.config, "model_id", "") or "")
if "Qwen3" in mid or "qwen3" in mid:
prefix = "/no_think\n"
batched_messages = [
[{"role": "user", "content": prefix + p}] for p in prompts
]
responses = engine.chat_complete_batch(
batched_messages,
max_tokens=int(max_tokens or self.config.max_tokens),
temperature=float(self.config.temperature),
top_p=1.0,
)
return [_strip_thinking(str(r)) for r in responses]
# ── T1: TSF (true horizon-list trajectory forecast) ────────────────
def _predict_t1(self, X: np.ndarray) -> np.ndarray:
if not isinstance(X, np.ndarray) or X.ndim != 3:
raise ValueError(
f"T1 X must be (N, lookback, F) np.ndarray, got "
f"shape={getattr(X, 'shape', None)} type={type(X).__name__}"
)
n, lookback, _ = X.shape
horizon = int(self._t1_horizon or 21)
if n == 0:
self.last_predict_meta = {
"task": "T1", "n_attempted": 0, "n_parse_errors": 0,
}
return np.zeros((0, horizon), dtype=np.float32)
close_idx = (
self._t1_close_idx
if self._t1_close_idx is not None
else _find_close_idx_from_array(X)
)
prompts: list[str] = []
for i in range(n):
close_series = X[i, :, close_idx]
last_close = float(close_series[-1])
mean_close = float(np.mean(close_series))
std_close = float(np.std(close_series))
denom = max(float(close_series[0]), 0.01)
trend = float((close_series[-1] - close_series[0]) / denom * 100)
prompts.append(
f"You are a quantitative analyst. Predict the daily closing "
f"prices of the stock for each of the next {horizon} trading "
f"days, given:\n"
f"- Current close: ${last_close:.2f}\n"
f"- Past {lookback} closes: "
f"mean=${mean_close:.2f}, std=${std_close:.2f}, "
f"trend={trend:+.1f}%\n\n"
f"Reply with {horizon} closing prices in chronological order, "
f"one per line, dollars only (no $ sign, no commentary)."
)
# Trajectory output requires more tokens than a single scalar: budget
# ~8 tokens per horizon step plus brackets/separators.
max_tokens = max(64, 12 * horizon + 16)
responses = self._call_batch(prompts, max_tokens=max_tokens)
preds = np.full((n, horizon), np.nan, dtype=np.float32)
unparsed_idx: list[int] = []
for i, resp in enumerate(responses):
traj = _parse_horizon_list(resp, horizon)
if traj is None:
unparsed_idx.append(i)
continue
preds[i, :] = traj
# Re-prompt unparseable rows ONCE with stricter format guidance.
if unparsed_idx:
retry_prompts = [
prompts[i]
+ f"\n\nIMPORTANT: Reply with EXACTLY {horizon} numbers "
"separated by commas or newlines, no other text."
for i in unparsed_idx
]
retries = self._call_batch(retry_prompts, max_tokens=max_tokens)
still_unparsed = []
for k, i in enumerate(unparsed_idx):
traj = _parse_horizon_list(retries[k], horizon)
if traj is None:
still_unparsed.append(i)
else:
preds[i, :] = traj
unparsed_idx = still_unparsed
if unparsed_idx:
logger.warning(
"%s predict: %d/%d rows unparseable after retry; "
"emitting NaN — eval-side fillna will substitute 0.",
type(self).__name__, len(unparsed_idx), n,
)
self.last_predict_meta = {
"task": "T1", "n_attempted": int(n),
"n_parse_errors_after_retry": 0,
"horizon": horizon, "close_idx": int(close_idx),
}
return preds
# ── T2 / T5: scalar valuation ────────────────────────────────────
def _predict_t2_t5(self, X: pd.DataFrame, *, task: str) -> np.ndarray:
if not isinstance(X, pd.DataFrame):
raise ValueError(
f"{task} X must be a DataFrame, got type={type(X).__name__}"
)
n = len(X)
if n == 0:
self.last_predict_meta = {
"task": task, "n_attempted": 0, "n_parse_errors": 0,
}
return np.zeros(0, dtype=np.float64)
prompts: list[str] = []
if task == "T2":
for _, row in X.iterrows():
sector = row.get("sector", "Unknown")
revenue = row.get("stmt_revenue", 0)
net_income = row.get("stmt_net_income", 0)
total_assets = row.get("stmt_total_assets", 0)
employees = row.get("fullTimeEmployees", "N/A")
macro_str = _format_macro_snapshot(row)
# NB: derived_pe stripped at build time to avoid the
# market-cap-leakage path (T2/T5 leakage fix).
prompts.append(
f"You are a financial analyst. Estimate the total equity "
f"market capitalization of this company.\n\n"
f"Sector: {sector}\n"
f"Revenue: ${_safe_float(revenue):,.0f}\n"
f"Net Income: ${_safe_float(net_income):,.0f}\n"
f"Total Assets: ${_safe_float(total_assets):,.0f}\n"
f"Employees: {employees}\n"
f"{macro_str}\n\n"
f"Reply with ONLY a single number: the estimated market cap "
f"in dollars."
)
else: # T5 — Val-Priv
stmt_cols = [c for c in X.columns if c.startswith("stmt_")]
for _, row in X.iterrows():
sector = row.get("sector", "Unknown")
industry = row.get("industry", "Unknown")
stmt_items = []
for c in stmt_cols:
val = row.get(c)
if pd.notna(val):
try:
stmt_items.append(f"{c}: ${float(val):,.0f}")
except (TypeError, ValueError):
continue
stmt_str = (
"\n".join(stmt_items) if stmt_items
else "No financial statement data available"
)
macro_str = _format_macro_snapshot(row)
prompts.append(
f"You are a private equity analyst. Given ONLY financial "
f"statement data (no market price), estimate the market "
f"capitalization of this company.\n\n"
f"Sector: {sector}\n"
f"Industry: {industry}\n"
f"{stmt_str}\n"
f"{macro_str}\n\n"
f"Reply with ONLY a single number: the estimated market cap "
f"in dollars."
)
responses = self._call_batch(prompts, max_tokens=64)
preds = np.full(n, np.nan, dtype=np.float64)
unparsed_idx: list[int] = []
for i, resp in enumerate(responses):
v = _parse_number(resp)
if v is None or v <= 0:
unparsed_idx.append(i)
continue
preds[i] = float(v)
# Retry once with stricter format guidance.
if unparsed_idx:
retry_prompts = [
prompts[i] + "\n\nIMPORTANT: Reply with ONLY a single positive "
"number (no units, no commas, no currency symbol, no other text)."
for i in unparsed_idx
]
retries = self._call_batch(retry_prompts, max_tokens=64)
still: list[int] = []
for k, i in enumerate(unparsed_idx):
v = _parse_number(retries[k])
if v is None or v <= 0:
still.append(i)
else:
preds[i] = float(v)
unparsed_idx = still
if unparsed_idx:
logger.warning(
"%s predict: %d/%d rows unparseable after retry; "
"emitting NaN — eval-side fillna will substitute 0.",
type(self).__name__, len(unparsed_idx), n,
)
self.last_predict_meta = {
"task": task, "n_attempted": int(n),
"n_parse_errors_after_retry": 0,
}
return preds
# ── T3 / T6: per-(ticker, fiscal_year) XBRL field generation ────
def _predict_t3_t6(self, X: pd.DataFrame, *, task: str) -> pd.DataFrame:
if not isinstance(X, pd.DataFrame):
raise ValueError(
f"{task} X must be a DataFrame, got type={type(X).__name__}"
)
n = len(X)
if n == 0:
self.last_predict_meta = {
"task": task, "n_attempted": 0, "n_parse_errors": 0,
}
return pd.DataFrame(
columns=["ticker", "fiscal_year", "field", "pred"]
)
# Field set: per-ticker if fitted, else global, else default panel.
global_fields = (
self._fitted_fields_global
or list(_DEFAULT_T3_T6_FIELDS)
)
prompts: list[str] = []
meta_rows: list[tuple[str, Any, list[str]]] = []
for _, row in X.iterrows():
ticker = str(row.get("ticker", "?"))
fy = row.get("fiscal_year", None)
fields_for_row = (
self._fitted_fields_per_ticker.get(ticker)
or global_fields
)
fields_str = ", ".join(fields_for_row)
example_key = fields_for_row[0] if fields_for_row else "Revenues"
meta_rows.append((ticker, fy, fields_for_row))
if task == "T3":
sector = row.get("sector", "Unknown")
revenue = _safe_float(row.get("stmt_revenue", 0))
net_income = _safe_float(row.get("stmt_net_income", 0))
total_assets = _safe_float(row.get("stmt_total_assets", 0))
total_equity = _safe_float(row.get("stmt_total_equity", 0))
prompts.append(
f"You are a financial analyst. Given company fundamentals, "
f"predict each of the following financial statement fields.\n\n"
f"Company: {ticker} ({sector})\n"
f"Revenue: ${revenue:,.0f}\n"
f"Net Income: ${net_income:,.0f}\n"
f"Total Assets: ${total_assets:,.0f}\n"
f"Total Equity: ${total_equity:,.0f}\n\n"
f"Reply with one line per field, format `<FieldName>: <number>`. "
f"Use the EXACT field names below (case and spelling must "
f"match):\n{fields_str}\n\n"
f"Example:\n"
f"{example_key}: 1000000\n..."
)
else: # T6 — Gen-Eval (NL company description, no stmt_*)
description = row.get(
"company_description", f"A company with ticker {ticker}",
)
sector = row.get("sector", "Unknown")
industry = row.get("industry", "Unknown")
prompts.append(
f"You are a financial analyst. Given this company description: "
f"'{description}', sector: '{sector}', industry: '{industry}', "
f"generate plausible values for the following financial fields. "
f"Use the EXACT field names below (case and spelling must "
f"match): {fields_str}.\n\n"
f"Reply with one line per field, format `<FieldName>: <number>`. "
f"Example:\n"
f"{example_key}: 1000000\n..."
)
responses = self._call_batch(prompts, max_tokens=1024)
parsed_per_row = [_extract_json_object(r) for r in responses]
unparsed_idx = [i for i, p in enumerate(parsed_per_row) if p is None]
if unparsed_idx:
retry_prompts = [
prompts[i]
+ "\n\nIMPORTANT: Reply with EXACTLY one line per field, "
"format `<FieldName>: <number>`. No extra commentary."
for i in unparsed_idx
]
retries = self._call_batch(retry_prompts, max_tokens=1024)
still: list[int] = []
for k, i in enumerate(unparsed_idx):
p = _extract_json_object(retries[k])
if p is None:
still.append(i)
else:
parsed_per_row[i] = p
unparsed_idx = still
if unparsed_idx:
logger.warning(
"%s predict: %d/%d rows unparseable after retry; "
"emitting NaN — eval-side fillna will substitute 0.",
type(self).__name__, len(unparsed_idx), n,
)
rows: list[dict[str, Any]] = []
n_valid = 0
for (ticker, fy, fields_for_row), parsed in zip(meta_rows, parsed_per_row):
for field in fields_for_row:
# Use the alias-aware canonical-field resolver so common
# LLM variants (Revenue, NetIncome, TotalAssets, ...)
# match the canonical XBRL names in y_true.
v = _resolve_canonical_field(parsed, str(field))
try:
pred_val = float(v) if v is not None else np.nan
except (TypeError, ValueError):
pred_val = np.nan
if not np.isnan(pred_val):
n_valid += 1
rows.append({
"ticker": ticker,
"fiscal_year": fy,
"field": str(field),
"pred": pred_val,
})
# 100% unparseable — log + emit NaN frame; eval-side fillna(0)
# substitutes the missing field-tuple values, contributing APE=100%
# per missed field. The cell remains MEASURABLE.
if n_valid == 0:
logger.warning(
"%s %s predict: 0/%d (canonical_field, value) cells "
"extracted; emitting NaN frame — eval will substitute 0.",
type(self).__name__, task, len(rows),
)
self.last_predict_meta = {
"task": task, "n_attempted": int(n),
"n_parse_errors_after_retry": 0,
"n_valid_field_cells": int(n_valid),
}
return pd.DataFrame(rows, columns=["ticker", "fiscal_year", "field", "pred"])
# ── T4: scenario-conditioned return ──────────────────────────────
def _predict_t4(self, X: Any) -> np.ndarray:
"""Per the canonical T4 loader, ``X`` is a DataFrame with columns
``lookback`` (object), ``event_type``, ``event_description``.
For backward compatibility with the legacy dict layout we accept
a dict too.
"""
if isinstance(X, pd.DataFrame):
if "event_type" not in X.columns:
raise ValueError("T4 X DataFrame missing 'event_type' column")
event_type = X["event_type"].astype(str).to_numpy()
event_desc = (
X["event_description"].astype(str).to_numpy()
if "event_description" in X.columns
else np.array([""] * len(X))
)
elif isinstance(X, dict):
event_type = np.asarray(X.get("event_type", []))
event_desc = np.asarray(X.get("event_description", []))
else:
raise ValueError(
f"T4 X must be a DataFrame or dict, got type={type(X).__name__}"
)
n = int(len(event_type))
if n == 0:
self.last_predict_meta = {
"task": "T4", "n_attempted": 0, "n_parse_errors": 0,
}
return np.zeros(0, dtype=np.float32)
if len(event_desc) != n:
raise ValueError(
f"T4 X: event_type ({len(event_type)}) and event_description "
f"({len(event_desc)}) length mismatch."
)
prompts: list[str] = []
for et, ed in zip(event_type, event_desc):
et_s = str(et) if et is not None else "unknown"
ed_s = str(ed)[:200] if ed is not None else ""
prompts.append(
f"You are a quantitative analyst. Predict the percentage return "
f"for the stock over the next 21 trading days following this "
f"macroeconomic event.\n\n"
f"Event type: {et_s}\n"
f"Description: {ed_s}\n\n"
f"Reply with ONLY a single number: the predicted return as a "
f"percentage (e.g., 2.5 for +2.5% or -1.3 for -1.3%)."
)
responses = self._call_batch(prompts, max_tokens=64)
preds = np.full(n, np.nan, dtype=np.float32)
unparsed_idx: list[int] = []
for i, resp in enumerate(responses):
v = _parse_number(resp)
if v is None:
unparsed_idx.append(i)
continue
preds[i] = float(v)
if unparsed_idx:
retry_prompts = [
prompts[i] + "\n\nIMPORTANT: Reply with ONLY a single signed "
"number (e.g. 2.5 or -1.3). No units, no percent sign, no text."
for i in unparsed_idx
]
retries = self._call_batch(retry_prompts, max_tokens=64)
still: list[int] = []
for k, i in enumerate(unparsed_idx):
v = _parse_number(retries[k])
if v is None:
still.append(i)
else:
preds[i] = float(v)
unparsed_idx = still
if unparsed_idx:
logger.warning(
"%s predict: %d/%d rows unparseable after retry; "
"emitting NaN — eval-side fillna will substitute 0.",
type(self).__name__, len(unparsed_idx), n,
)
self.last_predict_meta = {
"task": "T4", "n_attempted": int(n),
"n_parse_errors_after_retry": 0,
}
return preds
# ── T7: real-estate per-property rent / price ────────────────────
def _predict_t7(self, X: pd.DataFrame) -> pd.DataFrame:
if not isinstance(X, pd.DataFrame):
raise ValueError(
f"T7 X must be a DataFrame, got type={type(X).__name__}"
)
n = len(X)
if n == 0:
self.last_predict_meta = {
"task": "T7", "n_attempted": 0, "n_parse_errors": 0,
}
return pd.DataFrame(columns=["address", "pred_rent", "pred_price"])
prompts: list[str] = []
addrs: list[Any] = []
for _, row in X.iterrows():
addrs.append(row.get("address", None))
city = row.get("city", "Unknown")
state = row.get("state", "Unknown")
property_type = row.get("property_type", "Unknown")
sqft = row.get("sqft", "N/A")
beds = row.get("bedrooms", row.get("beds", "N/A"))
baths = row.get("bathrooms", row.get("baths", "N/A"))
year_built = row.get("year_built", "N/A")
last_sale_date = row.get("last_sale_date", None)
years_since_last_sale = row.get("years_since_last_sale", None)
sale_block = ""
if pd.notna(last_sale_date) and pd.notna(years_since_last_sale):
try:
lsd = pd.to_datetime(last_sale_date).strftime("%Y-%m-%d")
sale_block = (
f"Last sale: {lsd} "
f"({float(years_since_last_sale):.1f} years before today). "
)
except Exception:
sale_block = ""
prompts.append(
f"You are a real estate appraiser estimating value AS OF "
f"2026-04-11. Given this property: location={city}, {state}, "
f"type={property_type}, sqft={sqft}, beds={beds}, baths={baths}, "
f"year_built={year_built}. {sale_block}"
f"Estimate the monthly rent and sale price.\n\n"
f"Reply on two lines, dollars only (no $ sign, no commentary):\n"
f"Rent: <monthly_rent_dollars>\n"
f"Price: <sale_price_dollars>"
)
responses = self._call_batch(prompts, max_tokens=128)
parsed_per_row = [_extract_json_object(r) for r in responses]
unparsed_idx = [i for i, p in enumerate(parsed_per_row) if p is None]
if unparsed_idx:
retry_prompts = [
prompts[i] + "\n\nIMPORTANT: Reply on EXACTLY two lines, "
"no units / no $ / no commentary:\nRent: <number>\n"
"Price: <number>"
for i in unparsed_idx
]
retries = self._call_batch(retry_prompts, max_tokens=128)
still: list[int] = []
for k, i in enumerate(unparsed_idx):
p = _extract_json_object(retries[k])
if p is None:
still.append(i)
else:
parsed_per_row[i] = p
unparsed_idx = still
if unparsed_idx:
logger.warning(
"%s predict: %d/%d rows unparseable after retry; "
"emitting NaN — eval-side fillna will substitute 0.",
type(self).__name__, len(unparsed_idx), n,
)
rows: list[dict[str, Any]] = []
n_valid_rent = 0
n_valid_price = 0
for addr, parsed in zip(addrs, parsed_per_row):
if parsed is None:
rows.append({"address": addr, "pred_rent": np.nan,
"pred_price": np.nan})
continue
ci = {str(k).lower(): v for k, v in parsed.items()}
try:
rent_val = float(ci.get("rent", np.nan))
except (TypeError, ValueError):
rent_val = np.nan
try:
price_val = float(ci.get("price", np.nan))
except (TypeError, ValueError):
price_val = np.nan
if not np.isnan(rent_val):
n_valid_rent += 1
if not np.isnan(price_val):
n_valid_price += 1
rows.append({
"address": addr,
"pred_rent": rent_val,
"pred_price": price_val,
})
# 100% rent+price unparseable — log + emit NaN frame; eval-side
# fillna(0) substitutes both, APE=100% per row. Cell stays measurable.
if n_valid_rent == 0 and n_valid_price == 0:
logger.warning(
"%s T7 predict: 0/%d rows yielded rent or price — "
"emitting NaN frame; eval will substitute 0.",
type(self).__name__, n,
)
self.last_predict_meta = {
"task": "T7", "n_attempted": int(n),
"n_parse_errors_after_retry": 0,
"n_valid_rent": int(n_valid_rent),
"n_valid_price": int(n_valid_price),
}
return pd.DataFrame(rows, columns=["address", "pred_rent", "pred_price"])
# ── Concrete classes (one per HF model id) ──────────────────────────────
@register(
name="llama_scout",
family="llm",
tasks=_LLM_TASKS,
config_class=LlamaScoutConfig,
)
class LlamaScout(_LLMBase):
"""Llama-4 Scout 109B MoE (FP8), TP=4. Covers T1..T7 zero-shot."""
name: ClassVar[str] = "llama_scout"
_config_class: ClassVar[type[LLMConfig]] = LlamaScoutConfig
@register(
name="gemma4",
family="llm",
tasks=_LLM_TASKS,
config_class=Gemma4Config,
)
class Gemma4(_LLMBase):
"""Gemma-4 31B (FP8), TP=2. Covers T1..T7 zero-shot."""
name: ClassVar[str] = "gemma4"
_config_class: ClassVar[type[LLMConfig]] = Gemma4Config
@register(
name="qwen35",
family="llm",
tasks=_LLM_TASKS,
config_class=Qwen35Config,
)
class Qwen35(_LLMBase):
"""Qwen-3.5 27B (FP8), TP=1. Covers T1..T7 zero-shot."""
name: ClassVar[str] = "qwen35"
_config_class: ClassVar[type[LLMConfig]] = Qwen35Config
# Frontier closed-source LLMs served via OpenRouter (replace gemma4 + llm_finetuned).
class Gpt51Config(LLMConfig):
model_id: str = "openai/gpt-5.1"
@register(
name="gpt51",
family="llm",
tasks=_LLM_TASKS,
config_class=Gpt51Config,
)
class Gpt51(_LLMBase):
"""OpenAI GPT-5.1 served via OpenRouter. Zero-shot."""
name: ClassVar[str] = "gpt51"
_config_class: ClassVar[type[LLMConfig]] = Gpt51Config
class Gemini3FlashConfig(LLMConfig):
model_id: str = "google/gemini-3-flash-preview"
@register(
name="gemini3_flash",
family="llm",
tasks=_LLM_TASKS,
config_class=Gemini3FlashConfig,
)
class Gemini3Flash(_LLMBase):
"""Google Gemini-3 Flash (preview) via OpenRouter. Zero-shot."""
name: ClassVar[str] = "gemini3_flash"
_config_class: ClassVar[type[LLMConfig]] = Gemini3FlashConfig
class Exaone45Config(LLMConfig):
model_id: str = "LGAI-EXAONE/EXAONE-4.5-33B-FP8"
tensor_parallel_size: int = 4
@register(
name="exaone",
family="llm",
tasks=_LLM_TASKS,
config_class=Exaone45Config,
)
class Exaone45(_LLMBase):
"""LG AI Research EXAONE-4.5-33B (open weights, FP8). Local vLLM, TP=4. Zero-shot."""
name: ClassVar[str] = "exaone"
_config_class: ClassVar[type[LLMConfig]] = Exaone45Config
__all__ = ["LlamaScout", "Gemma4", "Qwen35", "Gpt51", "Gemini3Flash", "Exaone45"]