""" raq_extractor.py ---------------- Generic extractor for the RBI 'Report on Asset Quality' (RAQ) XBRL template. The template has 25 sheets, each with a different table layout. Layouts are described by IRIS/iFile markers (#LAYOUTSCSR#, #LAYOUTECSR#, #TABLE#, #CustPlc#, #SERIAL#, #TYPDIM#) and the data rows are tagged in column B with an XBRL element reference of the form `in-rbi-rep.xsd#in-rbi-rep_`. Rather than hard-coding 25 different parsers, we harvest every populated cell into a single tidy "long" frame, attaching the best-effort row label (nearest text to the left) and column header (nearest text above). This is robust to the structural differences between sheets and is exactly the shape the data-quality engine needs. Public API ---------- extract_workbook(path) -> RAQExtract .meta : dict (return code, bank, period, dates, version ...) .long : DataFrame one row per populated data cell .by_sheet : dict[str, DataFrame] convenience per-sheet pivots .sheets : list[str] data sheets found """ from __future__ import annotations import re from dataclasses import dataclass, field from datetime import datetime import openpyxl import pandas as pd ELEMENT_PREFIX = "in-rbi-rep.xsd#" MARKERS = { "#LAYOUTSCSR#", "#LAYOUTECSR#", "#LAYOUTSCER#", "#LAYOUTECER#", "#TABLE#", "#CustPlc#", "#SERIAL#", "#TYPDIM#", "#LAYOUTSCSR#", } # sheets that are config / taxonomy plumbing, not reportable data NON_DATA_SHEETS = { "StartUpDataSheet", "MainSheet", "Navigation", "StartUp", "Data", "+FootnoteTexts", "+Elements", "+Lineitems", } def _is_marker(v) -> bool: return isinstance(v, str) and v.strip() in MARKERS def _is_element(v) -> bool: return isinstance(v, str) and v.startswith(ELEMENT_PREFIX) def _is_text(v) -> bool: return isinstance(v, str) and v.strip() != "" and not _is_marker(v) and not _is_element(v) def _clean_label(v: str) -> str: s = re.sub(r"\s+", " ", str(v)).strip() return s def _concept_from_element(v: str) -> str: # in-rbi-rep.xsd#in-rbi-rep_AssetsCurrentTermLoans -> AssetsCurrentTermLoans tail = v.split("#")[-1] return tail.split("in-rbi-rep_")[-1] if "in-rbi-rep_" in tail else tail @dataclass class RAQExtract: meta: dict = field(default_factory=dict) long: pd.DataFrame = field(default_factory=pd.DataFrame) by_sheet: dict = field(default_factory=dict) sheets: list = field(default_factory=list) def _extract_meta(wb) -> dict: """Pull return-level metadata from the General Information sheet.""" meta = {} if "General Information" not in wb.sheetnames: return meta ws = wb["General Information"] for row in ws.iter_rows(values_only=True): cells = [c for c in row if c is not None] # rows look like: |