diff --git a/README.md b/README.md index d9c5f70..6f36e0c 100644 --- a/README.md +++ b/README.md @@ -137,6 +137,7 @@ No performance claims yet. The scaffold proves the invariants: | BeliefBench runner and baselines | `tests/test_beliefbench.py` | | GDELT and RSS map to observations | `tests/test_gdelt.py`, `tests/test_rss.py` | | Retries, dead letters, and replay | `tests/test_scheduler.py` | +| Fundamentals are as-filed, provenance-linked, and event flags cite ids | `tests/test_fundamentals.py` | | Quality checks catch duplicate, future, and stale data | `tests/test_quality.py` | | Predictions are immutable and settle once | `tests/test_ledger.py` | | RSI stays bounded; MACD / Bollinger / OBV behave | `tests/test_indicators.py` | diff --git a/core/janus/analysis/fundamentals.py b/core/janus/analysis/fundamentals.py new file mode 100644 index 0000000..3f81c01 --- /dev/null +++ b/core/janus/analysis/fundamentals.py @@ -0,0 +1,320 @@ +from __future__ import annotations + +from dataclasses import dataclass +from datetime import date, datetime +from typing import Any, Iterable, Optional, Sequence + +from ..memory.models import Observation, ObservationKind +from ..memory.store import JanusStore + +REVENUE_CONCEPTS = ( + "RevenueFromContractWithCustomerExcludingAssessedTax", + "Revenues", + "SalesRevenueNet", +) +GROSS_PROFIT_CONCEPTS = ("GrossProfit",) +OPERATING_INCOME_CONCEPTS = ("OperatingIncomeLoss",) +NET_INCOME_CONCEPTS = ("NetIncomeLoss", "ProfitLoss") +CFO_CONCEPTS = ( + "NetCashProvidedByUsedInOperatingActivities", + "NetCashProvidedByUsedInOperatingActivitiesContinuingOperations", +) +ASSETS_CONCEPTS = ("Assets",) +LIABILITIES_CONCEPTS = ("Liabilities",) +EQUITY_CONCEPTS = ( + "StockholdersEquity", + "StockholdersEquityIncludingPortionAttributableToNoncontrollingInterest", +) +DEBT_CONCEPTS = ("LongTermDebt", "LongTermDebtNoncurrent", "DebtCurrent") +EPS_CONCEPTS = ("EarningsPerShareDiluted", "EarningsPerShareBasic") + +EVENT_PATTERNS: dict[str, tuple[str, ...]] = { + "earnings": ("earnings", "results", "10-q", "10-k"), + "m&a": ("merger", "acquisition", "acquire", "acquires", "buyout"), + "litigation": ("lawsuit", "litigation", "court", "settlement", "probe"), + "insider": ("form 4", "insider", "beneficial ownership"), + "guidance": ("guidance", "outlook", "forecast"), +} + + +@dataclass(frozen=True) +class FeatureValue: + value: float + concepts: tuple[str, ...] + observation_ids: tuple[str, ...] + + +@dataclass(frozen=True) +class FundamentalReport: + entity_id: str + as_of: str + features: dict[str, float] + provenance: dict[str, list[str]] + missing: list[str] + + def to_dict(self) -> dict[str, Any]: + return { + "entity_id": self.entity_id, + "as_of": self.as_of, + "features": dict(sorted(self.features.items())), + "provenance": {key: sorted(value) for key, value in sorted(self.provenance.items())}, + "missing": sorted(self.missing), + } + + +def _parse_date(value: Any) -> Optional[date]: + if isinstance(value, date) and not isinstance(value, datetime): + return value + if isinstance(value, datetime): + return value.date() + if not value: + return None + try: + return date.fromisoformat(str(value)[:10]) + except ValueError: + return None + + +def _number(value: Any) -> Optional[float]: + try: + return float(value) + except (TypeError, ValueError): + return None + + +def _fact_period(observation: Observation) -> Optional[date]: + return _parse_date( + observation.value.get("period_end") + or observation.value.get("end") + or observation.valid_from + ) + + +def _latest_by_period( + observations: Sequence[Observation], concepts: Iterable[str] +) -> dict[date, Observation]: + allowed = set(concepts) + latest: dict[date, Observation] = {} + for observation in observations: + concept = str(observation.value.get("concept") or "") + if concept not in allowed: + continue + period = _fact_period(observation) + if period is None: + continue + current = latest.get(period) + if current is None or ( + observation.published_at, + observation.id, + ) > (current.published_at, current.id): + latest[period] = observation + return latest + + +def _latest( + observations: Sequence[Observation], concepts: Sequence[str] +) -> Optional[Observation]: + by_period = _latest_by_period(observations, concepts) + if not by_period: + return None + return by_period[max(by_period)] + + +def _prior_year( + observations: Sequence[Observation], concepts: Sequence[str], latest: Observation +) -> Optional[Observation]: + period = _fact_period(latest) + if period is None: + return None + by_period = _latest_by_period(observations, concepts) + candidates = [ + (abs((period - candidate_date).days - 365), candidate_date) + for candidate_date in by_period + if 300 <= (period - candidate_date).days <= 430 + ] + if not candidates: + return None + _, candidate_date = min(candidates) + return by_period[candidate_date] + + +def _value(observation: Optional[Observation]) -> Optional[float]: + if observation is None: + return None + return _number(observation.value.get("value")) + + +def _add( + features: dict[str, float], + provenance: dict[str, list[str]], + name: str, + value: Optional[float], + *observations: Optional[Observation], +) -> None: + if value is None: + return + features[name] = float(value) + provenance[name] = sorted( + observation.id for observation in observations if observation is not None + ) + + +def _ratio( + features: dict[str, float], + provenance: dict[str, list[str]], + name: str, + numerator: Optional[Observation], + denominator: Optional[Observation], +) -> None: + top = _value(numerator) + bottom = _value(denominator) + if top is None or bottom in (None, 0.0): + return + _add(features, provenance, name, top / bottom, numerator, denominator) + + +def _growth( + features: dict[str, float], + provenance: dict[str, list[str]], + name: str, + observations: Sequence[Observation], + concepts: Sequence[str], +) -> None: + current = _latest(observations, concepts) + if current is None: + return + prior = _prior_year(observations, concepts, current) + current_value = _value(current) + prior_value = _value(prior) + if current_value is None or prior_value in (None, 0.0): + return + _add( + features, + provenance, + name, + current_value / prior_value - 1.0, + current, + prior, + ) + + +def compute_fundamental_features( + store: JanusStore, + entity_id: str, + as_of: datetime, + *, + price: Optional[float] = None, +) -> FundamentalReport: + """Compute filing-backed fundamental features for one as-of date. + + Only facts published at or before ``as_of`` participate. A later + restatement therefore cannot change a historical feature. + """ + + if as_of.tzinfo is None or as_of.tzinfo.utcoffset(as_of) is None: + raise ValueError("as_of must be timezone-aware") + observations = [ + observation + for observation in store.query_observations_as_of( + entity_id, as_of, mode="published" + ) + if observation.kind is ObservationKind.fundamental + and observation.published_at <= as_of + and (_fact_period(observation) or date.max) <= as_of.date() + ] + + features: dict[str, float] = {} + provenance: dict[str, list[str]] = {} + + revenue = _latest(observations, REVENUE_CONCEPTS) + gross_profit = _latest(observations, GROSS_PROFIT_CONCEPTS) + operating_income = _latest(observations, OPERATING_INCOME_CONCEPTS) + net_income = _latest(observations, NET_INCOME_CONCEPTS) + cfo = _latest(observations, CFO_CONCEPTS) + assets = _latest(observations, ASSETS_CONCEPTS) + liabilities = _latest(observations, LIABILITIES_CONCEPTS) + equity = _latest(observations, EQUITY_CONCEPTS) + debt = _latest(observations, DEBT_CONCEPTS) + eps = _latest(observations, EPS_CONCEPTS) + + for name, observation in ( + ("revenue", revenue), + ("gross_profit", gross_profit), + ("operating_income", operating_income), + ("net_income", net_income), + ("operating_cash_flow", cfo), + ("assets", assets), + ("liabilities", liabilities), + ("equity", equity), + ("debt", debt), + ("eps_diluted", eps), + ): + _add(features, provenance, name, _value(observation), observation) + + _ratio(features, provenance, "gross_margin", gross_profit, revenue) + _ratio(features, provenance, "operating_margin", operating_income, revenue) + _ratio(features, provenance, "net_margin", net_income, revenue) + _ratio(features, provenance, "cash_flow_margin", cfo, revenue) + _ratio(features, provenance, "liabilities_to_assets", liabilities, assets) + _ratio(features, provenance, "debt_to_equity", debt, equity) + _growth(features, provenance, "revenue_growth_yoy", observations, REVENUE_CONCEPTS) + _growth(features, provenance, "net_income_growth_yoy", observations, NET_INCOME_CONCEPTS) + + if price is not None and eps is not None: + eps_value = _value(eps) + if eps_value is not None and eps_value > 0: + _add(features, provenance, "pe_ratio", float(price) / eps_value, eps) + if equity is not None and eps is not None: + shares = _value(net_income) + if shares not in (None, 0.0) and _value(eps) not in (None, 0.0): + shares = (_value(net_income) or 0.0) / (_value(eps) or 1.0) + if shares > 0: + book_value = (_value(equity) or 0.0) / shares + _add( + features, + provenance, + "book_value_per_share", + book_value, + equity, + net_income, + eps, + ) + + expected = ( + "revenue", + "gross_margin", + "operating_margin", + "net_margin", + "cash_flow_margin", + "liabilities_to_assets", + "debt_to_equity", + "revenue_growth_yoy", + "net_income_growth_yoy", + "eps_diluted", + ) + missing = [name for name in expected if name not in features] + return FundamentalReport( + entity_id=entity_id, + as_of=as_of.isoformat(), + features=dict(sorted(features.items())), + provenance=provenance, + missing=missing, + ) + + +def detect_events(observations: Sequence[Observation]) -> dict[str, list[str]]: + """Return event flags with the observation ids that support each flag.""" + + events: dict[str, set[str]] = {} + for observation in observations: + text = " ".join( + str(observation.value.get(key) or "") + for key in ("title", "summary", "description", "form", "items") + ).lower() + for flag, patterns in EVENT_PATTERNS.items(): + if any(pattern in text for pattern in patterns): + events.setdefault(flag, set()).add(observation.id) + return { + flag: sorted(ids) + for flag, ids in sorted(events.items()) + } diff --git a/docs/ANALYSIS.md b/docs/ANALYSIS.md index 37293e8..54f5bea 100644 --- a/docs/ANALYSIS.md +++ b/docs/ANALYSIS.md @@ -49,6 +49,16 @@ feature_store.history("AAPL", "rsi_14") These models are part of `CONTRACT_MODELS` and the exported JSON Schema. +## Fundamentals and events + +`core/janus/analysis/fundamentals.py` turns as-filed SEC facts into revenue, +margin, cash-flow, leverage, growth, EPS, PE, and book-value features. Only +facts published at or before `as_of` participate; a later restatement is visible +only to later views. Every feature carries the observation ids that produced it, +and missing inputs are listed explicitly. `detect_events` maps filing/news text +to earnings, M&A, litigation, insider, and guidance flags with the supporting +observation ids. + ## Regime baseline `classify_regime` is a rule-based baseline: diff --git a/docs/BACKLOG.md b/docs/BACKLOG.md index f27cbdb..6e29e3d 100644 --- a/docs/BACKLOG.md +++ b/docs/BACKLOG.md @@ -7,7 +7,7 @@ criteria. ## How to read this -**Current status (2026-11-24):** JAN-001, JAN-002, JAN-003, JAN-005, JAN-007, +**Current status (2026-11-24):** JAN-001, JAN-002, JAN-003, JAN-005, JAN-007, JAN-026, JAN-008, JAN-009, JAN-010, JAN-015, JAN-016, JAN-019, JAN-023, JAN-024, JAN-025, JAN-027, JAN-028, JAN-031 (tracker #39 / JAN-074), JAN-033, JAN-034, JAN-035, JAN-037, JAN-040, JAN-041, @@ -25,7 +25,7 @@ DSH UI wiring and cron are deferred to v0.2. See `schemas/janus.schema.json`, `tests/test_debrief.py`, `tests/test_persona_weighting.py`, `tests/test_mcp_service.py`, `tests/test_beliefbench.py`, `tests/test_gdelt.py`, `tests/test_rss.py`, `tests/test_scheduler.py`, -`tests/test_quality.py`, and `tests/test_copy.py`. +`tests/test_quality.py`, `tests/test_fundamentals.py`, and `tests/test_copy.py`. - **Milestones** are delivery windows, not promises: M0 foundation, M1 data and memory, M2 analysis, M3 forecast and review, M4 interface, M5 evaluation and diff --git a/tests/test_fundamentals.py b/tests/test_fundamentals.py new file mode 100644 index 0000000..2664f73 --- /dev/null +++ b/tests/test_fundamentals.py @@ -0,0 +1,161 @@ +from __future__ import annotations + +from datetime import date, datetime, timezone + +import pytest + +from janus.analysis.fundamentals import ( + compute_fundamental_features, + detect_events, +) +from janus.memory.models import Observation, ObservationKind +from janus.memory.store import JanusStore + + +def _filed(value: date) -> datetime: + return datetime.combine(value, datetime.min.time(), tzinfo=timezone.utc) + + +def _fact( + obs_id: str, + concept: str, + value: float, + period_end: str, + filed: str, + *, + entity_id: str = "ACME", +) -> Observation: + return Observation( + id=obs_id, + entity_id=entity_id, + kind=ObservationKind.fundamental, + source="sec_edgar", + published_at=_filed(date.fromisoformat(filed)), + valid_from=_filed(date.fromisoformat(period_end)), + value={ + "concept": concept, + "value": value, + "period_end": period_end, + "filed": filed, + "accn": obs_id, + }, + raw_hash=f"hash:{obs_id}", + ) + + +def _seed(store: JanusStore) -> None: + facts = [ + ("rev-2025", "RevenueFromContractWithCustomerExcludingAssessedTax", 100.0, "2025-12-31", "2026-01-15"), + ("rev-2024", "RevenueFromContractWithCustomerExcludingAssessedTax", 80.0, "2024-12-31", "2025-01-15"), + ("gp-2025", "GrossProfit", 40.0, "2025-12-31", "2026-01-15"), + ("op-2025", "OperatingIncomeLoss", 25.0, "2025-12-31", "2026-01-15"), + ("ni-2025", "NetIncomeLoss", 20.0, "2025-12-31", "2026-01-15"), + ("ni-2024", "NetIncomeLoss", 10.0, "2024-12-31", "2025-01-15"), + ("cfo-2025", "NetCashProvidedByUsedInOperatingActivities", 30.0, "2025-12-31", "2026-01-15"), + ("assets-2025", "Assets", 200.0, "2025-12-31", "2026-01-15"), + ("liab-2025", "Liabilities", 100.0, "2025-12-31", "2026-01-15"), + ("equity-2025", "StockholdersEquity", 100.0, "2025-12-31", "2026-01-15"), + ("debt-2025", "LongTermDebt", 20.0, "2025-12-31", "2026-01-15"), + ("eps-2025", "EarningsPerShareDiluted", 2.0, "2025-12-31", "2026-01-15"), + ] + for fact in facts: + store.insert_observation(_fact(*fact)) + + +def test_computes_fixture_ratios_with_provenance() -> None: + store = JanusStore(":memory:") + _seed(store) + report = compute_fundamental_features( + store, "ACME", datetime(2026, 2, 1, tzinfo=timezone.utc), price=40.0 + ) + + assert report.features["revenue"] == 100.0 + assert report.features["gross_margin"] == pytest.approx(0.4) + assert report.features["operating_margin"] == pytest.approx(0.25) + assert report.features["net_margin"] == pytest.approx(0.2) + assert report.features["cash_flow_margin"] == pytest.approx(0.3) + assert report.features["liabilities_to_assets"] == pytest.approx(0.5) + assert report.features["debt_to_equity"] == pytest.approx(0.2) + assert report.features["revenue_growth_yoy"] == pytest.approx(0.25) + assert report.features["net_income_growth_yoy"] == pytest.approx(1.0) + assert report.features["pe_ratio"] == pytest.approx(20.0) + assert report.features["book_value_per_share"] == pytest.approx(10.0) + assert report.provenance["net_margin"] == ["ni-2025", "rev-2025"] + assert report.missing == [] + + +def test_restatement_does_not_leak_backwards() -> None: + store = JanusStore(":memory:") + _seed(store) + store.insert_observation( + _fact( + "rev-restated", + "RevenueFromContractWithCustomerExcludingAssessedTax", + 120.0, + "2025-12-31", + "2026-02-15", + ) + ) + + before = compute_fundamental_features( + store, "ACME", datetime(2026, 2, 1, tzinfo=timezone.utc) + ) + after = compute_fundamental_features( + store, "ACME", datetime(2026, 3, 1, tzinfo=timezone.utc) + ) + + assert before.features["revenue"] == 100.0 + assert before.provenance["revenue"] == ["rev-2025"] + assert after.features["revenue"] == 120.0 + assert after.provenance["revenue"] == ["rev-restated"] + assert after.features["revenue_growth_yoy"] == pytest.approx(0.5) + + +def test_missing_facts_are_explicit() -> None: + store = JanusStore(":memory:") + store.insert_observation( + _fact("rev", "Revenues", 10.0, "2025-12-31", "2026-01-15") + ) + report = compute_fundamental_features( + store, "ACME", datetime(2026, 2, 1, tzinfo=timezone.utc) + ) + assert report.features["revenue"] == 10.0 + assert "net_margin" in report.missing + assert "revenue_growth_yoy" in report.missing + + +def test_as_of_must_be_timezone_aware() -> None: + with pytest.raises(ValueError, match="timezone-aware"): + compute_fundamental_features( + JanusStore(":memory:"), "ACME", datetime(2026, 1, 1) + ) + + +def test_event_flags_carry_observation_ids() -> None: + def event(obs_id: str, title: str, form: str = "") -> Observation: + return Observation( + id=obs_id, + entity_id="ACME", + kind=ObservationKind.news, + source="rss", + published_at=datetime(2026, 1, 1, tzinfo=timezone.utc), + value={"title": title, "form": form}, + raw_hash=obs_id, + ) + + events = detect_events( + [ + event("earn", "ACME reports quarterly results", "10-Q"), + event("deal", "ACME announces acquisition of BETA"), + event("suit", "ACME faces a lawsuit"), + event("insider", "Form 4 insider filing"), + event("guide", "ACME raises guidance"), + event("none", "A regular product update"), + ] + ) + assert events["earnings"] == ["earn"] + assert events["m&a"] == ["deal"] + assert events["litigation"] == ["suit"] + assert events["insider"] == ["insider"] + assert events["guidance"] == ["guide"] + assert "none" not in {item for ids in events.values() for item in ids}