Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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/1438.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +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)
3 changes: 3 additions & 0 deletions docs/upgrade/6.5.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ see [Getting help](6.0.md#getting-help).
| `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) |
| `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) |
| `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) |
| `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) |
| `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) |
| 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) |

### Quarterly financials

Expand Down
197 changes: 128 additions & 69 deletions edgar/xbrl/standardization/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,15 @@
import json
import logging
import os
from collections import defaultdict
from difflib import SequenceMatcher
from enum import Enum
from typing import Any, Dict, List, Optional, Set, Tuple

import pandas as pd

from .reverse_index import section_side

# Module-level logger (avoid creating logger inside hot paths)
logger = logging.getLogger(__name__)

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


def _derive_section_from_parent(calculation_parent: str, statement_type: str) -> Optional[str]:
# Parent totals that state a section. The generic totals (Assets, Liabilities,
# LiabilitiesAndStockholdersEquity) name a section but no side, so they never
# decide current vs noncurrent for a child.
_PARENT_TO_SECTION = {
"assetscurrent": "Current Assets",
"currentassets": "Current Assets",
"assetsnoncurrent": "Non-Current Assets",
"noncurrentassets": "Non-Current Assets",
"liabilitiescurrent": "Current Liabilities",
"currentliabilities": "Current Liabilities",
"liabilitiesnoncurrent": "Non-Current Liabilities",
"noncurrentliabilities": "Non-Current Liabilities",
"stockholdersequity": "Equity",
"stockholdersequityincludingportionattributabletononcontrollinginterest": "Equity",
"equity": "Equity",
"assets": "Assets",
"liabilities": "Liabilities",
"liabilitiesandstockholdersequity": "Liabilities and Equity",
}

# Substring patterns, noncurrent first: 'othernoncurrentassets' contains
# 'currentassets', so testing the current spelling first read it as current.
_PARENT_SECTION_PATTERNS = (
("assetsnoncurrent", "Non-Current Assets"),
("noncurrentassets", "Non-Current Assets"),
("liabilitiesnoncurrent", "Non-Current Liabilities"),
("noncurrentliabilities", "Non-Current Liabilities"),
("assetscurrent", "Current Assets"),
("currentassets", "Current Assets"),
("liabilitiescurrent", "Current Liabilities"),
("currentliabilities", "Current Liabilities"),
("stockholdersequity", "Equity"),
("equity", "Equity"),
("liabilitiesandstockholdersequity", "Liabilities and Equity"),
("assets", "Assets"),
("liabilities", "Liabilities"),
)


def _bare_parent_name(concept: str) -> str:
name = concept.lower()
if ":" in name:
name = name.split(":")[-1]
if "_" in name:
name = name.split("_")[-1]
return name


def _section_from_parent_name(calculation_parent: str, statement_type: str) -> Optional[str]:
"""The section one parent concept states by itself, without its own parents."""
name = _bare_parent_name(calculation_parent)
if name in _PARENT_TO_SECTION:
return _PARENT_TO_SECTION[name]

# An ...CurrentAndNoncurrent element is on neither side; 'Current' inside
# its name is not a section (GH #1438).
unclassified = "currentandnoncurrent" in name
for pattern, section in _PARENT_SECTION_PATTERNS:
if unclassified and section_side(section):
continue
if pattern in name:
return section

# A parent with a single standard concept states that concept's section.
# A parent with several does not: its context-free answer is only the
# first candidate, which is not evidence for the child (GH #1438).
try:
reverse_index = _get_reverse_index()
result = reverse_index.lookup(calculation_parent)
if result is None or result.is_ambiguous or len(result.standard_concepts) != 1:
return None
from .sections import get_section_for_concept
section = get_section_for_concept(result.primary_concept, statement_type)
if section and section != "Totals":
return section
# A debt note is not a balance sheet role, but LongTermDebtNoncurrent
# is noncurrent there too. Only a section that states a side is taken
# from the untyped lookup.
section = get_section_for_concept(result.primary_concept)
if section_side(section):
return section
except Exception as e:
logger.debug("Could not derive section from parent %s: %s", calculation_parent, e)

return None


def _derive_section_from_parent(calculation_parent: str, statement_type: str,
parents_of: Optional[Dict[str, Set[str]]] = None) -> Optional[str]:
"""
Derive the balance sheet section from a calculation parent concept.

Phase 3: Uses the calculation parent to determine which section an item
belongs to, enabling disambiguation of ambiguous tags.

The key insight is that if an item's calculation parent is "AssetsCurrent",
then the item belongs to the "Current Assets" section.
If an item's calculation parent is "AssetsCurrent", the item belongs to the
"Current Assets" section. A parent that states no side by itself (an
ambiguous element such as OtherBorrowings, or a generic total) passes on
the side of its own classified ancestor, found through `parents_of`
(concept -> its calculation parents in the same statement). Ancestors that
disagree, or a cycle, give no side.

Args:
calculation_parent: The calculation parent concept (e.g., "us-gaap:AssetsCurrent")
statement_type: The statement type (e.g., "BalanceSheet")
parents_of: Calculation parents of each concept in the same statement

Returns:
Section name (e.g., "Current Assets") or None if not determinable
"""
if not calculation_parent:
return None

# Normalize the parent concept name
parent_normalized = calculation_parent.lower()
# Remove namespace prefix
if ":" in parent_normalized:
parent_normalized = parent_normalized.split(":")[-1]
if "_" in parent_normalized:
parent_normalized = parent_normalized.split("_")[-1]

# Map parent totals to their sections
# Items under AssetsCurrent belong to "Current Assets" section
parent_to_section = {
# Current Assets - items rolling up to AssetsCurrent
"assetscurrent": "Current Assets",
"currentassets": "Current Assets",

# Non-Current Assets - items rolling up to AssetsNoncurrent
"assetsnoncurrent": "Non-Current Assets",
"noncurrentassets": "Non-Current Assets",

# Current Liabilities - items rolling up to LiabilitiesCurrent
"liabilitiescurrent": "Current Liabilities",
"currentliabilities": "Current Liabilities",

# Non-Current Liabilities - items rolling up to LiabilitiesNoncurrent
"liabilitiesnoncurrent": "Non-Current Liabilities",
"noncurrentliabilities": "Non-Current Liabilities",

# Equity - items rolling up to StockholdersEquity
"stockholdersequity": "Equity",
"stockholdersequityincludingportionattributabletononcontrollinginterest": "Equity",
"equity": "Equity",

# Top-level totals (less specific)
"assets": "Assets",
"liabilities": "Liabilities",
"liabilitiesandstockholdersequity": "Liabilities and Equity",
}

# Direct lookup
if parent_normalized in parent_to_section:
return parent_to_section[parent_normalized]

# Partial match fallback
for pattern, section in parent_to_section.items():
if pattern in parent_normalized:
return section

# Try reverse index as last resort
try:
reverse_index = _get_reverse_index()
parent_standard = reverse_index.get_standard_concept(calculation_parent)

if parent_standard:
from .sections import get_section_for_concept
section = get_section_for_concept(parent_standard, statement_type)
if section and section != "Totals":
return section

except Exception as e:
logger.debug("Could not derive section from parent %s: %s", calculation_parent, e)

return None
own = _section_from_parent_name(calculation_parent, statement_type)
if section_side(own) or not parents_of:
return own

# Walk up to the nearest ancestors that state a side.
sides: Set[str] = set()
seen = {calculation_parent}
frontier = list(parents_of.get(calculation_parent, ()))
while frontier:
ancestor = frontier.pop()
if ancestor in seen:
continue
seen.add(ancestor)
section = _section_from_parent_name(ancestor, statement_type)
if section_side(section):
sides.add(section)
else:
frontier.extend(parents_of.get(ancestor, ()))
if len(sides) == 1:
return sides.pop()
return own


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

# Calculation parents of each concept in this statement, so a parent that
# states no side can pass on its own classified ancestor's (GH #1438).
parents_of: Dict[str, Set[str]] = defaultdict(set)
for item in statement_data:
if item.get("concept") and item.get("calculation_parent") and not item.get("is_dimension", False):
parents_of[item["concept"]].add(item["calculation_parent"])

# First pass - identify which items need standardization and prepare context
for i, item in enumerate(statement_data):
# Skip abstract elements and dimensions as they don't need standardization
Expand Down Expand Up @@ -1034,7 +1093,7 @@ def standardize_statement(statement_data: List[Dict[str, Any]], mapper: ConceptM

# Phase 3: Derive section from calculation parent if available
if calculation_parent:
context["section"] = _derive_section_from_parent(calculation_parent, statement_type)
context["section"] = _derive_section_from_parent(calculation_parent, statement_type, parents_of)

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

Expand Down
67 changes: 67 additions & 0 deletions edgar/xbrl/standardization/reverse_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,39 @@ def _canonical_ifrs_key(tag: str) -> str:
return tag


# Elements that say nothing about whether the amount is current or noncurrent,
# and whose candidates are one current and one noncurrent concept. For these,
# candidate order is not evidence: OtherBorrowings is short-term borrowing at a
# bank and a five-year term loan at a REIT (BXP FY2025 tags its $797,053,000
# "Unsecured term loans, net" with it). A side is taken only from the row's own
# section or a classified ancestor; without one, get_standard_concept() returns
# None and the row keeps its filed caption (GH #1438). lookup() still lists the
# candidates.
REQUIRE_SECTION_EVIDENCE = frozenset({
"OtherBorrowings",
"AdvancesFromFederalHomeLoanBanks",
"RestrictedCashAndCashEquivalents",
})


def section_side(section: Optional[str]) -> Optional[str]:
"""'current' or 'noncurrent' when a section name states a balance sheet side.

'Assets', 'Liabilities', 'Totals' and 'Equity' state none. A name that says
both ('Current and Noncurrent ...') states none either.
"""
if not section or not isinstance(section, str):
return None
compact = section.lower().replace('-', '').replace(' ', '').replace('_', '')
if 'currentandnoncurrent' in compact:
return None
if 'noncurrent' in compact or 'longterm' in compact:
return 'noncurrent'
if 'current' in compact or 'shortterm' in compact:
return 'current'
return None


def _denotes_total(display_name: Optional[str]) -> bool:
"""Whether a standard concept's display name claims to be a statement total.

Expand Down Expand Up @@ -587,6 +620,11 @@ def get_standard_concept(
resolution_method = "fallback"
resolved = None

if result.mapping_key in REQUIRE_SECTION_EVIDENCE:
# No fallback, no entry-level section, no name hint: only the
# row's own classified section decides (GH #1438).
return self._resolve_from_section_evidence(result.standard_concepts, context)

if context and len(result.standard_concepts) > 1:
resolved = self._disambiguate_by_context(
xbrl_tag, result.standard_concepts, context
Expand Down Expand Up @@ -630,6 +668,29 @@ def get_standard_concept(

return resolved

def _resolve_from_section_evidence(self, candidates: List[str], context: Optional[Dict]) -> Optional[str]:
"""The one candidate whose section is the side the row's section states.

None when the context has no section, the section states no side, or
no single candidate sits in that section (a liability candidate never
matches a 'Current Assets' section).
"""
if context is not None and not isinstance(context, dict):
raise ValidationError(
"context must be a dict such as {'section': 'Current Assets'}, "
f"not {type(context).__name__}",
parameter="context", invalid_value=context)
section = (context or {}).get('section')
if section_side(section) is None:
return None
from .sections import get_section_for_concept
matches = [
candidate for candidate in candidates
if self._sections_match(section, get_section_for_concept(candidate, 'BalanceSheet')
or get_section_for_concept(candidate))
]
return matches[0] if len(matches) == 1 else None

def _disambiguate_by_context(
self,
xbrl_tag: str,
Expand Down Expand Up @@ -860,6 +921,12 @@ def get_display_name(self, xbrl_tag: str, context: Optional[Dict] = None,
if not result.is_ambiguous:
return result.primary_display_name

# The display name must agree with get_standard_concept(): no "Short-Term
# Debt" on a row that has no side (GH #1438).
if result.mapping_key in REQUIRE_SECTION_EVIDENCE:
resolved = self._resolve_from_section_evidence(result.standard_concepts, context)
return self.concept_to_display_name(resolved) if resolved else None

# Ambiguous tags: try to disambiguate using context
if context and len(result.standard_concepts) > 1:
resolved = self._disambiguate_by_context(
Expand Down
Loading