Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/1423.added.md
Original file line number Diff line number Diff line change
@@ -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)
25 changes: 25 additions & 0 deletions docs/xbrl/concepts/standardization.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions edgar/xbrl/standardization/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())

Expand Down
91 changes: 90 additions & 1 deletion edgar/xbrl/standardization/reverse_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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,
Expand Down
189 changes: 189 additions & 0 deletions tests/standardization/test_members_of.py
Original file line number Diff line number Diff line change
@@ -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