From bd32e42bbeb4841468d31b38a00d2897f04be6df Mon Sep 17 00:00:00 2001 From: Arjun Arun <77373370+arjunarun65164@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:54:49 -0500 Subject: [PATCH 1/2] feat(xbrl): add reverse index family discovery --- changelog.d/1423.added.md | 1 + docs/xbrl/concepts/standardization.md | 25 +++ edgar/xbrl/standardization/core.py | 5 +- edgar/xbrl/standardization/reverse_index.py | 91 +++++++++- tests/standardization/test_members_of.py | 189 ++++++++++++++++++++ 5 files changed, 308 insertions(+), 3 deletions(-) create mode 100644 changelog.d/1423.added.md create mode 100644 tests/standardization/test_members_of.py diff --git a/changelog.d/1423.added.md b/changelog.d/1423.added.md new file mode 100644 index 000000000..812ac6c7f --- /dev/null +++ b/changelog.d/1423.added.md @@ -0,0 +1 @@ +**`members_of()` lists the XBRL tags mapped to a standard concept.** Each record includes the stored key and its lookup result. The `Revenue` family includes `PremiumsEarnedNet`, the tag for UnitedHealth's $308,810 million in FY2024 premiums (10-K accession 0000731766-25-000063). (GH #1423) diff --git a/docs/xbrl/concepts/standardization.md b/docs/xbrl/concepts/standardization.md index 1f66b0b72..e49d6023f 100644 --- a/docs/xbrl/concepts/standardization.md +++ b/docs/xbrl/concepts/standardization.md @@ -619,6 +619,31 @@ The new fields are appended with defaults, so existing six-argument `MappingResu construction still works. `dataclasses.asdict()` now includes the new fields; consumers with strict serialized schemas should account for that additive change. +### Discovering Tags for a Standard Concept + +Use `members_of()` with an exact standard concept identifier from +`MappingResult.standard_concepts`. For example, the `Revenue` family +includes the tag for earned premiums: + +```python +from edgar.xbrl.standardization.reverse_index import members_of + +for member in members_of("Revenue"): + if member.mapping_key == "PremiumsEarnedNet": + print(member.mapping_key, member.result.standard_concepts) + # PremiumsEarnedNet ['Revenue'] +``` + +Each record keeps the exact stored key and the full lookup result, including +any other surviving candidates. Inspect `qualified_tag` when you need the +taxonomy-family spelling. A bare mapping key can have unknown qualification. +Pass `industry=` to apply the same overrides as `lookup()`. + +Families can contain both totals and components. The results are sorted by +stored key for repeatable inspection. Check the filing context before +selecting, comparing, or adding amounts. A tag's absence from a family +tells you nothing about whether a filing reports that fact or whether its value is zero. + ### Checking Coverage ```python diff --git a/edgar/xbrl/standardization/core.py b/edgar/xbrl/standardization/core.py index d18bf1f06..2b31b34ad 100644 --- a/edgar/xbrl/standardization/core.py +++ b/edgar/xbrl/standardization/core.py @@ -497,13 +497,14 @@ def get_display_name(self, company_concept: str, context: Optional[Dict] = None) def get_company_concepts(self, standard_concept: str) -> Set[str]: """ - Get all company concepts mapped to a standard concept. + Get the company concept keys stored in this legacy mapping store. Args: standard_concept: The standard concept Returns: - Set of company concepts mapped to the standard concept + Set of legacy keys for the standard concept. Use ReverseIndex.members_of() + to discover effective mappings in the reverse index. """ return self.mappings.get(standard_concept, set()) diff --git a/edgar/xbrl/standardization/reverse_index.py b/edgar/xbrl/standardization/reverse_index.py index 5473e384b..1505f2cf2 100644 --- a/edgar/xbrl/standardization/reverse_index.py +++ b/edgar/xbrl/standardization/reverse_index.py @@ -21,7 +21,7 @@ import json import logging import os -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from typing import Dict, List, Optional, Tuple from edgar.exceptions import ValidationError @@ -139,6 +139,23 @@ def primary_display_name(self) -> Optional[str]: return self.display_names[0] if self.display_names else None +@dataclass(frozen=True) +class MappingMember: + """One stored key and its effective mapping in a standard concept family.""" + + mapping_key: str + """Exact key in the mapping data.""" + + qualified_tag: Optional[str] + """Taxonomy-family spelling when established by the mapping key.""" + + identity_status: str + """Whether the mapping identity is qualified or unqualified.""" + + result: MappingResult + """Independent lookup result with all surviving candidates and metadata.""" + + class ReverseIndex: """ Reverse index for fast XBRL tag to standard concept lookups. @@ -446,6 +463,71 @@ def lookup(self, xbrl_tag: str, industry: Optional[str] = None) -> Optional[Mapp metadata_origins=metadata_origins, ) + def members_of( + self, standard_concept: str, *, industry: Optional[str] = None + ) -> tuple[MappingMember, ...]: + """Discover effective mappings for an exact standard concept identifier. + + An identifier is a value used in `MappingResult.standard_concepts`, + such as `Revenue`. A known family with no accepted members returns an + empty tuple. Industry overrides follow the same rules as `lookup()`. + + Results are sorted by stored key for repeatable inspection. A family + can contain both totals and components. Membership and order do not + imply that tags are interchangeable or can be added together. Absence + from the family does not establish that a filed fact is absent or zero. + + Raises: + TypeError: If standard_concept is not a string. + ValidationError: If the identifier is empty or unknown. This is a ValueError. + """ + if not isinstance(standard_concept, str): + raise TypeError("standard_concept must be a string") + if not standard_concept or not self._knows_standard_concept(standard_concept): + raise ValidationError( + f"Unknown standard concept {standard_concept!r}.", + parameter="standard_concept", + invalid_value=standard_concept, + suggestions=["Use an exact identifier from MappingResult.standard_concepts, such as 'Revenue'."], + ) + + members = [] + for key in sorted(self._index): + result = self.lookup(key, industry=industry) + if result is None or standard_concept not in result.standard_concepts: + continue + + qualified_tag = self._qualified_member_tag(key) + # Forward lookup can return the stored candidate list directly. + members.append(MappingMember( + mapping_key=key, + qualified_tag=qualified_tag, + identity_status="qualified" if qualified_tag else "unqualified", + result=replace(result, standard_concepts=result.standard_concepts.copy()), + )) + return tuple(members) + + def _knows_standard_concept(self, concept: str) -> bool: + if concept in self._display_names or concept in self._embedded_display_names: + return True + return any( + concept in entry.get("standard_tags", ()) + or any( + concept in override.get("standard_tags", ()) + for override in (entry.get("industry_overrides") or {}).values() + ) + for entry in self._index.values() + ) + + @staticmethod + def _qualified_member_tag(key: str) -> Optional[str]: + if _is_ifrs_tag(key): + return _canonical_ifrs_key(key).replace("_", ":", 1) + for taxonomy in ("us-gaap", "srt", "dei"): + if key.startswith((f"{taxonomy}:", f"{taxonomy}_")): + return f"{taxonomy}:{key[len(taxonomy) + 1:]}" + return None + def _may_resolve_to(self, key: str, entry: dict, concept: str, display_name: str) -> bool: """Whether the index entry `key` may resolve to `concept` (the total guard in lookup()).""" members = self._total_members.get(concept) @@ -882,6 +964,13 @@ def lookup(xbrl_tag: str) -> Optional[MappingResult]: return get_reverse_index().lookup(xbrl_tag) +def members_of( + standard_concept: str, *, industry: Optional[str] = None +) -> tuple[MappingMember, ...]: + """Discover effective mappings using the default reverse index.""" + return get_reverse_index().members_of(standard_concept, industry=industry) + + def get_standard_concept( xbrl_tag: str, context: Optional[Dict] = None, diff --git a/tests/standardization/test_members_of.py b/tests/standardization/test_members_of.py new file mode 100644 index 000000000..5845612e5 --- /dev/null +++ b/tests/standardization/test_members_of.py @@ -0,0 +1,189 @@ +"""Verify public discovery of effective XBRL mapping families. + +GitHub Issue: https://github.com/dgunning/edgartools/issues/1423 +""" + +import json +from decimal import Decimal +from pathlib import Path + +import pytest +from lxml import html + +from edgar.documents.strategies.xbrl_extraction import XBRLExtractor +from edgar.xbrl.standardization import get_default_store, reverse_index +from edgar.xbrl.standardization.reverse_index import ReverseIndex + +pytestmark = pytest.mark.fast + + +@pytest.fixture(scope="module") +def index(): + return ReverseIndex() + + +@pytest.fixture +def build_index(tmp_path): + def build(entries, *, totals=None, labels=None): + files = [] + for name, data in ( + ("mappings.json", entries), + ("display.json", labels or {}), + ("totals.json", {"totals": totals or {}}), + ): + path = tmp_path / name + path.write_text(json.dumps(data), encoding="utf-8") + files.append(str(path)) + return ReverseIndex(*files) + + return build + + +def test_members_match_effective_forward_lookup(build_index): + entries = { + "Zulu": {"standard_tags": ["Revenue", "OtherRevenue"], "ambiguous": True}, + "Component": {"standard_tags": ["Revenue", "OtherRevenue"], "confidence": 1.0, "is_total": True}, + "Alpha": {"standard_tags": ["Revenue"]}, + "CommonStockSharesAuthorized": {"standard_tags": ["Revenue"]}, + } + index = build_index(entries, totals={"Revenue": ["Alpha", "Zulu", "CommonStockSharesAuthorized"]}) + expected = {} + for key in sorted(entries): + result = index.lookup(key) + if result is not None and "Revenue" in result.standard_concepts: + expected[key] = result + assert tuple(expected) == ("Alpha", "Zulu") + + members = index.members_of("Revenue") + assert isinstance(members, tuple) + assert tuple(member.mapping_key for member in members) == tuple(expected) + assert [member.result for member in members] == list(expected.values()) + assert members[1].result.standard_concepts == ["Revenue", "OtherRevenue"] + assert members[1].result.is_ambiguous is True + assert index.lookup("Component").standard_concepts == ["OtherRevenue"] + + +def test_shipped_revenue_members_respect_total_guard(index): + keys = {member.mapping_key for member in index.members_of("Revenue")} + assert "Revenues" in keys + assert "SalesReturnsGoods" not in keys + + +def test_industry_changes_membership_and_preserves_provenance(build_index): + index = build_index( + { + "Premiums": { + "standard_tags": ["OtherRevenue"], + "industry_overrides": {"Insur": {"standard_tags": ["Revenue", "InsuranceRevenue"], "confidence": 0.8}}, + }, + "Sales": { + "standard_tags": ["Revenue"], + "industry_overrides": {"Insur": {"standard_tags": ["OtherRevenue"]}}, + }, + } + ) + separate_index = build_index({"Fees": {"standard_tags": ["Revenue"]}}) + + assert [member.mapping_key for member in index.members_of("Revenue")] == ["Sales"] + assert [member.mapping_key for member in index.members_of("Revenue", industry="Banks")] == ["Sales"] + (member,) = index.members_of("Revenue", industry="Insur") + assert member.mapping_key == "Premiums" + assert member.result == index.lookup("Premiums", industry="Insur") + assert member.result.standard_concepts == ["Revenue", "InsuranceRevenue"] + assert member.result.applied_industry == "Insur" + assert member.result.metadata_origins["confidence"] == "industry_override" + assert index.members_of("InsuranceRevenue") == () + assert [member.mapping_key for member in separate_index.members_of("Revenue", industry="Insur")] == ["Fees"] + assert [member.mapping_key for member in index.members_of("Revenue", industry="Insur")] == ["Premiums"] + + +def test_member_identity_preserves_distinct_keys(build_index): + index = build_index({key: {"standard_tags": ["TradeReceivables"]} for key in ("us-gaap:Example", "ifrs-full_Example", "Example")}) + members = index.members_of("TradeReceivables") + assert [(member.mapping_key, member.qualified_tag, member.identity_status) for member in members] == [ + ("Example", None, "unqualified"), + ("ifrs-full_Example", "ifrs-full:Example", "qualified"), + ("us-gaap:Example", "us-gaap:Example", "qualified"), + ] + + +@pytest.mark.parametrize("value", [None, 42]) +def test_non_string_identifier_raises(index, value): + with pytest.raises(TypeError): + index.members_of(value) + + +@pytest.mark.parametrize("value", ["", "Revenues", "NetIncomeLoss", "Total Sales"]) +def test_unknown_identifier_raises(build_index, value): + index = build_index({"Example": {"standard_tags": ["Revenue"]}}, labels={"Revenue": "Total Sales"}) + with pytest.raises(ValueError, match=r"(?i)standard concept"): + index.members_of(value) + + +def test_known_family_without_members_returns_empty_tuple(build_index): + index = build_index({}, labels={"Revenue": "Total Sales"}) + assert index.members_of("Revenue") == () + + +def test_mutating_member_result_does_not_affect_later_answers(build_index): + index = build_index({"Example": {"standard_tags": ["Revenue"], "confidence": 0.8}}) + (member,) = index.members_of("Revenue") + member.result.standard_concepts.append("Changed") + member.result.display_names.clear() + member.result.metadata_origins["confidence"] = "changed" + + assert index.lookup("Example").standard_concepts == ["Revenue"] + (later,) = index.members_of("Revenue") + assert later.result.standard_concepts == ["Revenue"] + assert later.result.display_names == ["Revenue"] + assert later.result.metadata_origins["confidence"] == "base" + + +def test_module_level_api_matches_class(build_index, monkeypatch): + index = build_index( + { + "Premiums": { + "standard_tags": ["OtherRevenue"], + "industry_overrides": {"Insur": {"standard_tags": ["Revenue"]}}, + } + } + ) + monkeypatch.setattr(reverse_index, "_default_index", index) + members = reverse_index.members_of("Revenue", industry="Insur") + assert members == reverse_index.get_reverse_index().members_of("Revenue", industry="Insur") + assert members + assert all(isinstance(member, reverse_index.MappingMember) for member in members) + + +def test_legacy_store_still_returns_legacy_revenue_keys(): + assert get_default_store().get_company_concepts("Revenue") == { + "us-gaap_OperatingRevenue", + "us-gaap_Revenue", + "us-gaap_Revenues", + "us-gaap_SalesRevenueNet", + } + + +def test_unitedhealth_2024_premiums_are_a_revenue_member(index): + """UnitedHealth FY2024 10-K, accession 0000731766-25-000063, page 41. + + Consolidated Statements of Operations, Premiums, $308,810 million. + https://www.sec.gov/Archives/edgar/data/731766/000073176625000063/unh-20241231.htm + """ + fixture = Path(__file__).parents[1] / "fixtures/html/unh/10k/unh-10-k-2025-02-27.html" + root = html.parse(str(fixture)) + elements = root.xpath('//*[@name="us-gaap:PremiumsEarnedNet" and @contextref="c-1"]') + assert len(elements) == 1 + fact = XBRLExtractor().extract_fact(elements[0]) + assert fact is not None + assert fact.context["entity"] == "0000731766" + assert fact.context["start_date"] == "2024-01-01" + assert fact.context["end_date"] == "2024-12-31" + assert fact.unit == "USD" + assert Decimal(fact.value) == Decimal("308810000000") + + result = index.lookup(fact.concept) + assert result is not None + assert result.mapping_key == "PremiumsEarnedNet" + members = {member.mapping_key: member.result for member in index.members_of("Revenue")} + assert members["PremiumsEarnedNet"] == result From c97aecd26975c6c75b48afa772cb002404df2569 Mon Sep 17 00:00:00 2001 From: Arjun Arun <77373370+arjunarun65164@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:09:35 -0500 Subject: [PATCH 2/2] Address review feedback on XBRL mapping family discovery --- docs/xbrl/concepts/standardization.md | 9 +++-- edgar/xbrl/standardization/reverse_index.py | 37 ++++++++++----------- tests/standardization/test_members_of.py | 29 +++++++++++++--- 3 files changed, 49 insertions(+), 26 deletions(-) diff --git a/docs/xbrl/concepts/standardization.md b/docs/xbrl/concepts/standardization.md index e49d6023f..c951a4c9f 100644 --- a/docs/xbrl/concepts/standardization.md +++ b/docs/xbrl/concepts/standardization.md @@ -636,8 +636,13 @@ for member in members_of("Revenue"): Each record keeps the exact stored key and the full lookup result, including any other surviving candidates. Inspect `qualified_tag` when you need the -taxonomy-family spelling. A bare mapping key can have unknown qualification. -Pass `industry=` to apply the same overrides as `lookup()`. +taxonomy-family spelling. A bare mapping key has `qualified_tag=None`. +Pass `industry=` to apply the same overrides as `lookup()`. If you pass an +unknown identifier, the error suggests similar known identifiers when available. + +This API reflects the XBRL statement mappings. `company.get_facts()` uses a +separate mapping path, and its `get_revenue()` method selects facts using that +path's rules. Families can contain both totals and components. The results are sorted by stored key for repeatable inspection. Check the filing context before diff --git a/edgar/xbrl/standardization/reverse_index.py b/edgar/xbrl/standardization/reverse_index.py index 1505f2cf2..76f727cc7 100644 --- a/edgar/xbrl/standardization/reverse_index.py +++ b/edgar/xbrl/standardization/reverse_index.py @@ -22,6 +22,7 @@ import logging import os from dataclasses import dataclass, field, replace +from difflib import get_close_matches from typing import Dict, List, Optional, Tuple from edgar.exceptions import ValidationError @@ -147,10 +148,7 @@ class MappingMember: """Exact key in the mapping data.""" qualified_tag: Optional[str] - """Taxonomy-family spelling when established by the mapping key.""" - - identity_status: str - """Whether the mapping identity is qualified or unqualified.""" + """Taxonomy-family spelling when established by the key, or None for a bare key.""" result: MappingResult """Independent lookup result with all surviving candidates and metadata.""" @@ -483,12 +481,17 @@ def members_of( """ if not isinstance(standard_concept, str): raise TypeError("standard_concept must be a string") - if not standard_concept or not self._knows_standard_concept(standard_concept): + known_concepts = self._known_standard_concepts() + if not standard_concept or standard_concept not in known_concepts: + matches = get_close_matches(standard_concept, known_concepts) + suggestion = "Use an exact identifier from MappingResult.standard_concepts, such as 'Revenue'." + if matches: + suggestion = f"Did you mean {', '.join(matches)}? {suggestion}" raise ValidationError( f"Unknown standard concept {standard_concept!r}.", parameter="standard_concept", invalid_value=standard_concept, - suggestions=["Use an exact identifier from MappingResult.standard_concepts, such as 'Revenue'."], + suggestions=[suggestion], ) members = [] @@ -497,27 +500,21 @@ def members_of( if result is None or standard_concept not in result.standard_concepts: continue - qualified_tag = self._qualified_member_tag(key) # Forward lookup can return the stored candidate list directly. members.append(MappingMember( mapping_key=key, - qualified_tag=qualified_tag, - identity_status="qualified" if qualified_tag else "unqualified", + qualified_tag=self._qualified_member_tag(key), result=replace(result, standard_concepts=result.standard_concepts.copy()), )) return tuple(members) - def _knows_standard_concept(self, concept: str) -> bool: - if concept in self._display_names or concept in self._embedded_display_names: - return True - return any( - concept in entry.get("standard_tags", ()) - or any( - concept in override.get("standard_tags", ()) - for override in (entry.get("industry_overrides") or {}).values() - ) - for entry in self._index.values() - ) + def _known_standard_concepts(self) -> set[str]: + concepts = set(self._display_names) + for entry in self._index.values(): + concepts.update(entry.get("standard_tags", ())) + for override in (entry.get("industry_overrides") or {}).values(): + concepts.update(override.get("standard_tags", ())) + return concepts @staticmethod def _qualified_member_tag(key: str) -> Optional[str]: diff --git a/tests/standardization/test_members_of.py b/tests/standardization/test_members_of.py index 5845612e5..3dd84626f 100644 --- a/tests/standardization/test_members_of.py +++ b/tests/standardization/test_members_of.py @@ -100,10 +100,10 @@ def test_industry_changes_membership_and_preserves_provenance(build_index): def test_member_identity_preserves_distinct_keys(build_index): index = build_index({key: {"standard_tags": ["TradeReceivables"]} for key in ("us-gaap:Example", "ifrs-full_Example", "Example")}) members = index.members_of("TradeReceivables") - assert [(member.mapping_key, member.qualified_tag, member.identity_status) for member in members] == [ - ("Example", None, "unqualified"), - ("ifrs-full_Example", "ifrs-full:Example", "qualified"), - ("us-gaap:Example", "us-gaap:Example", "qualified"), + assert [(member.mapping_key, member.qualified_tag) for member in members] == [ + ("Example", None), + ("ifrs-full_Example", "ifrs-full:Example"), + ("us-gaap:Example", "us-gaap:Example"), ] @@ -120,6 +120,27 @@ def test_unknown_identifier_raises(build_index, value): index.members_of(value) +@pytest.mark.parametrize( + "value, expected", + [("Revenues", "Revenue"), ("NetIncomeLoss", "NetIncome"), ("TotalAssets", "Assets")], +) +def test_unknown_identifier_suggests_known_concepts(index, value, expected): + with pytest.raises(ValueError, match=rf"Did you mean .*\b{expected}\b"): + index.members_of(value) + + +def test_suggestions_include_registry_and_override_concepts(build_index): + index = build_index( + {"Example": {"industry_overrides": {"Insur": {"standard_tags": ["UnderwritingIncome"]}}}}, + labels={"RegistryOnly": "Registry Label"}, + ) + + with pytest.raises(ValueError, match=r"Did you mean RegistryOnly"): + index.members_of("RegistryOnl") + with pytest.raises(ValueError, match=r"Did you mean UnderwritingIncome"): + index.members_of("UnderwritingIncom") + + def test_known_family_without_members_returns_empty_tuple(build_index): index = build_index({}, labels={"Revenue": "Total Sales"}) assert index.members_of("Revenue") == ()