"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(valuation): refuse non-finite comps and three-statement inputs
Robin1987China201419cdd91e
diff --git a/agent/src/quantlib/valuation/comps.py b/agent/src/quantlib/valuation/comps.pyindex 162542f29..06990aff7 100644--- a/agent/src/quantlib/valuation/comps.py+++ b/agent/src/quantlib/valuation/comps.py@@ -91,6 +91,7 @@ independently importable.from __future__ import annotations+import mathfrom collections.abc import Mapping, Sequencefrom dataclasses import dataclassfrom types import MappingProxyType@@ -251,7 +252,8 @@ def calendarise_metric(The aligned :class:`CalendarisedMetric`.Raises:- ValuationError: If `policy` is not one of `CALENDARISATION_POLICIES`.+ ValuationError: If `policy` is not one of `CALENDARISATION_POLICIES`,+ or if any supplied period value is not a finite number.MissingInputError: If `periods` lacks a field this policy needs."""if policy not in CALENDARISATION_POLICIES:@@ -261,6 +263,17 @@ def calendarise_metric()model = f"comps.calendarise_metric[{company_name}.{metric_name}:{policy}]"+ for name, val in (+ ("last_full_fiscal_year", periods.last_full_fiscal_year),+ ("current_year_to_date", periods.current_year_to_date),+ ("prior_year_to_date", periods.prior_year_to_date),+ ("next_full_fiscal_year", periods.next_full_fiscal_year),+ ):+ if val is not None and not math.isfinite(val):+ raise ValuationError(+ f"{model}: {name} must be a finite number, got {val!r}"+ )+if policy == "ltm":require_inputs({@@ -371,6 +384,14 @@ def _bridge_delta(`(delta, omitted_components)`."""omitted: list[str] = []+ if not math.isfinite(total_debt):+ raise ValuationError(+ f"comps: total_debt must be a finite number, got {total_debt!r}"+ )+ if not math.isfinite(cash_and_equivalents):+ raise ValuationError(+ f"comps: cash_and_equivalents must be a finite number, got {cash_and_equivalents!r}"+ )total = total_debt - cash_and_equivalentsfor name, value in (("minority_interest", minority_interest),@@ -380,6 +401,10 @@ def _bridge_delta(if value is None:omitted.append(name)continue+ if not math.isfinite(value):+ raise ValuationError(+ f"comps: {name} must be a finite number, got {value!r}"+ )sign = -1.0 if name == "investments_in_associates" else 1.0total += sign * valuereturn total, tuple(omitted)@@ -454,6 +479,8 @@ def enterprise_value(Raises:MissingInputError: If `market_cap`, `total_debt` or`cash_and_equivalents` is absent.+ ValuationError: If `market_cap` or any supplied bridge line is not a+ finite number."""require_inputs({@@ -467,6 +494,10 @@ def enterprise_value(delta, omitted = _bridge_delta(total_debt, cash_and_equivalents, minority_interest, preferred_stock, investments_in_associates)+ if not math.isfinite(market_cap):+ raise ValuationError(+ f"comps.enterprise_value: market_cap must be a finite number, got {market_cap!r}"+ )ev = float(market_cap) + deltareturn EVBridgeResult(direction="equity_to_ev",@@ -518,6 +549,8 @@ def equity_value_from_enterprise_value(Raises:MissingInputError: If `enterprise_value`, `total_debt` or`cash_and_equivalents` is absent.+ ValuationError: If `enterprise_value` or any supplied bridge line is+ not a finite number."""require_inputs({@@ -531,6 +564,11 @@ def equity_value_from_enterprise_value(delta, omitted = _bridge_delta(total_debt, cash_and_equivalents, minority_interest, preferred_stock, investments_in_associates)+ if not math.isfinite(enterprise_value):+ raise ValuationError(+ f"comps.equity_value_from_enterprise_value: enterprise_value must be a "+ f"finite number, got {enterprise_value!r}"+ )equity = float(enterprise_value) - deltareturn EVBridgeResult(direction="ev_to_equity",@@ -680,7 +718,8 @@ class ExcludedMultiple:multiple_name: Which multiple (one of `MULTIPLE_NAMES`).denominator_value: The denominator at the time of exclusion.numerator_value: The numerator at the time of exclusion.- reason: ``"non_positive_denominator"`` or ``"non_positive_numerator"``.+ reason: ``"non_positive_denominator"``, ``"non_positive_numerator"``,+ ``"non_finite_denominator"`` or ``"non_finite_numerator"``."""peer_name: str@@ -716,9 +755,25 @@ def _compute_multiple(multiple_name: For the exclusion record.Returns:- ``(value, None)`` when both sides are positive, else+ ``(value, None)`` when both sides are positive finite numbers, else``(None, ExcludedMultiple(...))`` naming the side that failed."""+ if not math.isfinite(denominator):+ return None, ExcludedMultiple(+ peer_name=peer_name,+ multiple_name=multiple_name,+ denominator_value=denominator,+ numerator_value=numerator,+ reason="non_finite_denominator",+ )+ if not math.isfinite(numerator):+ return None, ExcludedMultiple(+ peer_name=peer_name,+ multiple_name=multiple_name,+ denominator_value=denominator,+ numerator_value=numerator,+ reason="non_finite_numerator",+ )if denominator <= 0.0:return None, ExcludedMultiple(peer_name=peer_name,diff --git a/agent/src/quantlib/valuation/threestatement.py b/agent/src/quantlib/valuation/threestatement.pyindex b7626d795..faf78cd2b 100644--- a/agent/src/quantlib/valuation/threestatement.py+++ b/agent/src/quantlib/valuation/threestatement.py@@ -434,17 +434,46 @@ def check_balance_sheet(balance_sheet: BalanceSheet, tolerance: float = BALANCE_Raises:BalanceSheetError: If ``assets != liabilities + equity`` beyond- ``tolerance``. The exception carries the exact residual.+ ``tolerance``, or if any of ``assets``, ``liabilities`` or+ ``equity`` is not a finite number. The exception carries the+ exact residual."""assets = balance_sheet.total_assetsliabilities = balance_sheet.total_liabilitiesequity = balance_sheet.total_equityresidual = assets - liabilities - equityscale = max(abs(assets), 1.0)- if abs(residual) > tolerance * scale:+ if not math.isfinite(residual) or abs(residual) > tolerance * scale:raise BalanceSheetError(balance_sheet.period, assets, liabilities, equity, tolerance)+def _require_finite(value: float, name: str, model: str) -> float:+ """Check a value is a finite number, refusing NaN and infinity.++ Args:+ value: The candidate value.+ name: Field name for the error message.+ model: Model name for the error message.++ Returns:+ ``value`` as a float.++ Raises:+ ValuationError: If the value is not a finite number. A non-finite+ driver or opening figure would otherwise flow into the projection+ and surface as a misleading "did not converge" error.+ """+ try:+ numeric = float(value)+ except (TypeError, ValueError) as exc:+ raise ValuationError(f"{model}: {name} must be a number, got {value!r}") from exc+ if not math.isfinite(numeric):+ raise ValuationError(+ f"{model}: {name} must be a finite number, got {numeric!r}"+ )+ return numeric++def _resolve_period_count(drivers: Mapping[str, Sequence[float]]) -> int:"""Validate every driver sequence shares one non-zero length and return it.@@ -665,7 +694,8 @@ def project_three_statement(MissingInputError: If ``opening`` or ``drivers`` is missing a requiredfield.ValuationError: If the driver sequences disagree in length, are empty,- or if ``circularity_tolerance`` / ``balance_tolerance`` /+ if any opening or driver value is not a finite number, or if+ ``circularity_tolerance`` / ``balance_tolerance`` /``max_circularity_iterations`` are not usable.BalanceSheetError: If the opening balance sheet, or any projectedperiod's balance sheet, does not balance.@@ -682,6 +712,12 @@ def project_three_statement(f"{max_circularity_iterations!r}")+ for field in OPENING_REQUIRED_FIELDS:+ _require_finite(opening[field], f"opening {field}", MODEL_NAME)+ for field in DRIVER_REQUIRED_FIELDS:+ for index, raw in enumerate(drivers[field]):+ _require_finite(raw, f"drivers {field}[{index}]", MODEL_NAME)+periods = _resolve_period_count(drivers)opening_balance_sheet = BalanceSheet(diff --git a/agent/tests/quantlib/valuation/test_comps.py b/agent/tests/quantlib/valuation/test_comps.pyindex a3e60a484..dceeac97a 100644--- a/agent/tests/quantlib/valuation/test_comps.py+++ b/agent/tests/quantlib/valuation/test_comps.py@@ -27,6 +27,7 @@ from src.quantlib.valuation.comps import (FlowMetricPeriods,PeerCompany,TargetCompany,+ _compute_multiple,calendarise_metric,enterprise_value,equity_value_from_enterprise_value,@@ -776,3 +777,75 @@ def test_full_hand_computed_example():# No small-sample warning: 4 peers >= MIN_ROBUST_COMPS, and CCC's single# exclusion still leaves 3 included for ev_ebitda.assert result.warnings == ()+++def test_non_finite_numerator_is_excluded_not_a_nan_multiple():+ value, excluded = _compute_multiple(+ float("nan"), 100.0, peer_name="NANCO", multiple_name="ev_ebitda"+ )+ assert value is None+ assert excluded is not None+ assert excluded.peer_name == "NANCO"+ assert excluded.reason == "non_finite_numerator"+++def test_non_finite_denominator_is_excluded_not_a_nan_multiple():+ value, excluded = _compute_multiple(+ 200.0, float("inf"), peer_name="INFCO", multiple_name="ev_ebitda"+ )+ assert value is None+ assert excluded is not None+ assert excluded.reason == "non_finite_denominator"+++def test_finite_positive_multiple_is_still_computed():+ value, excluded = _compute_multiple(200.0, 10.0, peer_name="OK", multiple_name="ev_ebitda")+ assert excluded is None+ assert value == pytest.approx(20.0, abs=EXACT)+++def test_enterprise_value_refuses_non_finite_inputs():+ with pytest.raises(ValuationError):+ enterprise_value(market_cap=float("nan"), total_debt=100.0, cash_and_equivalents=20.0)+ with pytest.raises(ValuationError):+ enterprise_value(market_cap=200.0, total_debt=float("inf"), cash_and_equivalents=20.0)+ with pytest.raises(ValuationError):+ enterprise_value(market_cap=200.0, total_debt=100.0, cash_and_equivalents=float("nan"))+++def test_equity_value_from_enterprise_value_refuses_non_finite_enterprise_value():+ with pytest.raises(ValuationError):+ equity_value_from_enterprise_value(+ enterprise_value=float("inf"), total_debt=100.0, cash_and_equivalents=20.0+ )+++def test_enterprise_value_finite_bridge_is_unchanged():+ result = enterprise_value(market_cap=200.0, total_debt=100.0, cash_and_equivalents=20.0)+ assert result.enterprise_value == pytest.approx(280.0, abs=EXACT)+++def test_calendarise_metric_refuses_non_finite_period_values():+ with pytest.raises(ValuationError):+ calendarise_metric(+ _flow(float("nan"), ytd=10.0, prior_ytd=5.0),+ "ltm", metric_name="ebitda", company_name="X",+ )+ with pytest.raises(ValuationError):+ calendarise_metric(+ _flow(100.0, ytd=float("inf"), prior_ytd=5.0),+ "ltm", metric_name="ebitda", company_name="X",+ )+ with pytest.raises(ValuationError):+ calendarise_metric(+ _flow(100.0, next_fy=float("nan"), month=6),+ "calendar_year", metric_name="revenue", company_name="X",+ )+++def test_calendarise_metric_finite_ltm_is_unchanged():+ result = calendarise_metric(+ _flow(100.0, ytd=40.0, prior_ytd=30.0),+ "ltm", metric_name="ebitda", company_name="X",+ )+ assert result.value == pytest.approx(110.0, abs=EXACT)diff --git a/agent/tests/quantlib/valuation/test_threestatement.py b/agent/tests/quantlib/valuation/test_threestatement.pyindex 0de532e08..410f10cf2 100644--- a/agent/tests/quantlib/valuation/test_threestatement.py+++ b/agent/tests/quantlib/valuation/test_threestatement.py@@ -25,7 +25,7 @@ from __future__ import annotationsimport pytest-from src.quantlib.valuation.contracts import MissingInputError+from src.quantlib.valuation.contracts import MissingInputError, ValuationErrorfrom src.quantlib.valuation.threestatement import (MAX_CIRCULARITY_ITERATIONS,BalanceSheet,@@ -313,6 +313,52 @@ def test_check_balance_sheet_does_not_raise_when_balanced():check_balance_sheet(balanced) # must not raise+def test_check_balance_sheet_raises_on_non_finite_assets():+ """A NaN asset makes the residual non-finite, which must not pass the check."""+ sheet = BalanceSheet(+ period=1,+ cash=float("nan"),+ net_working_capital=200.0,+ ppe=3_000.0,+ revolver_balance=1_000.0,+ paid_in_capital=2_000.0,+ retained_earnings=1_200.0,+ )+ with pytest.raises(BalanceSheetError):+ check_balance_sheet(sheet)+++def test_check_balance_sheet_raises_on_infinite_equity():+ """An infinite equity value must not pass the balance check."""+ sheet = BalanceSheet(+ period=1,+ cash=1_000.0,+ net_working_capital=200.0,+ ppe=3_000.0,+ revolver_balance=1_000.0,+ paid_in_capital=float("inf"),+ retained_earnings=1_200.0,+ )+ with pytest.raises(BalanceSheetError):+ check_balance_sheet(sheet)+++def test_project_three_statement_refuses_non_finite_driver():+ """A NaN driver must fail with a clear non-finite error, not a misleading+ ConvergenceError."""+ bad_drivers = dict(DRIVERS)+ bad_drivers["revenue_growth"] = [float("nan"), 0.08, 0.05]+ with pytest.raises(ValuationError):+ project_three_statement(OPENING, bad_drivers)+++def test_project_three_statement_refuses_non_finite_opening():+ bad_opening = dict(OPENING)+ bad_opening["revenue"] = float("inf")+ with pytest.raises(ValuationError):+ project_three_statement(bad_opening, DRIVERS)++def test_project_three_statement_raises_on_broken_opening_balance_sheet():"""An opening balance sheet that does not balance must refuse to project at all.