edgartools icon indicating copy to clipboard operation
edgartools copied to clipboard

[FEATURE] Expose confidence, section, statement and is_total on MappingResult (currently only in private ReverseIndex._index)

Open synfonia-llc opened this issue 2 months ago • 6 comments

Feature Category

  • [x] New API functionality
  • [ ] Performance improvement
  • [x] Developer experience improvement
  • [ ] Documentation enhancement
  • [ ] Tool/utility addition

Problem Statement

Is your feature request related to a problem? Please describe.

ReverseIndex.lookup() returns a MappingResult that carries only standard_concepts, display_names, is_ambiguous, is_deprecated, deprecated_year and comment. The shipped gaap_mappings.json entry behind each result also records statement, section, is_total, confidence and company_count, and lookup() already reads is_total internally (it drops total concepts for tags with is_total is False). None of that reaches the caller. The only way to read it is the private get_reverse_index()._index dictionary.

This matters because confidence is the only signal that separates a sound mapping from a fuzzy one, and the two are indistinguishable in the public result. us-gaap:Revenues (confidence 1.0, 3,110 companies) and us-gaap:SalesAndMarketingExpense (mapped to OperatingIncomeLoss at confidence 0.313, 190 companies) come back in the same shape, both with is_ambiguous=False. A caller that wants to use only high-confidence mappings, or to group tags by statement section, has to reach into a private attribute whose layout can change without notice. Issue #914 shows what happens when low-confidence entries are treated as authoritative; callers need the signal to defend themselves.

Who would benefit from this feature?

  • [ ] Beginner Python users working with SEC filings
  • [x] Financial analysts and researchers
  • [x] Advanced developers building financial applications
  • [x] Data scientists working with financial datasets

Proposed Solution

Describe the solution you'd like

Add statement, section, is_total, confidence and (optionally) company_count to MappingResult, populated from the same entry after the industry override has been applied. Use Optional types with None defaults so the IFRS entries that carry no such metadata still work. This is additive: the new fields are appended after the existing ones and nothing existing changes.

get_standard_concept(context={'section', 'balance', 'statement_type', 'is_total'}) already accepts section and is_total as inputs, so exposing the same values as outputs makes the two halves of the API consistent.

Describe alternatives you've considered

Read get_reverse_index()._index[tag] directly. It works today, but it is private, it needs the same prefix and case normalization that lookup() does, and it bypasses the industry override, so it can disagree with lookup(tag, industry=...).

Use Case Example

How would you use this feature?

from edgar.xbrl.standardization.reverse_index import get_reverse_index

ri = get_reverse_index()
r = ri.lookup("us-gaap:SalesAndMarketingExpense")
if r and r.confidence >= 0.9:        # proposed field
    print(r.primary_concept, r.section, r.statement)
else:
    ...                              # treat as a candidate, not an answer

The reproduction below runs offline on EdgarTools 5.60.0 (it needs no SEC identity):

import dataclasses
import platform
import sys

import edgar
from edgar.xbrl.standardization.reverse_index import get_reverse_index

print("edgartools", edgar.__version__, "| Python", sys.version.split()[0], "|", platform.platform())

ri = get_reverse_index()
tags = [
    "us-gaap:Revenues",
    "us-gaap:RevenueFromContractWithCustomerExcludingAssessedTax",
    "us-gaap:PremiumsEarnedNet",
    "us-gaap:SalesAndMarketingExpense",
    "us-gaap:Assets",
]

r = ri.lookup("us-gaap:Revenues")
print("\nMappingResult fields   :", [f.name for f in dataclasses.fields(r)])
print("public attributes      :", [a for a in dir(r) if not a.startswith("_")])
for name in ("confidence", "section", "is_total", "statement", "company_count"):
    print(f"hasattr(result, {name!r:15}):", hasattr(r, name))

print("\nPublic lookup() result vs. the data it was built from (private _index):")
for t in tags:
    res = ri.lookup(t)
    raw = ri._index[t.split(":")[1]]
    print(f"\n{t}")
    print("  lookup() ->", res.standard_concepts, "ambiguous =", res.is_ambiguous)
    print("  _index   ->", {k: raw.get(k) for k in ("statement", "section", "is_total", "confidence", "company_count")})

Actual output:

edgartools 5.60.0 | Python 3.14.4 | Windows-11-10.0.26200-SP0

MappingResult fields   : ['standard_concepts', 'display_names', 'is_ambiguous', 'is_deprecated', 'deprecated_year', 'comment']
public attributes      : ['comment', 'deprecated_year', 'display_names', 'is_ambiguous', 'is_deprecated', 'primary_concept', 'primary_display_name', 'standard_concepts']
hasattr(result, 'confidence'   ): False
hasattr(result, 'section'      ): False
hasattr(result, 'is_total'     ): False
hasattr(result, 'statement'    ): False
hasattr(result, 'company_count'): False

Public lookup() result vs. the data it was built from (private _index):

us-gaap:Revenues
  lookup() -> ['Revenue'] ambiguous = False
  _index   -> {'statement': 'IncomeStatement', 'section': 'Revenue', 'is_total': True, 'confidence': 1.0, 'company_count': 3110}

us-gaap:RevenueFromContractWithCustomerExcludingAssessedTax
  lookup() -> ['Revenue'] ambiguous = False
  _index   -> {'statement': 'IncomeStatement', 'section': 'Revenue', 'is_total': True, 'confidence': 1.0, 'company_count': 3467}

us-gaap:PremiumsEarnedNet
  lookup() -> ['Revenue'] ambiguous = False
  _index   -> {'statement': 'IncomeStatement', 'section': 'Revenue', 'is_total': True, 'confidence': 0.5, 'company_count': 131}

us-gaap:SalesAndMarketingExpense
  lookup() -> ['OperatingIncomeLoss'] ambiguous = False
  _index   -> {'statement': 'IncomeStatement', 'section': 'Operating Income', 'is_total': True, 'confidence': 0.313, 'company_count': 190}

us-gaap:Assets
  lookup() -> ['Assets'] ambiguous = False
  _index   -> {'statement': 'BalanceSheet', 'section': 'Totals', 'is_total': True, 'confidence': 1.0, 'company_count': 8929}

Implementation Considerations

Complexity Level:

  • [x] Simple (minor API addition)
  • [ ] Moderate (new functionality with existing patterns)
  • [ ] Complex (significant architectural changes)

Backwards Compatibility:

  • [x] This feature maintains backwards compatibility
  • [ ] This feature might break existing code (please explain below)
  • [ ] Unsure about compatibility impact

MappingResult is constructed in one place, at the end of ReverseIndex.lookup() in edgar/xbrl/standardization/reverse_index.py. The new values come from the entry already in scope (after _apply_industry_override). Defaults on the new fields keep any external code that constructs a MappingResult working.

Additional Context

Environment: EdgarTools 5.60.0 (main), Python 3.14.4, Windows 11. The reproduction is offline.

For 10-K and 10-Q extraction, the lookup is how a tag a filer used (often a custom or unusual one) gets a candidate standard concept. Callers who build charts or statements from those candidates need to know whether the candidate is a firm match or a 0.3 to 0.5 guess, and whether it sits in a section such as Revenue or Totals. Today they either trust every result equally or read the private index.

This is the data-access half of the same concern as #914: that fix filters on is_total inside lookup(), but a caller cannot apply the same judgment to the remaining entries because the metadata stays hidden.

Related Issues/Features:

  • #914: line-item tags mapped to balance-sheet total concepts (closed). It fixed one symptom by using is_total internally; this request exposes the underlying metadata so callers can make the same distinction themselves.

Feature requests are evaluated based on EdgarTools' core principles: Simple yet powerful, accurate financials, beginner-friendly, and joyful UX.

synfonia-llc avatar Oct 05 '26 22:10 synfonia-llc

Note from the reporter: this issue was submitted with Claude, through the GitHub CLI, so the issue template's labels were not applied automatically. It is a Feature Request and should be labeled enhancement. Sorry for the extra triage step, and thank you!

synfonia-llc avatar Oct 05 '26 22:10 synfonia-llc

One thing to know before exposing these fields: some of the values behind them don't yet mean what the names suggest.

  • confidence: the 63 entries corrected by hand in 7434b08e and 864beede kept their generated confidence (0.307-0.422), so a caller filtering on confidence would discard verified fixes. 564 entries are placeholders (company_count 0, null years, confidence 0.4), and 1,504 sit at exactly 0.5.
  • is_total: a usage statistic, not a property of the element. 572 live entries flagged true are components (CommonStockValue, InterestPaidNet), and every industry override sets it false.
  • is_deprecated: never set. No entry carries deprecated, although 393 bare keys were removed from us-gaap (105 of them in 2024-2026) and 56 more are deprecated but still in the 2026 schema.
  • company_count: counted by local name, so 16 keys report use years after FASB removed them.

Regenerating _metadata and usage keyed by qualified concept, giving hand-verified entries confidence 1.0, and filling deprecated from the FASB releases would make the exposed fields trustworthy. Details are in #1446 (mapping data clean-up) and #1444 (the total guard).

synfonia-llc avatar Oct 06 '26 10:10 synfonia-llc

@dgunning, here is our current thinking on the root cause, proposed behavior, and coordination with other issues.

Root Cause:

MappingResult omits metadata already held by the reverse index, so callers cannot inspect those annotations and their origins through the public result.

Proposed Behavior:

Expose the five optional metadata fields, the exact mapping key, the applied industry and each field's base, override or missing origin. Preserve stored values and existing lookup exclusions, documenting that confidence has mixed origins and usage counts include placeholders. These annotations do not establish financial certainty, rank current candidates or prove that a component is a total.

Coordination:

Keep #1422 separate, coordinating metadata meanings and any review-marker or regeneration policy with #1446. Let #1423 reuse the result for family discovery, and keep contextual resolution with #1452. Preserve #1444's guards landed in #1808.

Below, please find the full design document. Please let me know your thoughts.

Brian

Attachment: design-public.md, Proposal for #1422: expose mapping metadata with its provenance and limits.

AI assistance: Codex; GPT-6.1 Sol (High) for current-source scouting, an offline metadata probe, final writing, and the metadata-definition revision; GPT-6 Astra (Max) for architecture and design drafting, with a separate agent providing independent financial statement review of the proposed metadata and source-preservation contract; Claude Opus 5.5 (High) for adversarial review and independent resolution.

synfonia-llc avatar Oct 27 '26 11:10 synfonia-llc

Hi Dwight, I would love to help out with this!

arjunarun65164 avatar Nov 06 '26 16:11 arjunarun65164

Hey Arun, thanks for the offer. Go ahead and implement, following generally the design in Brian's note. Keep us informed on your progress.

dgunning avatar Nov 09 '26 01:11 dgunning

@dgunning Sent a pull request with my updates - happy to expand more on my changes if necessary!

arjunarun65164 avatar Nov 10 '26 04:11 arjunarun65164