Skip to content

Commit 068b335

Browse files
dgunningclaude
andauthored
fix(xbrl): require section evidence for three current/noncurrent entries (#2071)
OtherBorrowings, AdvancesFromFederalHomeLoanBanks and RestrictedCashAndCashEquivalents each map to one current and one noncurrent concept. With no section, get_standard_concept() took the first candidate, so BXP's unsecured term loans (FY2025 10-K 0001037540-26-000006, $797,053,000 / $798,813,000, an unclassified REIT balance sheet) became ShortTermDebt. These three now resolve only from the row's own classified section or a classified ancestor and otherwise return None; the row keeps its filed label and values, get_display_name() agrees, and lookup() still lists both candidates. No mapping data changes. _derive_section_from_parent() no longer uses an ambiguous parent's context-free first candidate. A parent that states no side passes on its nearest classified ancestor's (conflicts and cycles give none), a ...CurrentAndNoncurrent parent states no side, noncurrent spellings are matched before the current ones they contain, and a single-candidate parent outside the balance sheet role (LongTermDebtNoncurrent in a debt note) still states its side. Stitching no longer merges a restricted-cash aggregate with its current or noncurrent portion on name containment, even when a common period agrees. The GH #1685 guard is unchanged. Across the 65 committed XBRL fixture sets, 27 of 87,716 standardized rows change: 15 target rows lose a first-candidate concept, 12 children now match their classified parent (XOM deferred taxes, debt discounts under long-term debt). Design and BXP case by synfonia-llc on GH #1438. Refs #1438 Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent a1aaa1d commit 068b335

19 files changed

Lines changed: 557 additions & 76 deletions

‎changelog.d/1438.fixed.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
**Debt and restricted-cash rows with no balance sheet side were given one by candidate order.** `OtherBorrowings`, `AdvancesFromFederalHomeLoanBanks` and `RestrictedCashAndCashEquivalents` took their first candidate when no section said current or noncurrent, so BXP's $797,053K unsecured term loans standardized as short-term debt. They now get no standard concept unless the row or a classified parent gives a side. (GH #1438)

‎docs/upgrade/6.5.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@ see [Getting help](6.0.md#getting-help).
1717
| `xbrl.current_period.statement_of_equity()` | filtered to the period-end instant: the opening balance showed the closing one, and no flow rows (net income, dividends, buybacks) | the fiscal year's duration (the quarter in a 10-Q), with the opening balance from the prior period end | Apple FY2023 10-K 0000320193-23-000106: opening equity $62,146M → $50,672M; 8 rows → 24 (GH #429) |
1818
| `xbrl.current_period.cash_flow_statement()` on a 10-Q | the three-month duration | the year-to-date duration, as the 10-Q files it | Tesla Q2 2024 10-Q 0001628280-24-032662: 2 rows → 36 (GH #429) |
1919
| `current_period` statements' `get_dataframe()` and `as_statement=False`: an instant balance row under a duration | left out | the balance the rendered table shows: the opening or closing instant | Apple FY2023 10-K 0000320193-23-000106: cash flow gains beginning cash $24,977M and ending cash $30,737M (GH #429) |
20+
| `standard_concept` of an `OtherBorrowings`, `AdvancesFromFederalHomeLoanBanks` or `RestrictedCashAndCashEquivalents` row with no current or noncurrent section | the first candidate (`ShortTermDebt`, `LongTermDebt`, `RestrictedCashCurrent`) | none; the row keeps its filed label and values, and `lookup()` still lists both candidates | BXP FY2025 10-K 0001037540-26-000006: "Unsecured term loans, net" ($797,053K) `ShortTermDebt` → none (GH #1438) |
21+
| `standard_concept` of a row whose calculation parent maps to both sides | the side of the parent's first candidate | the side of the parent's nearest classified ancestor | ExxonMobil FY2022 10-K 0000034088-23-000020: deferred tax on PP&E ($25,607M) `DeferredTaxCurrentLiabilities` → `DeferredTaxNonCurrentLiabilities`, matching its parent (GH #1438) |
22+
| Stitched statements: a restricted-cash aggregate (`RestrictedCashAndCashEquivalents`) and its current portion (`...AtCarryingValue`) from different filings | one row when they shared a standard concept | two rows | (GH #1438) |
2023

2124
### Quarterly financials
2225

‎edgar/xbrl/standardization/core.py‎

Lines changed: 128 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,15 @@
99
import json
1010
import logging
1111
import os
12+
from collections import defaultdict
1213
from difflib import SequenceMatcher
1314
from enum import Enum
1415
from typing import Any, Dict, List, Optional, Set, Tuple
1516

1617
import pandas as pd
1718

19+
from .reverse_index import section_side
20+
1821
# Module-level logger (avoid creating logger inside hot paths)
1922
logger = logging.getLogger(__name__)
2023

@@ -771,88 +774,137 @@ def _should_preserve_label(original_label: str, standardized_label: str) -> bool
771774
return False
772775

773776

774-
def _derive_section_from_parent(calculation_parent: str, statement_type: str) -> Optional[str]:
777+
# Parent totals that state a section. The generic totals (Assets, Liabilities,
778+
# LiabilitiesAndStockholdersEquity) name a section but no side, so they never
779+
# decide current vs noncurrent for a child.
780+
_PARENT_TO_SECTION = {
781+
"assetscurrent": "Current Assets",
782+
"currentassets": "Current Assets",
783+
"assetsnoncurrent": "Non-Current Assets",
784+
"noncurrentassets": "Non-Current Assets",
785+
"liabilitiescurrent": "Current Liabilities",
786+
"currentliabilities": "Current Liabilities",
787+
"liabilitiesnoncurrent": "Non-Current Liabilities",
788+
"noncurrentliabilities": "Non-Current Liabilities",
789+
"stockholdersequity": "Equity",
790+
"stockholdersequityincludingportionattributabletononcontrollinginterest": "Equity",
791+
"equity": "Equity",
792+
"assets": "Assets",
793+
"liabilities": "Liabilities",
794+
"liabilitiesandstockholdersequity": "Liabilities and Equity",
795+
}
796+
797+
# Substring patterns, noncurrent first: 'othernoncurrentassets' contains
798+
# 'currentassets', so testing the current spelling first read it as current.
799+
_PARENT_SECTION_PATTERNS = (
800+
("assetsnoncurrent", "Non-Current Assets"),
801+
("noncurrentassets", "Non-Current Assets"),
802+
("liabilitiesnoncurrent", "Non-Current Liabilities"),
803+
("noncurrentliabilities", "Non-Current Liabilities"),
804+
("assetscurrent", "Current Assets"),
805+
("currentassets", "Current Assets"),
806+
("liabilitiescurrent", "Current Liabilities"),
807+
("currentliabilities", "Current Liabilities"),
808+
("stockholdersequity", "Equity"),
809+
("equity", "Equity"),
810+
("liabilitiesandstockholdersequity", "Liabilities and Equity"),
811+
("assets", "Assets"),
812+
("liabilities", "Liabilities"),
813+
)
814+
815+
816+
def _bare_parent_name(concept: str) -> str:
817+
name = concept.lower()
818+
if ":" in name:
819+
name = name.split(":")[-1]
820+
if "_" in name:
821+
name = name.split("_")[-1]
822+
return name
823+
824+
825+
def _section_from_parent_name(calculation_parent: str, statement_type: str) -> Optional[str]:
826+
"""The section one parent concept states by itself, without its own parents."""
827+
name = _bare_parent_name(calculation_parent)
828+
if name in _PARENT_TO_SECTION:
829+
return _PARENT_TO_SECTION[name]
830+
831+
# An ...CurrentAndNoncurrent element is on neither side; 'Current' inside
832+
# its name is not a section (GH #1438).
833+
unclassified = "currentandnoncurrent" in name
834+
for pattern, section in _PARENT_SECTION_PATTERNS:
835+
if unclassified and section_side(section):
836+
continue
837+
if pattern in name:
838+
return section
839+
840+
# A parent with a single standard concept states that concept's section.
841+
# A parent with several does not: its context-free answer is only the
842+
# first candidate, which is not evidence for the child (GH #1438).
843+
try:
844+
reverse_index = _get_reverse_index()
845+
result = reverse_index.lookup(calculation_parent)
846+
if result is None or result.is_ambiguous or len(result.standard_concepts) != 1:
847+
return None
848+
from .sections import get_section_for_concept
849+
section = get_section_for_concept(result.primary_concept, statement_type)
850+
if section and section != "Totals":
851+
return section
852+
# A debt note is not a balance sheet role, but LongTermDebtNoncurrent
853+
# is noncurrent there too. Only a section that states a side is taken
854+
# from the untyped lookup.
855+
section = get_section_for_concept(result.primary_concept)
856+
if section_side(section):
857+
return section
858+
except Exception as e:
859+
logger.debug("Could not derive section from parent %s: %s", calculation_parent, e)
860+
861+
return None
862+
863+
864+
def _derive_section_from_parent(calculation_parent: str, statement_type: str,
865+
parents_of: Optional[Dict[str, Set[str]]] = None) -> Optional[str]:
775866
"""
776867
Derive the balance sheet section from a calculation parent concept.
777868
778-
Phase 3: Uses the calculation parent to determine which section an item
779-
belongs to, enabling disambiguation of ambiguous tags.
780-
781-
The key insight is that if an item's calculation parent is "AssetsCurrent",
782-
then the item belongs to the "Current Assets" section.
869+
If an item's calculation parent is "AssetsCurrent", the item belongs to the
870+
"Current Assets" section. A parent that states no side by itself (an
871+
ambiguous element such as OtherBorrowings, or a generic total) passes on
872+
the side of its own classified ancestor, found through `parents_of`
873+
(concept -> its calculation parents in the same statement). Ancestors that
874+
disagree, or a cycle, give no side.
783875
784876
Args:
785877
calculation_parent: The calculation parent concept (e.g., "us-gaap:AssetsCurrent")
786878
statement_type: The statement type (e.g., "BalanceSheet")
879+
parents_of: Calculation parents of each concept in the same statement
787880
788881
Returns:
789882
Section name (e.g., "Current Assets") or None if not determinable
790883
"""
791884
if not calculation_parent:
792885
return None
793886

794-
# Normalize the parent concept name
795-
parent_normalized = calculation_parent.lower()
796-
# Remove namespace prefix
797-
if ":" in parent_normalized:
798-
parent_normalized = parent_normalized.split(":")[-1]
799-
if "_" in parent_normalized:
800-
parent_normalized = parent_normalized.split("_")[-1]
801-
802-
# Map parent totals to their sections
803-
# Items under AssetsCurrent belong to "Current Assets" section
804-
parent_to_section = {
805-
# Current Assets - items rolling up to AssetsCurrent
806-
"assetscurrent": "Current Assets",
807-
"currentassets": "Current Assets",
808-
809-
# Non-Current Assets - items rolling up to AssetsNoncurrent
810-
"assetsnoncurrent": "Non-Current Assets",
811-
"noncurrentassets": "Non-Current Assets",
812-
813-
# Current Liabilities - items rolling up to LiabilitiesCurrent
814-
"liabilitiescurrent": "Current Liabilities",
815-
"currentliabilities": "Current Liabilities",
816-
817-
# Non-Current Liabilities - items rolling up to LiabilitiesNoncurrent
818-
"liabilitiesnoncurrent": "Non-Current Liabilities",
819-
"noncurrentliabilities": "Non-Current Liabilities",
820-
821-
# Equity - items rolling up to StockholdersEquity
822-
"stockholdersequity": "Equity",
823-
"stockholdersequityincludingportionattributabletononcontrollinginterest": "Equity",
824-
"equity": "Equity",
825-
826-
# Top-level totals (less specific)
827-
"assets": "Assets",
828-
"liabilities": "Liabilities",
829-
"liabilitiesandstockholdersequity": "Liabilities and Equity",
830-
}
831-
832-
# Direct lookup
833-
if parent_normalized in parent_to_section:
834-
return parent_to_section[parent_normalized]
835-
836-
# Partial match fallback
837-
for pattern, section in parent_to_section.items():
838-
if pattern in parent_normalized:
839-
return section
840-
841-
# Try reverse index as last resort
842-
try:
843-
reverse_index = _get_reverse_index()
844-
parent_standard = reverse_index.get_standard_concept(calculation_parent)
845-
846-
if parent_standard:
847-
from .sections import get_section_for_concept
848-
section = get_section_for_concept(parent_standard, statement_type)
849-
if section and section != "Totals":
850-
return section
851-
852-
except Exception as e:
853-
logger.debug("Could not derive section from parent %s: %s", calculation_parent, e)
854-
855-
return None
887+
own = _section_from_parent_name(calculation_parent, statement_type)
888+
if section_side(own) or not parents_of:
889+
return own
890+
891+
# Walk up to the nearest ancestors that state a side.
892+
sides: Set[str] = set()
893+
seen = {calculation_parent}
894+
frontier = list(parents_of.get(calculation_parent, ()))
895+
while frontier:
896+
ancestor = frontier.pop()
897+
if ancestor in seen:
898+
continue
899+
seen.add(ancestor)
900+
section = _section_from_parent_name(ancestor, statement_type)
901+
if section_side(section):
902+
sides.add(section)
903+
else:
904+
frontier.extend(parents_of.get(ancestor, ()))
905+
if len(sides) == 1:
906+
return sides.pop()
907+
return own
856908

857909

858910
def _assign_sections_bottom_up(
@@ -1007,6 +1059,13 @@ def standardize_statement(statement_data: List[Dict[str, Any]], mapper: ConceptM
10071059
items_to_standardize = []
10081060
statement_type = statement_data[0].get("statement_type", "") if statement_data else ""
10091061

1062+
# Calculation parents of each concept in this statement, so a parent that
1063+
# states no side can pass on its own classified ancestor's (GH #1438).
1064+
parents_of: Dict[str, Set[str]] = defaultdict(set)
1065+
for item in statement_data:
1066+
if item.get("concept") and item.get("calculation_parent") and not item.get("is_dimension", False):
1067+
parents_of[item["concept"]].add(item["calculation_parent"])
1068+
10101069
# First pass - identify which items need standardization and prepare context
10111070
for i, item in enumerate(statement_data):
10121071
# Skip abstract elements and dimensions as they don't need standardization
@@ -1034,7 +1093,7 @@ def standardize_statement(statement_data: List[Dict[str, Any]], mapper: ConceptM
10341093

10351094
# Phase 3: Derive section from calculation parent if available
10361095
if calculation_parent:
1037-
context["section"] = _derive_section_from_parent(calculation_parent, statement_type)
1096+
context["section"] = _derive_section_from_parent(calculation_parent, statement_type, parents_of)
10381097

10391098
items_to_standardize.append((i, concept, label, context))
10401099

‎edgar/xbrl/standardization/reverse_index.py‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,39 @@ def _canonical_ifrs_key(tag: str) -> str:
4848
return tag
4949

5050

51+
# Elements that say nothing about whether the amount is current or noncurrent,
52+
# and whose candidates are one current and one noncurrent concept. For these,
53+
# candidate order is not evidence: OtherBorrowings is short-term borrowing at a
54+
# bank and a five-year term loan at a REIT (BXP FY2025 tags its $797,053,000
55+
# "Unsecured term loans, net" with it). A side is taken only from the row's own
56+
# section or a classified ancestor; without one, get_standard_concept() returns
57+
# None and the row keeps its filed caption (GH #1438). lookup() still lists the
58+
# candidates.
59+
REQUIRE_SECTION_EVIDENCE = frozenset({
60+
"OtherBorrowings",
61+
"AdvancesFromFederalHomeLoanBanks",
62+
"RestrictedCashAndCashEquivalents",
63+
})
64+
65+
66+
def section_side(section: Optional[str]) -> Optional[str]:
67+
"""'current' or 'noncurrent' when a section name states a balance sheet side.
68+
69+
'Assets', 'Liabilities', 'Totals' and 'Equity' state none. A name that says
70+
both ('Current and Noncurrent ...') states none either.
71+
"""
72+
if not section or not isinstance(section, str):
73+
return None
74+
compact = section.lower().replace('-', '').replace(' ', '').replace('_', '')
75+
if 'currentandnoncurrent' in compact:
76+
return None
77+
if 'noncurrent' in compact or 'longterm' in compact:
78+
return 'noncurrent'
79+
if 'current' in compact or 'shortterm' in compact:
80+
return 'current'
81+
return None
82+
83+
5184
def _denotes_total(display_name: Optional[str]) -> bool:
5285
"""Whether a standard concept's display name claims to be a statement total.
5386
@@ -587,6 +620,11 @@ def get_standard_concept(
587620
resolution_method = "fallback"
588621
resolved = None
589622

623+
if result.mapping_key in REQUIRE_SECTION_EVIDENCE:
624+
# No fallback, no entry-level section, no name hint: only the
625+
# row's own classified section decides (GH #1438).
626+
return self._resolve_from_section_evidence(result.standard_concepts, context)
627+
590628
if context and len(result.standard_concepts) > 1:
591629
resolved = self._disambiguate_by_context(
592630
xbrl_tag, result.standard_concepts, context
@@ -630,6 +668,29 @@ def get_standard_concept(
630668

631669
return resolved
632670

671+
def _resolve_from_section_evidence(self, candidates: List[str], context: Optional[Dict]) -> Optional[str]:
672+
"""The one candidate whose section is the side the row's section states.
673+
674+
None when the context has no section, the section states no side, or
675+
no single candidate sits in that section (a liability candidate never
676+
matches a 'Current Assets' section).
677+
"""
678+
if context is not None and not isinstance(context, dict):
679+
raise ValidationError(
680+
"context must be a dict such as {'section': 'Current Assets'}, "
681+
f"not {type(context).__name__}",
682+
parameter="context", invalid_value=context)
683+
section = (context or {}).get('section')
684+
if section_side(section) is None:
685+
return None
686+
from .sections import get_section_for_concept
687+
matches = [
688+
candidate for candidate in candidates
689+
if self._sections_match(section, get_section_for_concept(candidate, 'BalanceSheet')
690+
or get_section_for_concept(candidate))
691+
]
692+
return matches[0] if len(matches) == 1 else None
693+
633694
def _disambiguate_by_context(
634695
self,
635696
xbrl_tag: str,
@@ -860,6 +921,12 @@ def get_display_name(self, xbrl_tag: str, context: Optional[Dict] = None,
860921
if not result.is_ambiguous:
861922
return result.primary_display_name
862923

924+
# The display name must agree with get_standard_concept(): no "Short-Term
925+
# Debt" on a row that has no side (GH #1438).
926+
if result.mapping_key in REQUIRE_SECTION_EVIDENCE:
927+
resolved = self._resolve_from_section_evidence(result.standard_concepts, context)
928+
return self.concept_to_display_name(resolved) if resolved else None
929+
863930
# Ambiguous tags: try to disambiguate using context
864931
if context and len(result.standard_concepts) > 1:
865932
resolved = self._disambiguate_by_context(

0 commit comments

Comments
 (0)