diff --git a/changelog.d/1438.fixed.md b/changelog.d/1438.fixed.md new file mode 100644 index 000000000..c4581f817 --- /dev/null +++ b/changelog.d/1438.fixed.md @@ -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) diff --git a/docs/upgrade/6.5.md b/docs/upgrade/6.5.md index b061ab6e3..246b04f00 100644 --- a/docs/upgrade/6.5.md +++ b/docs/upgrade/6.5.md @@ -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 diff --git a/edgar/xbrl/standardization/core.py b/edgar/xbrl/standardization/core.py index 2b31b34ad..d27986a5f 100644 --- a/edgar/xbrl/standardization/core.py +++ b/edgar/xbrl/standardization/core.py @@ -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__) @@ -771,19 +774,109 @@ 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 @@ -791,68 +884,27 @@ def _derive_section_from_parent(calculation_parent: str, statement_type: str) -> 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( @@ -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 @@ -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)) diff --git a/edgar/xbrl/standardization/reverse_index.py b/edgar/xbrl/standardization/reverse_index.py index 76f727cc7..6826fc2b3 100644 --- a/edgar/xbrl/standardization/reverse_index.py +++ b/edgar/xbrl/standardization/reverse_index.py @@ -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. @@ -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 @@ -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, @@ -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( diff --git a/edgar/xbrl/stitching/core.py b/edgar/xbrl/stitching/core.py index c02b47122..c20b31c09 100644 --- a/edgar/xbrl/stitching/core.py +++ b/edgar/xbrl/stitching/core.py @@ -635,6 +635,37 @@ def _are_concept_name_variants(key_a: str, key_b: str) -> bool: b = StatementStitcher._bare_concept_name(key_b) return a in b or b in a + @staticmethod + def _restricted_cash_scope(bare_name: str) -> Optional[str]: + """'aggregate', 'current' or 'noncurrent' for a restricted-cash element, else None. + + us-gaap RestrictedCashAndCashEquivalentsAtCarryingValue is the current + portion ("Restricted Cash and Cash Equivalents, Current"); RestrictedCash + and RestrictedCashAndCashEquivalents carry no classification. + """ + if not bare_name.startswith('RestrictedCash'): + return None + lower = bare_name.lower() + if 'noncurrent' in lower: + return 'noncurrent' + if lower.endswith('current') or bare_name == 'RestrictedCashAndCashEquivalentsAtCarryingValue': + return 'current' + if bare_name in ('RestrictedCash', 'RestrictedCashAndCashEquivalents'): + return 'aggregate' + return None + + @classmethod + def _restricted_cash_scopes_differ(cls, key_a: str, key_b: str) -> bool: + """True when both keys are restricted cash of different scope (GH #1438). + + Their names contain each other and they can share a standard concept, + but an aggregate and its current portion are different amounts: equal + values in a common period do not make them one line. + """ + a = cls._restricted_cash_scope(cls._bare_concept_name(key_a)) + b = cls._restricted_cash_scope(cls._bare_concept_name(key_b)) + return a is not None and b is not None and a != b + @staticmethod def _values_agree(pv, sv) -> bool: """Equal, or within the 0.1% rounding tolerance.""" @@ -765,6 +796,8 @@ def _merge_duplicate_standard_concepts(self): concept from being incorrectly merged (Issue #642). A continuing-operations amount is not merged into its total where the filing reports nonzero discontinued-operations cash for that activity and period (GH #1690). + A restricted-cash aggregate and its current or noncurrent portion never + merge on name containment, whatever their values (GH #1438). Additionally, concepts whose standard concepts are declared equivalent (via _EQUIVALENT_STANDARD_CONCEPTS) are grouped together and merged @@ -812,6 +845,8 @@ def _merge_duplicate_standard_concepts(self): # For regular groups, require name containment (Issue #642). if not skip_variant_check and not self._are_concept_name_variants(a_key, b_key): continue + if not skip_variant_check and self._restricted_cash_scopes_differ(a_key, b_key): + continue if skip_variant_check and not self._shown_to_be_same_amount(a_key, b_key): continue if self._continuing_differs_from_total(a_key, b_key): diff --git a/tests/fixtures/xbrl_gz/README.md b/tests/fixtures/xbrl_gz/README.md index 8239a0009..335ea0f03 100644 --- a/tests/fixtures/xbrl_gz/README.md +++ b/tests/fixtures/xbrl_gz/README.md @@ -12,8 +12,8 @@ definition-linkbase answer) as `filing.xbrl()` on the live filing. This was chec 2026-11-22 before the files were committed. Each directory holds the filing's instance (`*_htm.xml`), schema (`*.xsd`) and linkbases -(`_cal`, `_def`, `_lab`, `_pre`), plus a plain-text `filing_metadata.txt`. SLB embeds its -linkbases in the schema, so its directory has only the instance and the schema. The +(`_cal`, `_def`, `_lab`, `_pre`), plus a plain-text `filing_metadata.txt`. SLB and PBHC embed their +linkbases in the schema, so their directories have only the instance and the schema. The directory name is the fiscal year of the report's period end, taken from the instance filename. @@ -21,12 +21,14 @@ Used by `tests/issues/regression/test_issue_68lp_gh577_validation.py` and `tests/issues/regression/test_issue_683_vale_cashflow.py` (VALE: three consecutive 20-Fs, for stitching; checked against `filing.xbrl()` on 2026-11-23 by comparing the stitched cash flow statement on both stitching paths). +BXP and PBHC are used by `tests/issues/regression/test_issue_1438_classification_evidence.py`. ## Filings | Ticker | Company | Form | Filed | Accession | Directory | |---|---|---|---|---|---| | BA | BOEING CO | 10-K | 2026-01-30 | `0001628280-26-004357` | `ba/10k_2025` | +| BXP | BXP, Inc. | 10-K | 2026-02-27 | `0001037540-26-000006` | `bxp/10k_2025` | | BSX | BOSTON SCIENTIFIC CORP | 10-K | 2026-02-17 | `0000885725-26-000010` | `bsx/10k_2025` | | CARR | CARRIER GLOBAL Corp | 10-K | 2026-02-05 | `0001783180-26-000008` | `carr/10k_2025` | | CSX | CSX CORP | 10-K | 2026-02-12 | `0000277948-26-000006` | `csx/10k_2025` | @@ -37,6 +39,7 @@ statement on both stitching paths). | INTU | INTUIT INC. | 10-K | 2026-09-09 | `0000896878-26-000037` | `intu/10k_2026` | | JKHY | JACK HENRY & ASSOCIATES INC | 10-K | 2026-08-28 | `0000779152-26-000067` | `jkhy/10k_2026` | | NOC | NORTHROP GRUMMAN CORP /DE/ | 10-K | 2026-01-27 | `0001133421-26-000003` | `noc/10k_2025` | +| PBHC | Pathfinder Bancorp, Inc. | 10-K | 2025-03-31 | `0000950170-25-047820` | `pbhc/10k_2024` | | RTX | RTX Corp | 10-K | 2026-02-06 | `0000101829-26-000006` | `rtx/10k_2025` | | SLB | SLB LIMITED/NV | 10-K | 2026-01-23 | `0001193125-26-021017` | `slb/10k_2025` | | WDAY | Workday, Inc. | 10-K | 2026-03-06 | `0001327811-26-000014` | `wday/10k_2026` | @@ -147,4 +150,12 @@ a392d0a8f9f478f6686b0585df32666d1aff2c39243df830751158e37cbda170 vale/20f_2024/ b5890c854f43be48f985eb69be8de7324d01ff4d40e4817a333ab5f83204af85 vale/20f_2025/vale-20251231_pre.xml cf7bf0bd9d15e72cf6c4c6ecb7d2cd82b6aacce70386cd1afd7c2d2105bd991e vale/20f_2025/vale-20251231.xsd a5c9e5d99174340def207213349b8aed36bfb8b3e2692632b2e2c9da1fff22d0 vale/20f_2025/valeform20f_2025_htm.xml +323e54cf42a14d16b625a8ca5346b789ee9d061e42f4b170501e0227e283c8c8 bxp/10k_2025/bxp-20251231.xsd +7c199ff6c8b4bd34d3255f489847a95b03f235825d4e68514a85ca54c8a53da7 bxp/10k_2025/bxp-20251231_cal.xml +49d65c4692d794389f6ae248ef073baabed878be71dd150851b902c6befeee5b bxp/10k_2025/bxp-20251231_def.xml +d1f1a796bb0646a773a89622700a42c284112ed14f4e1f8cbdfbc4b3d034cc13 bxp/10k_2025/bxp-20251231_htm.xml +34a78044827fd634d8e2d4b334430f3086e8ff3b126231ff6e0b73d136be6aa0 bxp/10k_2025/bxp-20251231_lab.xml +f8163cd980afcd6e868ce621f4aeb9f2fe467778e2ac14b3d5723b1cf2446973 bxp/10k_2025/bxp-20251231_pre.xml +9778267ae769b50ba2d25469ab445dc1d50057da00bc5a3f9dd383f6c194e800 pbhc/10k_2024/pbhc-20241231.xsd +75f74e1fc39e58cfdf6127d409552e898ae5af5b0c6415a0a8724853c4572d1a pbhc/10k_2024/pbhc-20241231_htm.xml ``` diff --git a/tests/fixtures/xbrl_gz/bxp/10k_2025/bxp-20251231.xsd.gz b/tests/fixtures/xbrl_gz/bxp/10k_2025/bxp-20251231.xsd.gz new file mode 100644 index 000000000..601bdef1c Binary files /dev/null and b/tests/fixtures/xbrl_gz/bxp/10k_2025/bxp-20251231.xsd.gz differ diff --git a/tests/fixtures/xbrl_gz/bxp/10k_2025/bxp-20251231_cal.xml.gz b/tests/fixtures/xbrl_gz/bxp/10k_2025/bxp-20251231_cal.xml.gz new file mode 100644 index 000000000..7cdf4c529 Binary files /dev/null and b/tests/fixtures/xbrl_gz/bxp/10k_2025/bxp-20251231_cal.xml.gz differ diff --git a/tests/fixtures/xbrl_gz/bxp/10k_2025/bxp-20251231_def.xml.gz b/tests/fixtures/xbrl_gz/bxp/10k_2025/bxp-20251231_def.xml.gz new file mode 100644 index 000000000..ec0577cce Binary files /dev/null and b/tests/fixtures/xbrl_gz/bxp/10k_2025/bxp-20251231_def.xml.gz differ diff --git a/tests/fixtures/xbrl_gz/bxp/10k_2025/bxp-20251231_htm.xml.gz b/tests/fixtures/xbrl_gz/bxp/10k_2025/bxp-20251231_htm.xml.gz new file mode 100644 index 000000000..12cfc16b8 Binary files /dev/null and b/tests/fixtures/xbrl_gz/bxp/10k_2025/bxp-20251231_htm.xml.gz differ diff --git a/tests/fixtures/xbrl_gz/bxp/10k_2025/bxp-20251231_lab.xml.gz b/tests/fixtures/xbrl_gz/bxp/10k_2025/bxp-20251231_lab.xml.gz new file mode 100644 index 000000000..e3fcbb146 Binary files /dev/null and b/tests/fixtures/xbrl_gz/bxp/10k_2025/bxp-20251231_lab.xml.gz differ diff --git a/tests/fixtures/xbrl_gz/bxp/10k_2025/bxp-20251231_pre.xml.gz b/tests/fixtures/xbrl_gz/bxp/10k_2025/bxp-20251231_pre.xml.gz new file mode 100644 index 000000000..290ee6de3 Binary files /dev/null and b/tests/fixtures/xbrl_gz/bxp/10k_2025/bxp-20251231_pre.xml.gz differ diff --git a/tests/fixtures/xbrl_gz/bxp/10k_2025/filing_metadata.txt b/tests/fixtures/xbrl_gz/bxp/10k_2025/filing_metadata.txt new file mode 100644 index 000000000..fcef30f54 --- /dev/null +++ b/tests/fixtures/xbrl_gz/bxp/10k_2025/filing_metadata.txt @@ -0,0 +1,6 @@ +ticker=BXP +accession=0001037540-26-000006 +form=10-K +filing_date=2026-02-27 +cik=1037540 +company=BXP, Inc. diff --git a/tests/fixtures/xbrl_gz/pbhc/10k_2024/filing_metadata.txt b/tests/fixtures/xbrl_gz/pbhc/10k_2024/filing_metadata.txt new file mode 100644 index 000000000..c36833883 --- /dev/null +++ b/tests/fixtures/xbrl_gz/pbhc/10k_2024/filing_metadata.txt @@ -0,0 +1,6 @@ +ticker=PBHC +accession=0000950170-25-047820 +form=10-K +filing_date=2025-03-31 +cik=1609065 +company=Pathfinder Bancorp, Inc. diff --git a/tests/fixtures/xbrl_gz/pbhc/10k_2024/pbhc-20241231.xsd.gz b/tests/fixtures/xbrl_gz/pbhc/10k_2024/pbhc-20241231.xsd.gz new file mode 100644 index 000000000..b9f898c8c Binary files /dev/null and b/tests/fixtures/xbrl_gz/pbhc/10k_2024/pbhc-20241231.xsd.gz differ diff --git a/tests/fixtures/xbrl_gz/pbhc/10k_2024/pbhc-20241231_htm.xml.gz b/tests/fixtures/xbrl_gz/pbhc/10k_2024/pbhc-20241231_htm.xml.gz new file mode 100644 index 000000000..ea554e6fc Binary files /dev/null and b/tests/fixtures/xbrl_gz/pbhc/10k_2024/pbhc-20241231_htm.xml.gz differ diff --git a/tests/issues/regression/test_issue_1438_classification_evidence.py b/tests/issues/regression/test_issue_1438_classification_evidence.py new file mode 100644 index 000000000..58b6329f5 --- /dev/null +++ b/tests/issues/regression/test_issue_1438_classification_evidence.py @@ -0,0 +1,285 @@ +"""A current/noncurrent concept needs evidence from the filing, not candidate order. + +GitHub Issue: https://github.com/dgunning/edgartools/issues/1438 + +OtherBorrowings, AdvancesFromFederalHomeLoanBanks and RestrictedCashAndCashEquivalents +each map to one current and one noncurrent concept. With no section to go on, +get_standard_concept() took the first: BXP's "Unsecured term loans, net" (BXP FY2025 +10-K, 0001037540-26-000006, $797,053,000 at 2025-12-31 and $798,813,000 at 2024-12-31) +came back ShortTermDebt, though BXP files an unclassified balance sheet. These three +now resolve only from the row's own section or a classified ancestor, and otherwise +return None, keeping the filed caption and values. lookup() still lists both candidates. + +_derive_section_from_parent() handed a child its ambiguous parent's context-free first +candidate. An FHLB advance under OtherBorrowings under noncurrent liabilities became +ShortTermDebt while its parent became LongTermDebt. A parent that states no side now +passes on its own classified ancestor's, a ...CurrentAndNoncurrent parent states no +side, and a noncurrent spelling is matched before the current one it contains. + +Stitching merged a restricted-cash aggregate with its current-only portion through the +name-variant path (RestrictedCashAndCashEquivalents is contained in +RestrictedCashAndCashEquivalentsAtCarryingValue). They now stay separate rows. + +Design and BXP case: synfonia-llc on GH #1438. +""" +import gzip +import math +from pathlib import Path + +import pytest + +from edgar.xbrl import XBRL +from edgar.xbrl.standardization.core import _derive_section_from_parent, standardize_statement +from edgar.xbrl.standardization.reverse_index import get_reverse_index +from edgar.xbrl.stitching.core import StatementStitcher + +pytestmark = pytest.mark.fast + +FIXTURES = Path(__file__).parents[2] / "fixtures" / "xbrl_gz" + + +def _load(tmp_path_factory, directory): + dest = tmp_path_factory.mktemp(directory.replace("/", "_")) + for gz in (FIXTURES / directory).glob("*.gz"): + (dest / gz.name[:-3]).write_bytes(gzip.decompress(gz.read_bytes())) + return XBRL.from_directory(dest) + + +@pytest.fixture(scope="module") +def bxp(tmp_path_factory): + return _load(tmp_path_factory, "bxp/10k_2025") + + +@pytest.fixture(scope="module") +def pathfinder(tmp_path_factory): + return _load(tmp_path_factory, "pbhc/10k_2024") + + +# --- 1. require-evidence rule --------------------------------------------------- + +def test_bxp_term_loans_keep_filed_amounts_without_a_short_term_concept(bxp): + """BXP FY2025 10-K 0001037540-26-000006, consolidated balance sheet.""" + assert bxp.entity_name == "BXP, INC." + statement = bxp.statements.balance_sheet() + frame = statement.to_dataframe() + row = frame[(frame["concept"] == "us-gaap_OtherBorrowings") & ~frame["dimension"]] + assert len(row) == 1 + row = row.iloc[0] + assert row["label"] == "Unsecured term loans, net" + assert row["2025-12-31"] == 797_053_000 + assert row["2024-12-31"] == 798_813_000 + standard_concept = row["standard_concept"] + assert standard_concept is None or (isinstance(standard_concept, float) and math.isnan(standard_concept)) + + rendered = str(statement.render(standard=True)) + line = next(line for line in rendered.splitlines() if "797,053" in line) + assert "Unsecured term loans, net" in line + assert "short-term" not in line.lower() + + +@pytest.mark.parametrize("tag, candidates", [ + ("us-gaap:OtherBorrowings", ["ShortTermDebt", "LongTermDebt"]), + ("us-gaap:AdvancesFromFederalHomeLoanBanks", ["LongTermDebt", "ShortTermDebt"]), + ("us-gaap:RestrictedCashAndCashEquivalents", ["RestrictedCashCurrent", "RestrictedCashNonCurrent"]), +]) +def test_no_section_is_no_concept_and_lookup_keeps_candidates(tag, candidates): + index = get_reverse_index() + assert index.lookup(tag).standard_concepts == candidates + for context in (None, {}, {"statement_type": "BalanceSheet"}, {"statement_type": "BalanceSheet", "section": None}, + {"statement_type": "BalanceSheet", "section": "Assets"}, + {"statement_type": "BalanceSheet", "section": "Liabilities"}, + {"statement_type": "BalanceSheet", "is_total": True}): + assert index.get_standard_concept(tag, context) is None, context + assert index.get_display_name(tag, context) is None, context + + +@pytest.mark.parametrize("tag, section, expected", [ + ("us-gaap:OtherBorrowings", "Current Liabilities", "ShortTermDebt"), + ("us-gaap:OtherBorrowings", "Non-Current Liabilities", "LongTermDebt"), + ("us-gaap:OtherBorrowings", "Current Assets", None), + ("us-gaap:AdvancesFromFederalHomeLoanBanks", "Non-Current Liabilities", "LongTermDebt"), + ("us-gaap:AdvancesFromFederalHomeLoanBanks", "Current Liabilities", "ShortTermDebt"), + ("us-gaap:RestrictedCashAndCashEquivalents", "Current Assets", "RestrictedCashCurrent"), + ("us-gaap:RestrictedCashAndCashEquivalents", "Non-Current Assets", "RestrictedCashNonCurrent"), + ("us-gaap:RestrictedCashAndCashEquivalents", "Current Liabilities", None), +]) +def test_a_classified_section_still_resolves(tag, section, expected): + index = get_reverse_index() + context = {"statement_type": "BalanceSheet", "section": section} + assert index.get_standard_concept(tag, context) == expected + assert index.get_display_name(tag, context) == (index.concept_to_display_name(expected) if expected else None) + + +def test_bad_context_is_a_useful_error(): + from edgar.exceptions import ValidationError + with pytest.raises(ValidationError, match="context must be a dict"): + get_reverse_index().get_standard_concept("us-gaap:OtherBorrowings", "Current Liabilities") + + +def test_pathfinder_fhlb_advances_under_long_term_debt_stay_long_term(pathfinder): + """Pathfinder Bancorp FY2024 10-K 0000950170-25-047820, long-term borrowings note: + "Total advances with FHLB" ($27,068,000 at 2024-12-31) rolls up to + LongTermDebtNoncurrent. The parent is a classified ancestor even outside the + balance sheet role.""" + role = next(meta for meta in pathfinder.get_all_statements() + if "LongTermBorrowingsDetails" in meta["role"]) + data = pathfinder.get_statement(role["role"]) + std = pathfinder.standardization.standardize_statement_data(data, role["type"], use_cache=False) + rows = [item for item in std + if item["concept"] == "us-gaap_AdvancesFromFederalHomeLoanBanks" and not item.get("is_dimension")] + assert len(rows) == 1 + assert rows[0]["label"] == "Total advances with FHLB" + assert rows[0]["calculation_parent"] == "us-gaap_LongTermDebtNoncurrent" + assert rows[0]["values"]["instant_2024-12-31"] == 27_068_000 + assert rows[0]["standard_concept"] == "LongTermDebt" + + +# --- 2. section from the calculation parent ------------------------------------- + +def _row(concept, parent, value=100): + return {"concept": concept, "label": concept.split("_", 1)[1], "calculation_parent": parent, + "values": {"instant_2025-12-31": value}, "statement_type": "BalanceSheet", "level": 2} + + +def _concepts(rows): + return {item["concept"]: item.get("standard_concept") for item in standardize_statement(rows, None)} + + +@pytest.mark.parametrize("total, expected", [ + ("us-gaap_LiabilitiesNoncurrent", "LongTermDebt"), + ("us-gaap_LiabilitiesCurrent", "ShortTermDebt"), +]) +def test_fhlb_child_takes_the_side_of_its_parents_classified_ancestor(total, expected): + """Synthetic chain: FHLB advances under OtherBorrowings under a classified total.""" + concepts = _concepts([ + _row("us-gaap_AdvancesFromFederalHomeLoanBanks", "us-gaap_OtherBorrowings"), + _row("us-gaap_OtherBorrowings", total), + ]) + assert concepts["us-gaap_AdvancesFromFederalHomeLoanBanks"] == expected + assert concepts["us-gaap_OtherBorrowings"] == expected + + +def test_generic_total_is_not_a_side(): + concepts = _concepts([ + _row("us-gaap_AdvancesFromFederalHomeLoanBanks", "us-gaap_OtherBorrowings"), + _row("us-gaap_OtherBorrowings", "us-gaap_Liabilities"), + ]) + assert concepts == {"us-gaap_AdvancesFromFederalHomeLoanBanks": None, "us-gaap_OtherBorrowings": None} + + +def test_conflicting_ancestors_give_no_side(): + concepts = _concepts([ + _row("us-gaap_AdvancesFromFederalHomeLoanBanks", "us-gaap_OtherBorrowings"), + _row("us-gaap_OtherBorrowings", "us-gaap_LiabilitiesCurrent"), + _row("us-gaap_OtherBorrowings", "us-gaap_LiabilitiesNoncurrent"), + ]) + assert concepts["us-gaap_AdvancesFromFederalHomeLoanBanks"] is None + + +def test_a_calculation_cycle_gives_no_side_and_terminates(): + concepts = _concepts([ + _row("us-gaap_AdvancesFromFederalHomeLoanBanks", "us-gaap_OtherBorrowings"), + _row("us-gaap_OtherBorrowings", "us-gaap_AdvancesFromFederalHomeLoanBanks"), + ]) + assert concepts == {"us-gaap_AdvancesFromFederalHomeLoanBanks": None, "us-gaap_OtherBorrowings": None} + + +@pytest.mark.parametrize("parent, expected", [ + ("us-gaap_LiabilitiesCurrent", "Current Liabilities"), + ("us-gaap_OtherAssetsNoncurrent", "Non-Current Assets"), + # 'othernoncurrentassets' contains 'currentassets' + ("ifrs-full_OtherNoncurrentAssets", "Non-Current Assets"), + # 'Current' inside ...CurrentAndNoncurrent is not a side + ("us-gaap_OtherLiabilitiesCurrentAndNoncurrent", "Liabilities"), + # ambiguous parent with no ancestor: its first candidate is not evidence + ("us-gaap_OtherBorrowings", None), + ("us-gaap_Assets", "Assets"), +]) +def test_derive_section_from_parent(parent, expected): + assert _derive_section_from_parent(parent, "BalanceSheet") == expected + + +def test_xom_deferred_tax_components_follow_their_noncurrent_total(): + """ExxonMobil FY2022 10-K 0000034088-23-000020, deferred income taxes note. The + components sat under DeferredIncomeTaxLiabilities, which maps to both sides; its + first candidate made PP&E current while the total itself resolved noncurrent.""" + xbrl = XBRL.from_directory(Path(__file__).parents[2] / "fixtures" / "xbrl" / "xom" / "10k_2023") + role = "http://www.exxonmobil.com/role/IncomeAndOtherTaxesDeferredIncomeTaxesAssetsAndLiabilitiesDetails" + std = xbrl.standardization.standardize_statement_data(xbrl.get_statement(role), "Disclosures", use_cache=False) + rows = {item["concept"]: item for item in std if not item.get("is_dimension")} + ppe = rows["us-gaap_DeferredTaxLiabilitiesPropertyPlantAndEquipment"] + assert ppe["values"]["instant_2022-12-31"] == 25_607_000_000 + assert ppe["standard_concept"] == "DeferredTaxNonCurrentLiabilities" + assert rows["us-gaap_DeferredIncomeTaxLiabilities"]["standard_concept"] == "DeferredTaxNonCurrentLiabilities" + assert rows["us-gaap_DeferredTaxAssetsOther"]["standard_concept"] == "DeferredTaxNoncurrentAssets" + + +# --- 3. stitching: restricted-cash aggregate vs current portion ------------------ + +def _stmt(date, rows): + pid = f"instant_{date}" + return {"statement_type": "BalanceSheet", + "periods": {pid: {"label": date}}, + "data": [{"concept": c, "label": label, "level": 1, "is_abstract": False, "is_total": False, + "calculation_parent": "us-gaap_AssetsCurrent", + "values": {pid: v}, "decimals": {pid: 0}} + for c, label, v in rows]} + + +def _stitched(statements): + out = StatementStitcher().stitch_statements(statements) + return {r["concept"]: r["values"] for r in out["statement_data"] if r["concept"]} + + +def test_restricted_cash_aggregate_and_current_portion_stay_separate(): + """Synthetic amounts: 120 aggregate at 2025-12-31, 80 current-only at 2024-12-31, + no common period. Both resolve RestrictedCashCurrent under current assets.""" + rows = _stitched([ + _stmt("2025-12-31", [("us-gaap_RestrictedCashAndCashEquivalents", "Restricted cash and cash equivalents", 120)]), + _stmt("2024-12-31", [("us-gaap_RestrictedCashAndCashEquivalentsAtCarryingValue", "Restricted cash, current", 80)]), + ]) + assert rows["us-gaap_RestrictedCashAndCashEquivalents"] == {"instant_2025-12-31": 120} + assert rows["us-gaap_RestrictedCashAndCashEquivalentsAtCarryingValue"] == {"instant_2024-12-31": 80} + + +def test_restricted_cash_scopes_stay_separate_even_when_a_common_period_agrees(): + """Name containment is not identity. (An identical caption with an agreeing + nonzero amount is a retag and merges by label, GH #1802; that is not this path.)""" + later = _stmt("2025-12-31", [("us-gaap_RestrictedCashAndCashEquivalents", "Restricted cash and cash equivalents", 120)]) + later["data"][0]["values"]["instant_2024-12-31"] = 80 + rows = _stitched([ + later, + _stmt("2024-12-31", [("us-gaap_RestrictedCashAndCashEquivalentsAtCarryingValue", "Restricted cash, current", 80)]), + ]) + assert rows["us-gaap_RestrictedCashAndCashEquivalents"] == {"instant_2025-12-31": 120} + assert rows["us-gaap_RestrictedCashAndCashEquivalentsAtCarryingValue"] == {"instant_2024-12-31": 80} + + +def test_restricted_cash_scope(): + scope = StatementStitcher._restricted_cash_scope + assert scope("RestrictedCashAndCashEquivalents") == "aggregate" + assert scope("RestrictedCash") == "aggregate" + assert scope("RestrictedCashAndCashEquivalentsAtCarryingValue") == "current" + assert scope("RestrictedCashCurrent") == "current" + assert scope("RestrictedCashAndCashEquivalentsNoncurrent") == "noncurrent" + assert scope("CashAndCashEquivalentsAtCarryingValue") is None + + +def test_ordinary_cash_without_common_period_stays_separate_control(): + """GH #1685's guard, unchanged.""" + rows = _stitched([ + _stmt("2023-12-31", [("us-gaap_CashAndCashEquivalentsAtCarryingValue", "Cash and cash equivalents", 120)]), + _stmt("2022-12-31", [("us-gaap_CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents", + "Cash, cash equivalents and restricted cash", 130)]), + ]) + assert rows["us-gaap_CashAndCashEquivalentsAtCarryingValue"] == {"instant_2023-12-31": 120} + assert rows["us-gaap_CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents"] == {"instant_2022-12-31": 130} + + +def test_same_definition_name_variants_still_merge_control(): + rows = _stitched([ + _stmt("2025-12-31", [("us-gaap_LongTermDebtNoncurrent", "Long-term debt, net of current portion", 500)]), + _stmt("2024-12-31", [("us-gaap_LongTermDebt", "Long-term debt", 450)]), + ]) + assert len(rows) == 1 + assert next(iter(rows.values())) == {"instant_2025-12-31": 500, "instant_2024-12-31": 450} diff --git a/tests/issues/regression/test_issue_1438_followup.py b/tests/issues/regression/test_issue_1438_followup.py index d15adf46f..aac85d9ee 100644 --- a/tests/issues/regression/test_issue_1438_followup.py +++ b/tests/issues/regression/test_issue_1438_followup.py @@ -32,7 +32,7 @@ from edgar.xbrl import XBRL from edgar.xbrl.standardization import reverse_index as reverse_index_module from edgar.xbrl.standardization.core import ConceptMapper, MappingStore, standardize_statement -from edgar.xbrl.standardization.reverse_index import get_reverse_index +from edgar.xbrl.standardization.reverse_index import REQUIRE_SECTION_EVIDENCE, get_reverse_index from edgar.xbrl.standardization.sections import get_section_for_concept from edgar.xbrl.standardization.sic_industry import _FF48_SIC_RANGES @@ -166,6 +166,12 @@ def test_public_context_paths_keep_the_corrected_concept(index, tag, statement_t if EXPECTED[tag] is None: assert concept is None assert index.get_display_name(tag, context) is None + elif tag in REQUIRE_SECTION_EVIDENCE: + # No first-candidate fallback: only a section on this element's own + # side of the balance sheet resolves it (GH #1438 scope decision). + sides = {get_section_for_concept(c, "BalanceSheet"): c for c in EXPECTED[tag]} + assert concept == sides.get(section) + assert index.get_display_name(tag, context) == (DISPLAY_NAMES[concept] if concept else None) else: assert concept in EXPECTED[tag] assert index.get_display_name(tag, context) == DISPLAY_NAMES[concept] @@ -177,7 +183,8 @@ def test_standardization_preserves_filed_data(mapper, tag): result = standardize_statement([item], mapper) assert len(result) == 1 assert {key: value for key, value in result[0].items() if key != "standard_concept"} == item - if EXPECTED[tag] is None: + if EXPECTED[tag] is None or tag in REQUIRE_SECTION_EVIDENCE: + # A lone row has no section, so a require-evidence element keeps only its filed data. assert "standard_concept" not in result[0] else: assert result[0]["standard_concept"] in EXPECTED[tag] diff --git a/tests/issues/regression/test_issue_1441_industry_mappings.py b/tests/issues/regression/test_issue_1441_industry_mappings.py index dd6a177dd..9ef38a6f4 100644 --- a/tests/issues/regression/test_issue_1441_industry_mappings.py +++ b/tests/issues/regression/test_issue_1441_industry_mappings.py @@ -23,7 +23,7 @@ from edgar.xbrl.standardization import reverse_index as reverse_index_module from edgar.xbrl.standardization.core import ConceptMapper, MappingStore, standardize_statement from edgar.xbrl.standardization.exclusions import EXCLUDED_TAGS -from edgar.xbrl.standardization.reverse_index import get_reverse_index +from edgar.xbrl.standardization.reverse_index import REQUIRE_SECTION_EVIDENCE, get_reverse_index from edgar.xbrl.standardization.sections import get_section_for_concept, get_statement_for_concept from edgar.xbrl.standardization.sic_industry import _FF48_SIC_RANGES @@ -103,7 +103,8 @@ def test_explicit_lookups(index): @pytest.mark.parametrize( "section, expected", - [("Non-Current Liabilities", "LongTermDebt"), ("Current Liabilities", "ShortTermDebt"), (None, "LongTermDebt")], + # No section is no evidence: the first candidate is not a side (GH #1438 scope decision). + [("Non-Current Liabilities", "LongTermDebt"), ("Current Liabilities", "ShortTermDebt"), (None, None)], ) def test_fhlb_advances_take_the_side_of_their_section(index, section, expected): context = {"statement_type": "BalanceSheet", "section": section} if section else None @@ -155,7 +156,7 @@ def test_standardization_preserves_filed_data(mapper, tag, statement_type): assert len(result) == 1 assert {key: value for key, value in result[0].items() if key != "standard_concept"} == item expected = EXPECTED[tag] - if expected is None: + if expected is None or tag in REQUIRE_SECTION_EVIDENCE: assert "standard_concept" not in result[0] else: assert result[0]["standard_concept"] in expected