""" Process raw XBRL company facts into structured annual and quarterly financial data. Supports both US-GAAP and IFRS (ifrs-full) filers (ADRs filing 20-F/6-K). """ from datetime import datetime, timedelta from config import ( SCALE_FACTOR, ANNUAL_MIN_DAYS, ANNUAL_MAX_DAYS, QUARTERLY_MIN_DAYS, QUARTERLY_MAX_DAYS, SEMI_ANNUAL_MIN_DAYS, SEMI_ANNUAL_MAX_DAYS, ) from xbrl_mapper import IS_CONCEPTS, BS_CONCEPTS, CF_CONCEPTS, get_all_concepts # ── IFRS → US-GAAP concept translation ───────────────────────── # Maps each SMB universal code to a list of ifrs-full concept names to try # (in priority order). When an IFRS filer is detected, we copy IFRS data # into a synthetic us-gaap dict keyed by the first us-gaap concept name # that xbrl_mapper expects, so all downstream code works unchanged. IFRS_CONCEPT_MAP = { # ── Income Statement ────────────────────────────────────── "IS-1000": ["Revenue", "RevenueFromSaleOfGoods", "RevenueFromRenderingOfServices", "RevenueFromContractsWithCustomers"], "IS-2000": ["CostOfSales"], "IS-3000": ["GrossProfit"], "IS-4000": ["SellingGeneralAndAdministrativeExpense", "AdministrativeExpense", "DistributionCosts", "SellingExpense"], "IS-4100": ["SellingExpense"], "IS-4200": ["ResearchAndDevelopmentExpense"], "IS-4300": ["AdministrativeExpense", "GeneralAndAdministrativeExpense"], "IS-5000": ["DepreciationAndAmortisationExpense", "DepreciationExpense", "AmortisationExpense"], "IS-5500": ["RestructuringProvision", "RestructuringAndRelatedCostIncurredCost"], "IS-6000": [], # IFRS typically doesn't report a single total opex line "IS-7000": ["ProfitLossFromOperatingActivities", "OperatingProfit"], "IS-7100": ["InterestRevenueCalculatedUsingEffectiveInterestMethod", "InterestRevenue", "FinanceIncome"], "IS-7200": ["InterestExpense", "FinanceCosts"], "IS-7300": ["OtherFinanceIncome", "OtherNonoperatingIncomeExpense"], "IS-8000": ["ProfitLossBeforeTax"], "IS-8500": ["IncomeTaxExpenseContinuingOperations", "TaxExpenseBenefitOnIncomeLossFromContinuingOperations", "IncomeTaxExpense"], "IS-9000": ["ProfitLoss", "ProfitLossAttributableToOwnersOfParent"], "IS-9500": ["BasicEarningsLossPerShare"], "IS-9600": ["DilutedEarningsLossPerShare"], "IS-9700": [], # Shares — typically in dei namespace "IS-9800": [], "IS-SBC": ["SharebasedPaymentExpense", "ShareBasedPaymentArrangementExpense"], # ── Balance Sheet ───────────────────────────────────────── "BS-1100": ["CashAndCashEquivalents", "Cash"], "BS-1200": ["OtherCurrentFinancialAssets", "CurrentFinancialAssetsAtFairValueThroughProfitOrLoss"], "BS-1300": ["TradeAndOtherCurrentReceivables", "CurrentTradeReceivables"], "BS-1400": ["Inventories", "CurrentInventories"], "BS-1500": ["CurrentPrepaidExpenses", "OtherCurrentAssets", "OtherCurrentNonfinancialAssets"], "BS-1900": ["CurrentAssets"], "BS-2100": ["PropertyPlantAndEquipment"], "BS-2200": ["RightofuseAssets"], "BS-2300": ["Goodwill"], "BS-2400": ["IntangibleAssetsOtherThanGoodwill", "OtherIntangibleAssets"], "BS-2500": ["NoncurrentFinancialAssets", "NoncurrentInvestments", "OtherNoncurrentFinancialAssets"], "BS-2600": ["OtherNoncurrentAssets", "OtherNoncurrentNonfinancialAssets"], "BS-2900": ["Assets"], "BS-3100": ["TradeAndOtherCurrentPayables", "CurrentTradePayables"], "BS-3200": ["CurrentPortionOfNoncurrentBorrowings", "ShorttermBorrowings", "CurrentBorrowings"], "BS-3300": ["CurrentProvisions", "OtherCurrentLiabilities", "OtherCurrentFinancialLiabilities"], "BS-3400": ["ContractLiabilities", "DeferredIncomeCurrent"], "BS-3500": ["CurrentLeaseLiabilities"], "BS-3900": ["CurrentLiabilities"], "BS-4100": ["NoncurrentPortionOfNoncurrentBorrowings", "NoncurrentBorrowings", "Borrowings"], "BS-4200": ["NoncurrentLeaseLiabilities"], "BS-4300": ["OtherNoncurrentLiabilities", "NoncurrentProvisions", "OtherNoncurrentFinancialLiabilities"], "BS-4900": ["Liabilities"], "BS-6100": ["IssuedCapital", "SharePremium"], "BS-6200": ["RetainedEarnings"], "BS-6300": ["TreasuryShares"], "BS-6400": ["OtherReserves", "ReserveOfExchangeDifferencesOnTranslation"], "BS-6900": ["Equity", "EquityAttributableToOwnersOfParent"], "BS-7000": ["EquityAndLiabilities"], # ── Cash Flow ───────────────────────────────────────────── "CF-1000": ["ProfitLoss", "ProfitLossAttributableToOwnersOfParent"], "CF-1100": ["DepreciationAndAmortisationExpense", "DepreciationExpense", "AdjustmentsForDepreciationAndAmortisationExpense"], "CF-1200": ["SharebasedPaymentExpense", "ShareBasedPaymentArrangementExpense"], "CF-1300": ["AdjustmentsForDeferredTax", "DeferredTaxExpenseIncome"], "CF-1400": ["OtherNoncashIncomeExpense", "AdjustmentsForNoncashItems"], "CF-2100": ["AdjustmentsForDecreaseIncreaseInTradeAccountReceivable", "DecreaseIncreaseInTradeAndOtherReceivables"], "CF-2200": ["AdjustmentsForDecreaseIncreaseInInventories", "DecreaseIncreaseInInventories"], "CF-2300": ["AdjustmentsForIncreaseDecreaseInTradeAccountPayable", "IncreaseDecreaseInTradeAndOtherPayables"], "CF-2400": ["AdjustmentsForIncreaseDecreaseInOtherOperatingCapital", "OtherInflowsOutflowsOfCashClassifiedAsOperatingActivities"], "CF-3000": ["CashFlowsFromUsedInOperatingActivities"], "CF-4100": ["PurchaseOfPropertyPlantAndEquipmentClassifiedAsInvestingActivities", "AdditionsOtherThanThroughBusinessCombinationsPropertyPlantAndEquipment"], "CF-4200": ["CashFlowsUsedInObtainingControlOfSubsidiariesOrOtherBusinessesClassifiedAsInvestingActivities", "AcquisitionOfBusinessesNetOfCashAcquired"], "CF-4300": ["PurchaseOfInvestmentsOtherThanInvestmentsAccountedForUsingEquityMethod", "PurchaseOfFinancialAssets"], "CF-4400": ["ProceedsFromSalesOfInvestmentsOtherThanInvestmentsAccountedForUsingEquityMethod", "ProceedsFromSalesOfFinancialAssets"], "CF-4500": ["OtherInflowsOutflowsOfCashClassifiedAsInvestingActivities"], "CF-4900": ["CashFlowsFromUsedInInvestingActivities"], "CF-5100": ["ProceedsFromBorrowingsClassifiedAsFinancingActivities", "ProceedsFromIssuanceOfDebt"], "CF-5200": ["RepaymentsOfBorrowingsClassifiedAsFinancingActivities", "RepaymentsOfBorrowings"], "CF-5300": ["PurchaseOfTreasurySharesClassifiedAsFinancingActivities", "PaymentsToAcquireOrRedeemEntitysShares"], "CF-5400": ["DividendsPaidClassifiedAsFinancingActivities", "DividendsPaid"], "CF-5500": ["ProceedsFromIssuingShares"], "CF-5600": ["OtherInflowsOutflowsOfCashClassifiedAsFinancingActivities"], "CF-5900": ["CashFlowsFromUsedInFinancingActivities"], "CF-6000": ["EffectOfExchangeRateChangesOnCashAndCashEquivalents"], "CF-6100": ["IncreaseDecreaseInCashAndCashEquivalents", "IncreaseDecreaseInCashAndCashEquivalentsBeforeEffectOfExchangeRateChanges"], "CF-6200": ["CashAndCashEquivalents"], # instant — beginning balance "CF-6300": ["CashAndCashEquivalents"], # instant — ending balance } class DataProcessor: """Processes raw SEC XBRL data into structured financial statements.""" def __init__(self, company_facts: dict, submissions: dict): self.facts = company_facts self.submissions = submissions self.entity_name = company_facts.get("entityName", "Unknown") self.cik = company_facts.get("cik", 0) # Parse fiscal year end from submissions fye = submissions.get("fiscalYearEnd", "1231") self.fiscal_year_end_month = int(fye[:2]) self.fiscal_year_end_day = int(fye[2:]) self.sic = submissions.get("sic", "") self.sic_desc = submissions.get("sicDescription", "") # Detect IFRS vs US-GAAP raw_usgaap = self.facts.get("facts", {}).get("us-gaap", {}) self.ifrs = self.facts.get("facts", {}).get("ifrs-full", {}) self.is_ifrs = len(self.ifrs) > 0 and len(raw_usgaap) == 0 self.dei = self.facts.get("facts", {}).get("dei", {}) if self.is_ifrs: # Detect filing currency (may not be USD) self.filing_currency = self._detect_ifrs_currency() # Build synthetic us-gaap namespace from IFRS data self.usgaap = self._build_usgaap_from_ifrs() else: self.filing_currency = "USD" self.usgaap = raw_usgaap def _detect_ifrs_currency(self) -> str: """Detect the primary filing currency for an IFRS filer. Checks a few high-level concepts for which currency units are present.""" for probe in ("Revenue", "ProfitLoss", "Assets", "CashAndCashEquivalents"): concept_data = self.ifrs.get(probe, {}) units = concept_data.get("units", {}) if "USD" in units: return "USD" # Return first non-per-share currency found for unit_key in units: if "/" not in unit_key: # skip "USD/shares" etc. return unit_key return "USD" # fallback def _build_usgaap_from_ifrs(self) -> dict: """Translate IFRS facts into a synthetic us-gaap dict. For each SMB code, find the first matching IFRS concept and store its data under the first us-gaap concept name that xbrl_mapper expects. All downstream code then works unchanged.""" all_concepts = get_all_concepts() synthetic = {} currency = self.filing_currency for code, cdef in all_concepts.items(): ifrs_names = IFRS_CONCEPT_MAP.get(code, []) if not ifrs_names: continue # Target: the first us-gaap concept name xbrl_mapper would look for target_gaap_name = cdef["concepts"][0] for ifrs_name in ifrs_names: ifrs_data = self.ifrs.get(ifrs_name, {}) if not ifrs_data: continue units = ifrs_data.get("units", {}) # Try filing currency first, then USD entries = units.get(currency, []) if not entries and currency != "USD": entries = units.get("USD", []) # For per-share concepts, try currency/shares patterns unit_type = cdef.get("unit", "") if unit_type == "USD/shares": entries = units.get(f"{currency}/shares", []) if not entries: entries = units.get("USD/shares", []) if not entries: # Try bare per-share keys for k in units: if "/shares" in k.lower(): entries = units[k] break elif unit_type == "shares" or cdef.get("scale_shares"): entries = units.get("shares", []) if not entries: entries = units.get("pure", []) if entries: # Store under the target gaap name so _resolve_concept finds it if target_gaap_name not in synthetic: synthetic[target_gaap_name] = { "label": ifrs_data.get("label", cdef.get("label", "")), "units": {}, } # Determine which unit key to store under if unit_type == "USD/shares": store_key = "USD/shares" elif unit_type == "shares" or cdef.get("scale_shares"): store_key = "shares" else: store_key = "USD" synthetic[target_gaap_name]["units"][store_key] = entries break # first matching IFRS concept wins return synthetic def _get_concept_entries(self, concept_name: str, unit_type="USD"): """Get all entries for a given XBRL concept and unit.""" concept_data = self.usgaap.get(concept_name, {}) units = concept_data.get("units", {}) return units.get(unit_type, []) def _parse_date(self, date_str: str): """Parse date string to datetime.""" if not date_str: return None try: return datetime.strptime(date_str, "%Y-%m-%d") except ValueError: return None def _duration_days(self, entry: dict) -> int: """Calculate duration in days for an entry.""" start = self._parse_date(entry.get("start", "")) end = self._parse_date(entry.get("end", "")) if start and end: return (end - start).days return 0 def _is_annual(self, entry: dict) -> bool: """Check if entry represents an annual period.""" d = self._duration_days(entry) return ANNUAL_MIN_DAYS <= d <= ANNUAL_MAX_DAYS def _is_quarterly(self, entry: dict) -> bool: """Check if entry represents a quarterly period.""" d = self._duration_days(entry) return QUARTERLY_MIN_DAYS <= d <= QUARTERLY_MAX_DAYS def _is_semi_annual(self, entry: dict) -> bool: """Check if entry represents a semi-annual (~180 day) period.""" d = self._duration_days(entry) return SEMI_ANNUAL_MIN_DAYS <= d <= SEMI_ANNUAL_MAX_DAYS def _is_quarterly_or_semi_annual(self, entry: dict) -> bool: """Accept both quarterly (80-100d) and semi-annual (170-190d) periods.""" return self._is_quarterly(entry) or self._is_semi_annual(entry) def _get_fiscal_year(self, entry: dict) -> int: """Extract fiscal year from entry.""" fy = entry.get("fy") if fy: return int(fy) # Fallback: use end date end = self._parse_date(entry.get("end", "")) if end: return end.year return 0 def _get_fiscal_period(self, entry: dict) -> str: """Extract fiscal period (FY, Q1, Q2, Q3, Q4).""" return entry.get("fp", "") def _resolve_concept(self, concept_def: dict, entries_filter, unit_type="USD"): """ Try each concept name in priority order and MERGE across all variants. Earlier concepts in the list have priority: if concept A already populated FY2022, concept B will not overwrite it even if concept B has a more recent filing date. Within the SAME concept name, most-recently-filed wins (handles restatements / amendments). This handles the common case where a company switches XBRL tags mid-history (e.g., Revenues → RevenueFromContractWithCustomer after ASC 606 adoption). Each concept fills the years the others missed, producing a complete time series. """ concepts_list = concept_def["concepts"] merged = {} # (fy, fp) -> entry merged_concept = {} # (fy, fp) -> concept_index (priority tracking) primary_concept = None for concept_idx, concept_name in enumerate(concepts_list): entries = self._get_concept_entries(concept_name, unit_type) if not entries: continue filtered = [e for e in entries if entries_filter(e)] if not filtered: continue if primary_concept is None: primary_concept = concept_name # Deduplicate: for each entry, derive the fiscal year from # the END date (most reliable) and keep most-recently-filed # within the same concept priority tier. for e in filtered: end_date = self._parse_date(e.get("end", "")) if not end_date: continue # Determine the fiscal year this entry actually belongs to. # Use end-date year, adjusted if fiscal year doesn't end Dec 31. fy_month = self.fiscal_year_end_month if fy_month != 12: # E.g., Apple FYE Sep: entry ending Sep 2023 → FY2023 if end_date.month <= fy_month: actual_fy = end_date.year else: actual_fy = end_date.year + 1 else: actual_fy = end_date.year fp = self._get_fiscal_period(e) if not fp: fp = "FY" if self._is_annual(e) else "" key = (actual_fy, fp) filed = e.get("filed", "") prev_idx = merged_concept.get(key) if prev_idx is None: # No data for this period yet — take it merged[key] = e merged[key]["_actual_fy"] = actual_fy merged_concept[key] = concept_idx elif concept_idx == prev_idx and filed > merged[key]["filed"]: # Same concept, more recent filing — update (restatement) merged[key] = e merged[key]["_actual_fy"] = actual_fy # If concept_idx > prev_idx, skip — higher-priority concept # already populated this period. if merged: # Re-key with actual_fy; carry match metadata result = {} match_info = {} for orig_key, e in merged.items(): fy = e.get("_actual_fy", self._get_fiscal_year(e)) fp = orig_key[1] new_key = (fy, fp) result[new_key] = e cidx = merged_concept.get(orig_key, 0) match_info[new_key] = { "concept_idx": cidx, "concept_name": concepts_list[cidx] if cidx < len(concepts_list) else concepts_list[0], "total_candidates": len(concepts_list), } return primary_concept or concepts_list[0], result, match_info return None, {}, {} def _resolve_instant_concept(self, concept_def: dict, period_type="end"): """ Resolve an instant (balance sheet) concept. Merges data across concept name variants so older eras (which may use different XBRL tags) still populate. Earlier concepts in the list have priority: if concept A already populated a date, concept B will not overwrite it. Within the same concept, most-recently-filed wins (restatements/amendments). Key insight: each 10-K filing reports TWO balance-sheet dates (current year and prior-year comparative), both tagged with the same fy. We key by end-date to avoid mixing comparatives with current-year values, then map end-dates to fiscal years. """ concepts_list = concept_def["concepts"] # Key by end_date (string) -> entry (priority-aware) by_end_date = {} by_end_date_priority = {} # (end_str, fp) -> concept_idx primary_concept = None for concept_idx, concept_name in enumerate(concepts_list): entries = self._get_concept_entries(concept_name) if not entries: continue # Instant items have 'end' but no 'start' instant_entries = [e for e in entries if not e.get("start") and e.get("end") and e.get("form") in ("10-K", "10-Q", "10-K/A", "10-Q/A", "20-F", "20-F/A", "6-K", "6-K/A")] if not instant_entries: # Some entries have both start and end for instant items instant_entries = [e for e in entries if e.get("end") and e.get("form") in ("10-K", "10-Q", "10-K/A", "10-Q/A", "20-F", "20-F/A", "6-K", "6-K/A")] if not instant_entries: continue if primary_concept is None: primary_concept = concept_name for e in instant_entries: end_str = e.get("end", "") fp = self._get_fiscal_period(e) key = (end_str, fp) filed = e.get("filed", "") prev_idx = by_end_date_priority.get(key) if prev_idx is None: by_end_date[key] = e by_end_date_priority[key] = concept_idx elif concept_idx == prev_idx and filed > by_end_date[key]["filed"]: by_end_date[key] = e if not by_end_date: return None, {}, {} # Now map end_date -> fiscal year using our FYE logic merged = {} # (fy, fp) -> entry merged_priority = {} # (fy, fp) -> concept_idx fy_month = self.fiscal_year_end_month for (end_str, fp), e in by_end_date.items(): end_date = self._parse_date(end_str) if not end_date: continue # Determine fiscal year from the end_date if fy_month != 12: if end_date.month <= fy_month: actual_fy = end_date.year else: actual_fy = end_date.year + 1 else: actual_fy = end_date.year key = (actual_fy, fp) filed = e.get("filed", "") if key not in merged or filed > merged[key]["filed"]: merged[key] = e merged[key]["_actual_fy"] = actual_fy merged_priority[key] = by_end_date_priority.get((end_str, fp), 0) # Re-key with actual_fy; carry match metadata result = {} match_info = {} for orig_key, e in merged.items(): fy = e.get("_actual_fy", self._get_fiscal_year(e)) fp = orig_key[1] new_key = (fy, fp) result[new_key] = e cidx = merged_priority.get(orig_key, 0) match_info[new_key] = { "concept_idx": cidx, "concept_name": concepts_list[cidx] if cidx < len(concepts_list) else concepts_list[0], "total_candidates": len(concepts_list), } return primary_concept or concepts_list[0], result, match_info def _build_confidence_entry(self, code, cdef, match_info_for_period=None): """Build a confidence_map entry for a line item. Args: code: line item code (e.g. "IS-1000") cdef: concept definition from xbrl_mapper match_info_for_period: dict with concept_idx, concept_name, total_candidates from the resolve call (None if no XBRL match) Returns: dict with confidence metadata """ has_formula = bool(cdef.get("formula")) if match_info_for_period is None: # No XBRL match found if has_formula: return { "confidence": "derived", "concept_matched": None, "match_position": None, "total_candidates": len(cdef.get("concepts", [])), "is_formula": True, "formula": cdef["formula"], "source": "formula", } return { "confidence": "fallback", "concept_matched": None, "match_position": None, "total_candidates": len(cdef.get("concepts", [])), "is_formula": False, "source": "default", } cidx = match_info_for_period["concept_idx"] cname = match_info_for_period["concept_name"] total = match_info_for_period["total_candidates"] # primary = matched on 1st or 2nd concept (idx 0 or 1) # secondary = matched on 3rd+ concept (idx >= 2) if cidx <= 1: confidence = "primary" else: confidence = "secondary" return { "confidence": confidence, "concept_matched": cname, "match_position": cidx + 1, # 1-based "total_candidates": total, "is_formula": has_formula, "source": "xbrl", } def extract_annual_data(self) -> dict: """ Extract all annual financial data. Returns: { "years": [2019, 2020, ...], "is_data": {"IS-1000": {2019: val, 2020: val, ...}, ...}, "bs_data": {"BS-1100": {2019: val, ...}, ...}, "cf_data": {"CF-1000": {2019: val, ...}, ...}, "concept_map": {"IS-1000": "RevenueFromContract...", ...}, "confidence_map": {"IS-1000": {"confidence": "primary", ...}, ...}, } """ is_data, bs_data, cf_data = {}, {}, {} concept_map = {} confidence_map = {} all_years = set() # ── Income Statement (duration-based, annual) ── for code, cdef in IS_CONCEPTS.items(): unit = "USD" if cdef.get("unit") == "USD/shares": unit = "USD/shares" elif cdef.get("unit") == "shares" or cdef.get("scale_shares"): unit = "shares" def annual_filter(e): return (self._is_annual(e) and e.get("form") in ("10-K", "10-K/A", "S-1", "20-F", "20-F/A")) concept_name, by_period, match_info = self._resolve_concept(cdef, annual_filter, unit) if concept_name: concept_map[code] = concept_name is_data[code] = {} # Use first available match_info entry for code-level confidence first_mi = next(iter(match_info.values()), None) confidence_map[code] = self._build_confidence_entry(code, cdef, first_mi) for (fy, fp), entry in by_period.items(): val = entry["val"] if unit == "USD": val = val / SCALE_FACTOR val *= cdef.get("sign", 1) elif cdef.get("scale_shares"): val = val / SCALE_FACTOR # millions is_data[code][fy] = val all_years.add(fy) elif cdef.get("formula"): # No XBRL match but has formula — mark as derived confidence_map[code] = self._build_confidence_entry(code, cdef, None) # ── Balance Sheet (instant, annual 10-K year-end) ── for code, cdef in BS_CONCEPTS.items(): concept_name, by_period, match_info = self._resolve_instant_concept(cdef) if concept_name: concept_map[code] = concept_name bs_data[code] = {} first_mi = next(iter(match_info.values()), None) confidence_map[code] = self._build_confidence_entry(code, cdef, first_mi) for (fy, fp), entry in by_period.items(): # Only take FY (year-end) values for annual if fp != "FY": continue val = entry["val"] / SCALE_FACTOR * cdef.get("sign", 1) bs_data[code][fy] = val all_years.add(fy) # ── Cash Flow (duration-based, annual) ── for code, cdef in CF_CONCEPTS.items(): ctype = cdef["type"] if ctype == "duration": def annual_cf_filter(e): return (self._is_annual(e) and e.get("form") in ("10-K", "10-K/A", "S-1", "20-F", "20-F/A")) concept_name, by_period, match_info = self._resolve_concept(cdef, annual_cf_filter) elif ctype in ("instant_start", "instant_end"): concept_name, by_period, match_info = self._resolve_instant_concept(cdef) else: continue if concept_name: concept_map[code] = concept_name cf_data[code] = {} first_mi = next(iter(match_info.values()), None) confidence_map[code] = self._build_confidence_entry(code, cdef, first_mi) for (fy, fp), entry in by_period.items(): if ctype == "duration": # Only take FY-tagged entries for annual CF if fp != "FY": continue elif ctype == "instant_end": if fp != "FY": continue elif ctype == "instant_start": if fp != "FY": continue val = entry["val"] / SCALE_FACTOR * cdef.get("sign", 1) if ctype == "instant_start": # Balance at FYE is the BEGINNING of the next fiscal year cf_data[code][fy + 1] = val # Don't expand year range; let IS/BS determine columns else: cf_data[code][fy] = val all_years.add(fy) years = sorted(all_years) # ── 52/53-week fiscal year detection ── # Retail filers (WMT, COST, TGT, NKE) use 52/53-week calendars. # Annual periods are 364 or 371 days instead of 365. is_52_53_week = False _week_year_periods = [] # Sample a duration concept (revenue) to check period lengths for code in ("IS-1000", "IS-7000", "IS-9000"): cdef = IS_CONCEPTS.get(code) if not cdef: continue for concept_name in cdef["concepts"]: entries = self._get_concept_entries(concept_name) if not entries: continue for e in entries: if e.get("form") in ("10-K", "10-K/A") and e.get("fp") == "FY": d = self._duration_days(e) if d in (364, 371): is_52_53_week = True _week_year_periods.append( {"fy": self._get_fiscal_year(e), "days": d, "weeks": d // 7} ) if is_52_53_week: break if is_52_53_week: break result = { "years": years, "is_data": is_data, "bs_data": bs_data, "cf_data": cf_data, "concept_map": concept_map, "confidence_map": confidence_map, } if is_52_53_week: result["_is_52_53_week"] = True result["_52_53_week_periods"] = _week_year_periods # ── Fiscal year end change detection ── self._detect_fye_changes(result) # ── Preferred stock detection ── self._detect_preferred_stock(result) # ── Dual-class share structure detection ── self._detect_dual_class_shares(result) # ── Stub period detection (M&A, FYE change, IPO mid-year) ── self._detect_stub_periods(result) # ── Limited history flag (spin-off / IPO) ── n_years = len(result["years"]) result["_limited_history"] = n_years < 3 result["_history_years"] = n_years return result def _detect_fye_changes(self, annual_data: dict): """Detect if the company changed its fiscal year end during the data period. Looks at end-date months of annual periods across years. If the month changes, a FYE change occurred (e.g., Dec -> Sep transition). """ end_months = {} for concept_name in ['Revenues', 'RevenueFromContractWithCustomerExcludingAssessedTax', 'NetIncomeLoss', 'ProfitLoss']: concept_data = self.usgaap.get(concept_name, {}) if not concept_data: continue entries = concept_data.get('units', {}).get('USD', []) for e in entries: if e.get('fp') == 'FY': end = e.get('end', '') fy = e.get('fy') if end and fy: try: month = int(end.split('-')[1]) end_months[fy] = month except (IndexError, ValueError): pass if end_months: break unique_months = set(end_months.values()) if len(unique_months) > 1: annual_data["_fye_change"] = { "detected": True, "end_months_by_year": end_months, "note": f"FYE changed: months {unique_months}", } else: annual_data["_fye_change"] = {"detected": False} def _detect_preferred_stock(self, annual_data: dict): """Detect whether the company has preferred stock outstanding. Checks for non-zero values in preferred-stock-related XBRL concepts. If found, downstream writers can note that EPS is adjusted for preferred dividends. """ preferred = False pref_concepts = [ 'PreferredStockValue', 'PreferredStockValueOutstanding', 'TemporaryEquityCarryingAmountAttributableToParent', 'RedeemableNoncontrollingInterestEquityPreferredStockCarryingAmount', 'DividendsPreferredStock', 'PreferredStockDividendsPerShareDeclared', ] for concept in pref_concepts: concept_data = self.usgaap.get(concept, {}) if not concept_data: continue entries = concept_data.get('units', {}).get('USD', []) fy_entries = [e for e in entries if e.get('fp') == 'FY' and e.get('val', 0) != 0] if fy_entries: preferred = True break annual_data["_has_preferred_stock"] = preferred def _detect_dual_class_shares(self, annual_data: dict): """Detect dual-class share structures (e.g., GOOG/GOOGL, META, BRK). Checks for multiple EPS values per fiscal year (different share classes) and for multiple share-count entries with different segments on the same date. """ dual_class = False # Check EPS entries for multiple distinct values per FY for eps_name in ['EarningsPerShareBasic', 'EarningsPerShareDiluted']: eps_concept = self.usgaap.get(eps_name, {}) if not eps_concept: continue entries = eps_concept.get('units', {}).get('USD/shares', []) fy_entries = [e for e in entries if e.get('fp') == 'FY'] for fy in set(e.get('fy') for e in fy_entries): year_entries = [e for e in fy_entries if e.get('fy') == fy] unique_vals = set(e.get('val') for e in year_entries) if len(unique_vals) > 2: dual_class = True break if dual_class: break # Also check dei namespace for multiple share class entries on same date if not dual_class: for concept in ['EntityCommonStockSharesOutstanding']: concept_data = self.dei.get(concept, {}) if not concept_data: continue entries = concept_data.get('units', {}).get('shares', []) dates = {} for e in entries: end = e.get('end', '') seg = e.get('segment', '') if end: dates.setdefault(end, set()).add(str(seg)) if any(len(segs) > 1 for segs in dates.values()): dual_class = True annual_data["_dual_class_shares"] = dual_class def _detect_stub_periods(self, annual_data: dict): """Flag fiscal years shorter than 340 days as stub periods. Stub periods arise from mid-year acquisitions, fiscal year end changes, or mid-year IPOs. Growth rates across stub periods are not comparable. """ stubs = [] for concept_name in ['Revenues', 'RevenueFromContractWithCustomerExcludingAssessedTax', 'ProfitLoss', 'NetIncomeLoss']: concept_data = self.usgaap.get(concept_name, {}) if not concept_data: continue entries = concept_data.get('units', {}).get('USD', []) for e in entries: if e.get('fp') == 'FY': start = e.get('start', '') end = e.get('end', '') if start and end: try: d1 = datetime.strptime(start, '%Y-%m-%d') d2 = datetime.strptime(end, '%Y-%m-%d') days = (d2 - d1).days fy = e.get('fy') if days < 340 and fy: # normal FY is 350-380 days stubs.append({ "year": int(fy) if fy else 0, "days": days, "start": start, "end": end, "note": f"Stub period: {days} days ({start} to {end})", }) except (ValueError, TypeError): pass if stubs: break # Deduplicate by year seen = set() unique_stubs = [] for s in stubs: if s["year"] not in seen: seen.add(s["year"]) unique_stubs.append(s) annual_data["_stub_periods"] = unique_stubs def extract_quarterly_data(self, annual_data: dict = None) -> dict: """ Extract quarterly financial data. Returns same structure as annual but keyed by (year, quarter). If annual_data is provided, derives Q4 = FY - Q1 - Q2 - Q3 for IS and CF items. """ is_data, bs_data, cf_data = {}, {}, {} concept_map = {} all_periods = set() # ── Income Statement (quarterly) ── for code, cdef in IS_CONCEPTS.items(): unit = "USD" if cdef.get("unit") == "USD/shares": unit = "USD/shares" elif cdef.get("unit") == "shares" or cdef.get("scale_shares"): unit = "shares" def qtr_filter(e): duration_ok = (self._is_quarterly_or_semi_annual(e) if self.is_ifrs else self._is_quarterly(e)) return (duration_ok and e.get("form") in ("10-Q", "10-Q/A", "10-K", "10-K/A", "20-F", "20-F/A", "6-K", "6-K/A")) concept_name, by_period, _mi = self._resolve_concept(cdef, qtr_filter, unit) if concept_name: concept_map[code] = concept_name is_data[code] = {} for (fy, fp), entry in by_period.items(): if fp not in ("Q1", "Q2", "Q3", "Q4"): continue val = entry["val"] if unit == "USD": val = val / SCALE_FACTOR val *= cdef.get("sign", 1) elif cdef.get("scale_shares"): val = val / SCALE_FACTOR period_key = f"{fp} {fy}" is_data[code][period_key] = val all_periods.add(period_key) # ── Balance Sheet (quarterly) ── for code, cdef in BS_CONCEPTS.items(): concept_name, by_period, _mi = self._resolve_instant_concept(cdef) if concept_name: concept_map[code] = concept_name bs_data[code] = {} for (fy, fp), entry in by_period.items(): if fp not in ("Q1", "Q2", "Q3", "Q4", "FY"): continue period_key = f"{'Q4' if fp == 'FY' else fp} {fy}" val = entry["val"] / SCALE_FACTOR * cdef.get("sign", 1) bs_data[code][period_key] = val all_periods.add(period_key) # ── Cash Flow (quarterly) ── # CF items are often cumulative YTD (Q2=6mo, Q3=9mo) not standalone. # Capture ALL Q1/Q2/Q3 entries regardless of duration, then convert # cumulative to standalone: Q2_std = Q2_cum - Q1, Q3_std = Q3_cum - Q2_cum for code, cdef in CF_CONCEPTS.items(): ctype = cdef["type"] if ctype == "duration": # Accept any entry tagged Q1/Q2/Q3 from 10-Q/10-K def qtr_cf_filter(e): return (e.get("fp") in ("Q1", "Q2", "Q3", "Q4") and e.get("form") in ("10-Q", "10-Q/A", "10-K", "10-K/A", "20-F", "20-F/A", "6-K", "6-K/A") and self._duration_days(e) > 0) concept_name, by_period, _mi = self._resolve_concept(cdef, qtr_cf_filter) elif ctype in ("instant_start", "instant_end"): concept_name, by_period, _mi = self._resolve_instant_concept(cdef) else: continue if concept_name: concept_map[code] = concept_name cf_data[code] = {} if ctype == "duration": # Group entries by fiscal year, detect cumulative vs standalone by_fy = {} for (fy, fp), entry in by_period.items(): if fp not in ("Q1", "Q2", "Q3", "Q4"): continue by_fy.setdefault(fy, {})[fp] = entry sign = cdef.get("sign", 1) for fy, qtr_entries in by_fy.items(): vals = {} for fp, entry in sorted(qtr_entries.items()): raw = entry["val"] / SCALE_FACTOR * sign days = self._duration_days(entry) vals[fp] = {"raw": raw, "days": days} # Detect cumulative: Q2 duration > 150 days = YTD q2_cum = vals.get("Q2", {}).get("days", 0) > 150 q3_cum = vals.get("Q3", {}).get("days", 0) > 250 for fp in ("Q1", "Q2", "Q3", "Q4"): if fp not in vals: continue raw = vals[fp]["raw"] if fp == "Q2" and q2_cum and "Q1" in vals: raw = raw - vals["Q1"]["raw"] elif fp == "Q3" and q3_cum and "Q2" in vals: raw = raw - vals["Q2"]["raw"] period_key = f"{fp} {fy}" cf_data[code][period_key] = raw all_periods.add(period_key) else: # Instant items (BS-like) for (fy, fp), entry in by_period.items(): if fp not in ("Q1", "Q2", "Q3", "Q4", "FY"): continue period_key = f"{'Q4' if fp == 'FY' else fp} {fy}" val = entry["val"] / SCALE_FACTOR * cdef.get("sign", 1) cf_data[code][period_key] = val all_periods.add(period_key) # Sort periods chronologically def period_sort_key(p): parts = p.split() qtr = {"Q1": 1, "Q2": 2, "Q3": 3, "Q4": 4}.get(parts[0], 0) yr = int(parts[1]) if len(parts) > 1 else 0 return (yr, qtr) periods = sorted(all_periods, key=period_sort_key) result = { "periods": periods, "is_data": is_data, "bs_data": bs_data, "cf_data": cf_data, "concept_map": concept_map, } # Detect semi-annual reporting (European ADRs: only H1 ~180d, labeled Q2) # Check IS data specifically — BS has FY snapshots mapped as Q4 which # don't indicate quarterly reporting. semi_annual = False if self.is_ifrs and is_data: is_periods = set() for code_vals in is_data.values(): is_periods.update(code_vals.keys()) if is_periods: has_q1 = any("Q1" in p for p in is_periods) has_q3 = any("Q3" in p for p in is_periods) has_q2 = any("Q2" in p for p in is_periods) # Semi-annual: has Q2 (H1) but no Q1 or Q3 if has_q2 and not has_q1 and not has_q3: semi_annual = True self.is_semi_annual = semi_annual if semi_annual and annual_data: result = self._convert_to_semi_annual(result, annual_data) elif annual_data: # Derive Q4 = FY - Q1 - Q2 - Q3 for IS and CF duration items self._derive_q4(result, annual_data) result["_reporting_frequency"] = "quarterly" else: result["_reporting_frequency"] = "quarterly" return result def _convert_to_semi_annual(self, qtr_data: dict, annual_data: dict) -> dict: """Convert quarterly data with only H1 (~180d, labeled Q2) to H1/H2 semi-annual. H1 = the existing Q2 value (the reported 6-month period). H2 = FY - H1 for IS and CF duration items. BS: H1 uses the interim snapshot; H2 uses FY year-end values. """ new_is, new_bs, new_cf = {}, {}, {} new_periods = set() for period in qtr_data["periods"]: parts = period.split() if len(parts) != 2: continue try: year = int(parts[1]) except ValueError: continue h1_label = f"H1 {year}" h2_label = f"H2 {year}" # ── Relabel Q2 → H1 across all sections ── for section, dest in [("is_data", new_is), ("bs_data", new_bs), ("cf_data", new_cf)]: src = qtr_data[section] for code, vals in src.items(): if period in vals: if code not in dest: dest[code] = {} dest[code][h1_label] = vals[period] new_periods.add(h1_label) # ── Derive H2 = FY - H1 for IS duration items ── if year in annual_data.get("years", []): for code in annual_data.get("is_data", {}): fy_val = annual_data["is_data"][code].get(year) h1_val = qtr_data["is_data"].get(code, {}).get(period) if fy_val is not None and h1_val is not None: if code not in new_is: new_is[code] = {} new_is[code][h2_label] = fy_val - h1_val # ── Derive H2 = FY - H1 for CF duration items ── for code, cdef in CF_CONCEPTS.items(): if cdef["type"] != "duration": continue fy_val = annual_data.get("cf_data", {}).get(code, {}).get(year) h1_val = qtr_data["cf_data"].get(code, {}).get(period) if fy_val is not None and h1_val is not None: if code not in new_cf: new_cf[code] = {} new_cf[code][h2_label] = fy_val - h1_val # ── BS H2 = FY year-end snapshot ── for code in annual_data.get("bs_data", {}): fy_val = annual_data["bs_data"][code].get(year) if fy_val is not None: if code not in new_bs: new_bs[code] = {} new_bs[code][h2_label] = fy_val new_periods.add(h2_label) # Sort periods chronologically: H1 before H2, by year def semi_sort_key(p): parts = p.split() half = 1 if parts[0] == "H1" else 2 yr = int(parts[1]) if len(parts) > 1 else 0 return (yr, half) return { "periods": sorted(new_periods, key=semi_sort_key), "is_data": new_is, "bs_data": new_bs, "cf_data": new_cf, "concept_map": qtr_data.get("concept_map", {}), "_reporting_frequency": "semi_annual", } def _derive_q4(self, qtr_data: dict, annual_data: dict): """Derive Q4 for IS and CF duration items: Q4 = FY_annual - Q1 - Q2 - Q3.""" # Collect years present in quarterly data years_seen = set() for period in qtr_data["periods"]: parts = period.split() if len(parts) == 2: try: years_seen.add(int(parts[1])) except ValueError: pass new_periods = set(qtr_data["periods"]) for yr in years_seen: q1k, q2k, q3k, q4k = f"Q1 {yr}", f"Q2 {yr}", f"Q3 {yr}", f"Q4 {yr}" # IS items for code, cdef in IS_CONCEPTS.items(): fy_val = annual_data["is_data"].get(code, {}).get(yr) q_data = qtr_data["is_data"].get(code, {}) q1, q2, q3 = q_data.get(q1k), q_data.get(q2k), q_data.get(q3k) if fy_val is not None and q1 is not None and q2 is not None and q3 is not None: if q4k not in q_data: if code not in qtr_data["is_data"]: qtr_data["is_data"][code] = {} qtr_data["is_data"][code][q4k] = fy_val - q1 - q2 - q3 new_periods.add(q4k) # CF duration items only (BS instant already maps FY→Q4) for code, cdef in CF_CONCEPTS.items(): if cdef["type"] != "duration": continue fy_val = annual_data["cf_data"].get(code, {}).get(yr) q_data = qtr_data["cf_data"].get(code, {}) q1, q2, q3 = q_data.get(q1k), q_data.get(q2k), q_data.get(q3k) if fy_val is not None and q1 is not None and q2 is not None and q3 is not None: if q4k not in q_data: if code not in qtr_data["cf_data"]: qtr_data["cf_data"][code] = {} qtr_data["cf_data"][code][q4k] = fy_val - q1 - q2 - q3 new_periods.add(q4k) # Re-sort periods def period_sort_key(p): parts = p.split() qtr = {"Q1": 1, "Q2": 2, "Q3": 3, "Q4": 4}.get(parts[0], 0) yr = int(parts[1]) if len(parts) > 1 else 0 return (yr, qtr) qtr_data["periods"] = sorted(new_periods, key=period_sort_key)