"""LLM-with-time-series reasoning methods (family ``llm_ts``). Two concrete classes, all covering T1..T7 per the Method × Task matrix in the unified-API plan §9: - :class:`ChatTime` (``name="chattime"``) — AAAI 2025 Oral; official repo ``ForestsKing/ChatTime``. - :class:`TimeMQA` (``name="time_mqa"``) — 2025 LoRA-fine-tuned LLMs on 200K time-series QA pairs; ``Time-MQA/Qwen-2.5-7B``. Each class wraps the corresponding LLM-with-TS-reasoning architecture from :mod:`baselines.llm_ts_reason`. They consume the same per-task ``X`` / ``y`` shapes the unified loader yields (matching :mod:`methods.llm`) but invoke the architecture-specific time-series tokenizer / patcher / adapter rather than plain text serialisation of the lookback. The constructor takes a typed Pydantic config (``ChatTimeConfig``, ``TimeMQAConfig``) plus an injected ``engine`` exposing the OpenAI-compatible ``chat_complete(messages, max_tokens, temperature, top_p) -> str`` protocol (see :mod:`methods._openai_engine`). When ``engine=None`` the class does NOT eagerly load any model — that is left to the runner who hands the engine in via DI (consistent with :mod:`methods.llm`). ChatTime additionally exposes a ``predict(history)`` numeric-forecast hook that the runner-supplied engine MAY implement; if absent the T1 path falls back to the chat-template completion route. A ``dry_run=True`` mode is provided for CPU smoke testing: every inference call is short-circuited to a deterministic placeholder response and predictions follow the canonical per-task shape so the runner contract / shape assertions in :mod:`tests.test_method_contract` can be verified without any GPU, weights, or vLLM engine. Both classes implement the canonical :class:`methods.base.Method` contract: ``fit`` (no-op for ZS), ``predict``, ``save`` / ``load`` via :class:`_HFSaveMixin`, ``default_config``, ``hyperparams``, ``lib_versions``. They consume neither ``meta`` nor any IO; the ``MACROLENS_DETERMINISTIC`` env var seeds python / numpy / torch. Per-task input / output shapes (mirrors :mod:`methods.llm`): T1 : X = (N, lookback, F) np.ndarray → y_pred (N, horizon) float32. T2 : X = pd.DataFrame → y_pred (N,) float32. T3 : X = pd.DataFrame → y_pred long-form [ticker, fiscal_year, field, value]. T4 : X = pd.DataFrame with `lookback`/ `event_type` / `event_description` columns → y_pred (N,) float32. T5 : X = pd.DataFrame → y_pred (N,) float32. T6 : X = pd.DataFrame → y_pred long-form. T7 : X = pd.DataFrame → y_pred [address, rent, price]. """ from __future__ import annotations import json import logging import os import pathlib import re from typing import Any import numpy as np import pandas as pd from ._config import ( ChatTimeConfig, LLMTSConfig, TimeMQAConfig, ) from ._openai_engine import DryRunEngine from ._registry import register from .base import Method, _HFSaveMixin logger = logging.getLogger(__name__) # ── Shared parsing helpers (lifted from baselines.llm_ts_reason) ────────── _NUM_RE = re.compile(r"[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?") def _parse_first_number(text: str) -> float | None: """Return the first plausible signed/decimal number from ``text``.""" if not text: return None cleaned = text.replace(",", "") m = _NUM_RE.search(cleaned) if not m: return None try: return float(m.group(0)) except (TypeError, ValueError): return None def _parse_horizon_list(response: str, horizon: int) -> np.ndarray | None: """Extract a JSON list of floats representing a forecast trajectory. Looks for the first ``[...]`` substring in ``response`` and parses it as JSON. Returns a ``(horizon,)`` float32 ndarray, padding with the last value when shorter and truncating when longer. Falls back to extracting all numeric tokens from the bracketed slice when JSON parsing fails. Returns ``None`` on total parse failure. """ if not response: return None start = response.find("[") end = response.rfind("]") if start < 0 or end <= start: return None candidate = response[start : end + 1] parsed: list[Any] | None = None try: loaded = json.loads(candidate) if isinstance(loaded, list): parsed = loaded except json.JSONDecodeError: parsed = None if parsed is None: tokens = _NUM_RE.findall(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: vals.append(float(v)) except (TypeError, ValueError): continue 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 _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 ``: `` 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 ": " 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 _safe_float(v: Any, default: float = 0.0) -> float: """Coerce ``v`` to float, returning ``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 _seed_from_env(seed: int) -> None: """Honor MACROLENS_DETERMINISTIC: seed python/numpy/torch when set.""" import random random.seed(seed) np.random.seed(seed) os.environ.setdefault("PYTHONHASHSEED", str(seed)) try: import torch torch.manual_seed(seed) if os.environ.get("MACROLENS_DETERMINISTIC") == "1": try: torch.use_deterministic_algorithms(True) except Exception: pass try: torch.backends.cudnn.deterministic = True # type: ignore[attr-defined] except Exception: pass except Exception: pass def _find_close_idx_from_array(X: np.ndarray) -> int: """Heuristic close-column finder for a (N, L, F) tensor.""" 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))]) # ── Task-conditional prompt builders ────────────────────────────────────── def _t1_prompt(history: np.ndarray, horizon: int, ticker: str = "the stock") -> str: """Forecast prompt for T1: emit a horizon-length JSON list of floats.""" last = float(history[-1]) if len(history) else 0.0 mean = float(np.mean(history)) if len(history) else 0.0 std = float(np.std(history)) if len(history) else 0.0 denom = max(float(history[0]) if len(history) else 1e-2, 1e-2) trend = float((history[-1] - history[0]) / denom * 100) if len(history) else 0.0 last20 = ", ".join(f"{v:.4f}" for v in history[-20:]) return ( f"You are a quantitative analyst. Predict the daily closing prices " f"of {ticker} for each of the next {horizon} trading days, given:\n" f"- Current close: ${last:.2f}\n" f"- Past {len(history)} closes: mean=${mean:.2f}, std=${std:.2f}, " f"trend={trend:+.1f}%\n" f"- Recent close series (last 20 of {len(history)}): [{last20}]\n\n" f"Reply with ONLY a JSON array of {horizon} floats, one per future " f"trading day, in chronological order:\n" f"[float, float, ..., float]" ) def _format_macro_snapshot(row: pd.Series) -> str: """Render the at-anchor macro snapshot for T2/T5 prompts. Mirrors :func:`methods.llm._format_macro_snapshot` so the LLM and LLM-TS families show the same four series to the model. """ 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 _t2_prompt(row: pd.Series) -> str: 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)) employees = row.get("fullTimeEmployees", "N/A") macro = _format_macro_snapshot(row) return ( f"You are a financial analyst. Estimate the total equity market " f"capitalization of this company.\n\n" f"Sector: {sector}\n" f"Revenue: ${revenue:,.0f}\n" f"Net Income: ${net_income:,.0f}\n" f"Total Assets: ${total_assets:,.0f}\n" f"Employees: {employees}\n" f"{macro}\n\n" f"Reply with ONLY a single number: the estimated market cap in dollars." ) def _t5_prompt(row: pd.Series, stmt_cols: list[str]) -> str: sector = row.get("sector", "Unknown") industry = row.get("industry", "Unknown") items = [] for c in stmt_cols: val = row.get(c) if pd.notna(val): try: items.append(f"{c}: ${float(val):,.0f}") except (TypeError, ValueError): continue block = "\n".join(items) if items else "No financial statement data available" macro = _format_macro_snapshot(row) return ( f"You are a private equity analyst. Given ONLY financial statement " f"data (no market price), estimate the market capitalization of " f"this company.\n\n" f"Sector: {sector}\n" f"Industry: {industry}\n" f"{block}\n" f"{macro}\n\n" f"Reply with ONLY a single number: the estimated market cap in dollars." ) _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 # (Revenue/Revenues, NetIncome/NetIncomeLoss, TotalAssets/Assets, etc.). # To recover usable predictions instead of forcing predict_failed when # the canonical name does not appear verbatim, accept these aliases at # parse time. Lookup is case-insensitive; lowercased keys. _T3_T6_FIELD_ALIASES: dict[str, list[str]] = { "Revenues": [ "revenues", "revenue", "totalrevenue", "totalrevenues", "sales", "totalsales", "stmt_revenue", "netrevenue", "netrevenues", ], "NetIncomeLoss": [ "netincomeloss", "netincome", "netearnings", "netprofit", "stmt_net_income", "income", "earnings", ], "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, canon_field: str) -> Any: """Look up ``canon_field`` in a parsed LLM response dict, accepting common-English aliases (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 def _t3_prompt(row: pd.Series, fields_str: str) -> str: ticker = str(row.get("ticker", "?")) 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)) example_key = fields_str.split(",")[0].strip() or "Revenues" return ( f"You are a financial analyst. Given company fundamentals, predict " f"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 `: `. " 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..." ) def _t6_prompt(row: pd.Series, fields_str: str) -> str: ticker = str(row.get("ticker", "?")) description = row.get( "company_description", f"A company with ticker {ticker}" ) sector = row.get("sector", "Unknown") industry = row.get("industry", "Unknown") example_key = fields_str.split(",")[0].strip() or "Revenues" return ( 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 match): " f"{fields_str}.\n\n" f"Reply with one line per field, format `: `. " f"Example:\n" f"{example_key}: 1000000\n..." ) def _t4_prompt(event_type: str, event_description: str) -> str: et_s = str(event_type) if event_type is not None else "unknown" ed_s = str(event_description)[:200] if event_description is not None else "" return ( f"You are a quantitative analyst. Predict the percentage return for " f"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%)." ) def _t7_prompt(row: pd.Series) -> str: 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 = "" return ( 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: \n" f"Price: " ) # ── Engine protocol ─────────────────────────────────────────────────────── # # The shared ``DryRunEngine`` from :mod:`methods._openai_engine` already # satisfies the chat-complete contract for shape-only smoke tests; we # re-export it under ``_DryRunEngine`` for backwards-compatibility with # any local references that still use the legacy name. _DryRunEngine = DryRunEngine # ── Base class for all three llm_ts methods ─────────────────────────────── class _LLMTSBase(_HFSaveMixin, Method): """Shared scaffolding for ChatTime / Time-MQA. Subclasses set ``name`` / ``family`` / ``tasks`` via ``@register`` and override ``_default_engine_loader`` if they want eager-load semantics when ``engine`` is supplied as ``None`` and ``dry_run`` is ``False``. """ _ALL_TASKS = frozenset({"T1", "T2", "T3", "T4", "T5", "T6", "T7"}) def __init__( self, *, task: str, config: LLMTSConfig | None = None, engine: Any = None, dry_run: bool = False, **kwargs: Any, ) -> None: if task not in self.tasks: raise ValueError( f"{type(self).__name__}: task={task!r} not in supported " f"set {sorted(self.tasks)}" ) self.task = task cfg_cls = self._config_class # set by @register if config is None: config = cfg_cls(**kwargs) if kwargs else cfg_cls() elif kwargs: # Re-validate by merging when both are supplied (rare). merged = {**config.model_dump(), **kwargs} config = cfg_cls(**merged) self.config = config # Honor either an explicit ``dry_run`` ctor kwarg OR ``config.dry_run`` # (the smoke-test path sets the latter via ``cfg.model_copy(...)``). self.dry_run = bool(dry_run) or bool(getattr(config, "dry_run", False)) self._engine = engine if engine is not None else ( DryRunEngine() if self.dry_run else None ) # Populated post-predict for parse-error tracking. self.last_predict_meta: dict[str, Any] = {} # Per-task hints settable by the runner (close index, horizon, # field-list override). Mirrors :mod:`methods.llm`. self._t1_close_idx: int | None = None self._t1_horizon: int = 21 self._t3_t6_fields_str: str = _DEFAULT_T3_T6_FIELDS # ── Method contract ── @classmethod def default_config(cls) -> LLMTSConfig: """Return a default-constructed config of the registered class.""" return cls._config_class() def fit(self, X: Any, y: Any, *, seed: int = 42) -> "Method": """No-op for zero-shot llm_ts methods (consistent with :mod:`methods.llm`). For T1 we still capture ``y.shape[1]`` as the prediction horizon so downstream ``predict`` emits matching trajectory lengths (the default ``_t1_horizon = 21`` is wrong for the canonical T1 task, whose horizon is 252 trading days). """ _seed_from_env(seed) if self.task == "T1" and isinstance(y, np.ndarray) and y.ndim == 2: self._t1_horizon = int(y.shape[1]) return self def predict(self, X: Any) -> np.ndarray | pd.DataFrame: """Dispatch to the per-task predictor for ``self.task``.""" if self._engine is None and not self.dry_run: raise RuntimeError( f"{type(self).__name__}.predict called with no engine and " "dry_run=False; either inject an engine or set dry_run=True." ) if self.task == "T1": return self._predict_t1(X) if self.task == "T2": return self._predict_t2_t5(X, task="T2") if self.task == "T3": return self._predict_t3_t6(X, task="T3") if self.task == "T4": return self._predict_t4(X) if self.task == "T5": return self._predict_t2_t5(X, task="T5") if self.task == "T6": return self._predict_t3_t6(X, task="T6") if self.task == "T7": return self._predict_t7(X) raise ValueError(f"Unknown task: {self.task!r}") # ── HF-save hooks (ZS — manifest-only) ── def _hf_save(self, path: pathlib.Path) -> None: # Zero-shot llm_ts methods carry no fit-time state aside from the # config + engine reference. The Pydantic config is already # serialised via ``manifest.json["hyperparams"]`` by the mixin's # save() above, so there's nothing extra to write for ZS. # Subclasses that hold non-config state may override. return None def _hf_load(self, path: pathlib.Path) -> None: # Symmetric: no extra artifacts to read for ZS. return None # ── Engine call ── def _call(self, prompt: str, *, max_tokens: int = 256) -> str: """Single-prompt inference via the injected engine. Subclasses MAY override to use ``engine.predict(numeric_history, ...)`` for T1 (ChatTime) instead of the natural-language chat-complete path. Default contract: ``self._engine.chat_complete(messages, max_tokens, ...) -> str``. """ engine = self._engine if engine is None: raise RuntimeError( f"{type(self).__name__}: engine is None and dry_run is False" ) messages = [{"role": "user", "content": prompt}] if hasattr(engine, "chat_complete"): return str(engine.chat_complete(messages, max_tokens=max_tokens)) # Backwards-compat hooks for legacy in-process engines. if hasattr(engine, "answer"): return str(engine.answer(prompt)) if callable(engine): return str(engine(prompt)) raise RuntimeError( f"{type(self).__name__}: injected engine has no .chat_complete() " "and is not callable" ) def _call_batch( self, prompts: list[str], *, max_tokens: int = 256, ) -> list[str]: """Batched inference. Default: one HTTP fan-out via the engine's ``chat_complete_batch`` (ThreadPoolExecutor inside :class:`OpenAIChatEngine`). Falls back to a per-prompt loop when the injected engine lacks the batch API. Order is preserved. TimeMQA overrides this to wrap each prompt in the authors' `` ... `` template before dispatch and strip ```` from each response. """ if not prompts: return [] engine = self._engine if engine is None: raise RuntimeError( f"{type(self).__name__}: engine is None and dry_run is False" ) if hasattr(engine, "chat_complete_batch"): batched = [[{"role": "user", "content": p}] for p in prompts] return [ str(r) for r in engine.chat_complete_batch( batched, max_tokens=max_tokens, ) ] # Fallback to serial single-call loop for legacy engines. return [self._call(p, max_tokens=max_tokens) for p in prompts] def _call_t1_batch( self, *, prompts: list[str], histories: list[np.ndarray], horizon: int, max_tokens: int = 256, ) -> list[str]: """Batched T1 inference. Default delegates to :meth:`_call_batch`. ChatTime overrides to use ``engine.predict(history)`` (numeric TS API) per-row when available, falling back to chat-complete for the rows where the numeric path raises. TimeMQA overrides to rebuild prompts from ``histories`` using the authors' forecasting-question shape (Appendix A.1, Kong et al. 2025). """ del histories, horizon return self._call_batch(prompts, max_tokens=max_tokens) # ── Per-task predictors ── 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, _n_feats = X.shape horizon = int(self._t1_horizon) 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) ) preds = np.full((n, horizon), np.nan, dtype=np.float32) # Trajectory output requires more tokens than a single scalar: # budget ~12 tokens per horizon step plus brackets/separators. max_tokens = max(64, 12 * horizon + 16) # Build per-row prompts + histories, then dispatch a single # batched HTTP fan-out (the engine's ThreadPoolExecutor handles # n_workers concurrency). histories: list[np.ndarray] = [] prompts: list[str] = [] for i in range(n): h = X[i, :, close_idx] histories.append(h) prompts.append(_t1_prompt(h, horizon)) responses = self._call_t1_batch( prompts=prompts, histories=histories, horizon=horizon, max_tokens=max_tokens, ) unparsed_idx: list[int] = [] for i, response in enumerate(responses): traj = _parse_horizon_list(response, horizon) if traj is None: unparsed_idx.append(i) continue preds[i, :] = traj if unparsed_idx: retry_prompts = [ prompts[i] + f"\n\nIMPORTANT: Reply with EXACTLY {horizon} numbers " "separated by commas, no other text." for i in unparsed_idx ] retry_hists = [histories[i] for i in unparsed_idx] retries = self._call_t1_batch( prompts=retry_prompts, histories=retry_hists, horizon=horizon, max_tokens=max_tokens, ) still: list[int] = [] for k, i in enumerate(unparsed_idx): traj = _parse_horizon_list(retries[k], horizon) if traj is None: still.append(i) else: preds[i, :] = traj 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": "T1", "n_attempted": int(n), "n_parse_errors_after_retry": 0, "horizon_in_prompt": horizon, "close_idx": int(close_idx), "lookback": int(lookback), } return preds def _call_t1( self, prompt: str, *, history: np.ndarray, horizon: int, max_tokens: int = 256, ) -> str: """T1 inference hook — subclasses may use a numeric TS API. Default falls back to the natural-language ``_call``. The ``max_tokens`` budget is sized for a horizon-length JSON array. """ return self._call(prompt, max_tokens=max_tokens) 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.float32) if task == "T2": prompts = [_t2_prompt(row) for _, row in X.iterrows()] else: stmt_cols = [c for c in X.columns if c.startswith("stmt_")] prompts = [_t5_prompt(row, stmt_cols) for _, row in X.iterrows()] responses = self._call_batch(prompts, max_tokens=64) preds = np.full(n, np.nan, dtype=np.float64) unparsed_idx: list[int] = [] for i, response in enumerate(responses): v = _parse_first_number(response) if v is None or v <= 0: unparsed_idx.append(i) continue preds[i] = float(v) 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_first_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 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"] ) fields_str = self._t3_t6_fields_str fields_for_row = [ f.strip() for f in fields_str.split(",") if f.strip() ] prompts: list[str] = [] tickers: list[str] = [] fys: list[Any] = [] for _, row in X.iterrows(): tickers.append(str(row.get("ticker", "?"))) fys.append(row.get("fiscal_year", None)) prompts.append( _t3_prompt(row, fields_str) if task == "T3" else _t6_prompt(row, fields_str) ) 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 `: `. 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, ) # Canonical fields the eval-side join expects. Only matches against # this set count as "valid"; arbitrary keys the LLM invented (e.g. # ``Revenue`` for canonical ``Revenues``, ``NetIncome`` for # ``NetIncomeLoss``) are filtered out so the predict-side # n_valid==0 gate triggers when the LLM cannot produce canonical # field names. canonical_fields = {f.strip() for f in fields_for_row if f.strip()} canonical_lc = {f.lower(): f for f in canonical_fields} rows: list[dict[str, Any]] = [] n_valid = 0 for i, parsed in enumerate(parsed_per_row): ticker = tickers[i] fy = fys[i] for canon_field in canonical_fields: v = _resolve_canonical_field(parsed, canon_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": canon_field, "pred": pred_val, }) if n_valid == 0: # 0/N valid is a legitimate benchmark measurement for methods that # cannot produce the canonical XBRL field schema (ChatTime's # 10K-bin numeric tokenizer cannot emit structured text; the # chat-fallback path returns ""). Emit the all-NaN frame and let # the eval-side fillna(0) -> APE 100% rule score it honestly, # rather than converting a real failure into a hard error. logger.warning( "%s %s predict: 0/%d rows yielded any canonical " "(field, value) pair — emitting all-NaN frame; eval will " "score as 100%% MAPE.", type(self).__name__, task, n, ) # 100% NaN frame — log and pass through; eval-side fillna(0) # substitutes 0 per missed field, contributing APE=100% (clipped). if not any( (r["pred"] is not None) and not ( isinstance(r["pred"], float) and np.isnan(r["pred"]) ) for r in rows ): logger.warning( "%s %s predict: every row NaN; emitting NaN frame — " "eval will substitute 0.", type(self).__name__, task, ) 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"] ) def _predict_t4(self, X: Any) -> np.ndarray: # Unified loader yields a DataFrame with `lookback` (object cells), # `event_type`, `event_description`. Accept the legacy dict form # too for backwards compat with :mod:`methods.llm` callers. if isinstance(X, dict): event_type = np.asarray(X.get("event_type", [])) event_desc = np.asarray(X.get("event_description", [])) elif isinstance(X, pd.DataFrame): event_type = ( X["event_type"].to_numpy() if "event_type" in X.columns else np.array([]) ) event_desc = ( X["event_description"].to_numpy() if "event_description" in X.columns else np.array([""] * len(event_type)) ) else: raise ValueError( f"T4 X must be 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 " f"event_description ({len(event_desc)}) length mismatch." ) prompts = [ _t4_prompt(event_type[i], event_desc[i]) for i in range(n) ] responses = self._call_batch(prompts, max_tokens=64) preds = np.full(n, np.nan, dtype=np.float32) unparsed_idx: list[int] = [] for i, response in enumerate(responses): v = _parse_first_number(response) 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_first_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 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"] ) addrs: list[Any] = [] prompts: list[str] = [] for _, row in X.iterrows(): addrs.append(row.get("address", None)) prompts.append(_t7_prompt(row)) 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: \n" "Price: " 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 i, parsed in enumerate(parsed_per_row): addr = addrs[i] 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", 0) or 0) except (TypeError, ValueError): rent_val = np.nan try: price_val = float(ci.get("price", 0) or 0) except (TypeError, ValueError): price_val = np.nan if not np.isnan(rent_val) and rent_val != 0: n_valid_rent += 1 if not np.isnan(price_val) and price_val != 0: n_valid_price += 1 rows.append({"address": addr, "pred_rent": rent_val, "pred_price": price_val}) 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"] ) # ── ChatTime ────────────────────────────────────────────────────────────── @register( name="chattime", family="llm_ts", tasks={"T1", "T2", "T3", "T4", "T5", "T6", "T7"}, config_class=ChatTimeConfig, ) class ChatTime(_LLMTSBase): """ChatTime (AAAI 2025 Oral) wrapped under the unified Method contract. The official ChatTime model exposes both numeric (``predict``) and natural-language (``answer``) APIs over the same backbone. We use ``predict(history)`` for T1 and ``answer(prompt)`` for T2..T7. Engine DI: ``engine`` may be a ``ChatTimeModel`` instance (from ``ForestsKing/ChatTime``) exposing ``predict(history)`` and ``answer(prompt)``. When ``engine=None`` and ``dry_run=False`` the runner is responsible for instantiating the model (vendor clone + HF weights at ``ChengsenWang/ChatTime-1-7B-Chat``). """ def _call_t1_batch( self, *, prompts: list[str], histories: list[np.ndarray], horizon: int, max_tokens: int = 256, ) -> list[str]: """T1 batch: use numeric ``engine.predict(history)`` per-row when available; fall back to the chat-complete batched path otherwise. Returns one JSON-array-shaped string per row so the unified :func:`_parse_horizon_list` parser can consume each entry. """ engine = self._engine if ( engine is not None and hasattr(engine, "predict") and not self.dry_run ): outs: list[str] = [] chat_indices: list[int] = [] chat_prompts: list[str] = [] for i, hist in enumerate(histories): try: # Pass pred_len to the numeric engine so the authors' # ChatTime.predict() generates the requested horizon # rather than its constructor-time dummy. try: forecast = engine.predict(hist, pred_len=horizon) except TypeError: forecast = engine.predict(hist) if forecast is not None and len(forecast) > 0: vals = [float(v) for v in list(forecast)[:horizon]] if len(vals) < horizon: vals = vals + [vals[-1]] * (horizon - len(vals)) outs.append( "[" + ", ".join(f"{v:.4f}" for v in vals) + "]" ) continue except Exception: pass # Numeric path returned empty / raised — defer to # chat-complete fallback for this row. outs.append("") chat_indices.append(i) chat_prompts.append(prompts[i]) if chat_prompts: fallback = self._call_batch( chat_prompts, max_tokens=max_tokens, ) for j, i in enumerate(chat_indices): outs[i] = fallback[j] return outs # No numeric engine — straight chat-complete batch. return self._call_batch(prompts, max_tokens=max_tokens) # ── Time-MQA ────────────────────────────────────────────────────────────── # Authors' Q&A wrapper — verbatim from the Time-MQA paper, Appendix D # "Training Data Format" (Kong et al., ACL 2025, p. 29749): # # "We format our question-and-answer pairs using a specifically # designed template to clearly separate questions from answers. # The template is structured as follows: {Question} # {Answer} . ... In the case of the Qwen model, only # <|endoftext|> is added at the end of each sample." # # Authors' Q&A *content* style (verbatim, Appendix A.1–A.5, p. 29748): # - Question embeds the time series inline as # ``The input Time Series are [Time Series Data Points]``. # - Answer always begins ``Based on the given information, ...``. # - Forecasting answer body is a bracketed list of floats. # # We honour the wrapper exactly: the user message we send is # `` {question} `` and we ask the model to terminate with # ````. Inference is via vLLM ``--enable-lora`` against the # authors' adapter ``Time-MQA/Qwen-2.5-7B`` over base # ``Qwen/Qwen2.5-7B-Instruct`` (see :mod:`methods._openai_engine`). _TIME_MQA_END_TOKEN = "" def _wrap_time_mqa(question: str) -> str: """Wrap an arbitrary task-specific question in the authors' Q&A format. The authors trained Qwen-2.5-7B on samples shaped exactly as `` {Question} {Answer} ``. At inference we send the `` ... `` prefix verbatim and instruct the model to terminate with ```` (matching the training distribution). """ return ( f" {question} Based on the given information, " ) def _strip_time_mqa(response: str) -> str: """Strip the authors' ```` terminator + Qwen ``<|endoftext|>``. Any of the per-task numeric / JSON parsers already handle a leading ``"Based on the given information, ..."`` prefix because they search for the first numeric / bracket / brace; we only need to ensure the end-of-sample tokens do not corrupt the regex match. """ if not response: return response out = response end_idx = out.find(_TIME_MQA_END_TOKEN) if end_idx >= 0: out = out[:end_idx] out = out.replace("<|endoftext|>", "") return out.strip() def _t1_prompt_time_mqa( history: np.ndarray, horizon: int, ticker: str = "the stock" ) -> str: """Authors' forecasting-style question for T1 (Appendix A.1, p. 29748). Mirrors the training-distribution shape: ``... The input Time Series are [v1, v2, ..., vL]. Please predict the next N time series points given information above.`` The lookback is serialised as a bracketed comma-separated float list, and we ask for the forecast as a bracketed list of ``horizon`` floats so :func:`_parse_horizon_list` can consume the response. """ series_str = "[" + ", ".join(f"{float(v):.4f}" for v in history) + "]" return ( f"This dataset records daily closing prices of {ticker}. " f"The input Time Series are {series_str}. " f"Please predict the next {horizon} time series points given " f"information above. Reply with ONLY a list of {horizon} floats " f"in the form [v1, v2, ..., v{horizon}]." ) @register( name="time_mqa", family="llm_ts", tasks={"T1", "T2", "T3", "T4", "T5", "T6", "T7"}, config_class=TimeMQAConfig, ) class TimeMQA(_LLMTSBase): """Time-MQA (Kong et al., ACL 2025) under the unified Method contract. Time-MQA's Qwen-2.5-7B checkpoint is a LoRA adapter trained on the 192,843-pair TSQA corpus, with every sample wrapped as `` {Question} {Answer} `` (paper §D, p. 29749). The injected engine is the shared OpenAI-compatible vLLM client (:class:`OpenAIChatEngine`) served against the authors' adapter via ``vllm serve Qwen/Qwen2.5-7B-Instruct --enable-lora --lora-modules time_mqa=Time-MQA/Qwen-2.5-7B`` (see :mod:`methods._openai_engine`). Faithfulness to the authors' inference distribution --------------------------------------------------- We honour the authors' published Q&A wrapper exactly: every user message is `` {question} Based on the given information,`` and we strip a trailing ```` from the response before parsing. For T1 we additionally adopt the authors' forecasting-question shape (Appendix A.1: ``... The input Time Series are [...]. Please predict the next N time series points given information above.``) so the lookback is serialised in the format Qwen-2.5-7B was tuned on. Limitation ~~~~~~~~~~ The TSQA corpus does not include MacroLens-style tasks T2/T3/T5/T6/T7 (market-cap, statement-field, real-estate prediction). For those tasks we keep the MacroLens task-specific question content but wrap it in the authors' `` ... `` separators so the model operates inside its trained input distribution. Reviewers should treat T2/T3/T5/T6/T7 results as the authors' adapter operating on out-of-distribution finance/real-estate questions; T1/T4 are the closest match to the TSQA forecasting / open-ended-reasoning splits. """ def _call(self, prompt: str, *, max_tokens: int = 256) -> str: """Wrap ``prompt`` in the authors' `` ... `` template.""" wrapped = _wrap_time_mqa(prompt) engine = self._engine if engine is None: raise RuntimeError( f"{type(self).__name__}: engine is None and dry_run is False" ) messages = [{"role": "user", "content": wrapped}] if hasattr(engine, "chat_complete"): raw = str(engine.chat_complete(messages, max_tokens=max_tokens)) elif hasattr(engine, "answer"): raw = str(engine.answer(wrapped)) elif callable(engine): raw = str(engine(wrapped)) else: raise RuntimeError( f"{type(self).__name__}: injected engine has no .chat_complete() " "and is not callable" ) return _strip_time_mqa(raw) def _call_batch( self, prompts: list[str], *, max_tokens: int = 256, ) -> list[str]: """Batch path with the authors' Q&A wrapper. Each prompt is wrapped in `` ... `` before dispatch and each response stripped of ```` (and Qwen's ``<|endoftext|>``) before return. Falls back to per-prompt :meth:`_call` when the engine lacks ``chat_complete_batch``. """ if not prompts: return [] engine = self._engine if engine is None: raise RuntimeError( f"{type(self).__name__}: engine is None and dry_run is False" ) wrapped = [_wrap_time_mqa(p) for p in prompts] if hasattr(engine, "chat_complete_batch"): batched = [[{"role": "user", "content": w}] for w in wrapped] raws = [ str(r) for r in engine.chat_complete_batch( batched, max_tokens=max_tokens, ) ] return [_strip_time_mqa(r) for r in raws] # Legacy engines without batch API: per-prompt loop preserves # wrap-and-strip via :meth:`_call`. return [self._call(p, max_tokens=max_tokens) for p in prompts] def _call_t1_batch( self, *, prompts: list[str], histories: list[np.ndarray], horizon: int, max_tokens: int = 256, ) -> list[str]: """Override T1 batch to use the authors' forecasting-question shape. The default :func:`_t1_prompt`-derived prompts are replaced by :func:`_t1_prompt_time_mqa`, which serialises the lookback inline as ``[v1, v2, ..., vL]`` and asks for the next ``horizon`` points — exactly the shape Qwen-2.5-7B was tuned on for TSQA's forecasting split (Appendix A.1, Kong et al. 2025). """ del prompts # Rebuilt from histories below. ts_prompts = [_t1_prompt_time_mqa(h, horizon) for h in histories] return self._call_batch(ts_prompts, max_tokens=max_tokens) __all__ = ["ChatTime", "TimeMQA"]