Skip to content

API reference

The importable Python surface: the loading and summary functions, the SepaMessageSummary dataclass, and SepaStatementParser, the BankStatementParser the core discovers through the sepa, pain002 and pain008 entry points in bankstatementparser.loaders. Generated from the docstrings by mkdocstrings.

bankstatementparser_loader_sepa.loader

Core ISO 20022 SEPA PAIN.002 & PAIN.008 Statement Loader.

SepaMessageSummary dataclass

Summary metrics and headers for a SEPA PAIN.002 or PAIN.008 message.

Source code in bankstatementparser_loader_sepa/loader.py
66
67
68
69
70
71
72
73
74
75
76
@dataclass(frozen=True)
class SepaMessageSummary:
    """Summary metrics and headers for a SEPA PAIN.002 or PAIN.008 message."""

    message_type: str
    message_id: str | None
    creation_date: datetime | None
    account_id: str | None
    currency: str | None
    item_count: int
    total_amount: Decimal

SepaStatementParser

Bases: BankStatementParser

BankStatementParser plugin implementation for SEPA PAIN.002 & PAIN.008 XML files.

Source code in bankstatementparser_loader_sepa/loader.py
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
class SepaStatementParser(BankStatementParser):
    """BankStatementParser plugin implementation for SEPA PAIN.002 & PAIN.008 XML files."""

    def __init__(self, file_name: str | Path, **kwargs: Any) -> None:
        """Initialize the SEPA parser.

        Args:
            file_name: Path to the SEPA XML file.
            **kwargs: Extra options passed to base parser.
        """
        super().__init__(file_name, **kwargs)
        self._summary_cache: SepaMessageSummary | None = None

    def parse(self) -> pd.DataFrame:
        """Parse the SEPA file into a pandas DataFrame.

        Returns:
            A pandas DataFrame containing standardized statement transactions.
        """
        txs = self.to_transactions()
        if not txs:
            return pd.DataFrame(
                columns=[
                    "date",
                    "description",
                    "amount",
                    "currency",
                    "account_id",
                    "reference",
                    "source",
                ]
            )

        records = [
            {
                "date": tx.booking_date.isoformat() if tx.booking_date else "",
                "description": tx.description or "",
                "amount": float(tx.amount),
                "currency": tx.currency,
                "account_id": tx.account_id,
                "reference": tx.reference,
                "source": tx.source,
            }
            for tx in txs
        ]
        return pd.DataFrame(records)

    def to_transactions(self) -> list[Transaction]:
        """Parse the SEPA file into a list of Transaction models.

        Returns:
            List of parsed Transaction instances.
        """
        return load_sepa_file(self.file_name)

    def get_summary(self) -> SepaSummaryRecord:
        """Get summary metadata and metrics for the SEPA file.

        Returns:
            Message statistics. ``total_amount`` is ``Decimal``, as
            ``SummaryRecord`` declares.
        """
        if self._summary_cache is None:
            content = Path(self.file_name).read_bytes()
            self._summary_cache = summarize_sepa(content)

        s = self._summary_cache
        return {
            "message_type": s.message_type,
            "message_id": s.message_id,
            "creation_date": (
                s.creation_date.isoformat() if s.creation_date else None
            ),
            "account_id": s.account_id,
            "currency": s.currency,
            "item_count": s.item_count,
            "total_amount": s.total_amount,
        }

__init__(file_name, **kwargs)

Initialize the SEPA parser.

Parameters:

Name Type Description Default
file_name str | Path

Path to the SEPA XML file.

required
**kwargs Any

Extra options passed to base parser.

{}
Source code in bankstatementparser_loader_sepa/loader.py
406
407
408
409
410
411
412
413
414
def __init__(self, file_name: str | Path, **kwargs: Any) -> None:
    """Initialize the SEPA parser.

    Args:
        file_name: Path to the SEPA XML file.
        **kwargs: Extra options passed to base parser.
    """
    super().__init__(file_name, **kwargs)
    self._summary_cache: SepaMessageSummary | None = None

parse()

Parse the SEPA file into a pandas DataFrame.

Returns:

Type Description
DataFrame

A pandas DataFrame containing standardized statement transactions.

Source code in bankstatementparser_loader_sepa/loader.py
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
def parse(self) -> pd.DataFrame:
    """Parse the SEPA file into a pandas DataFrame.

    Returns:
        A pandas DataFrame containing standardized statement transactions.
    """
    txs = self.to_transactions()
    if not txs:
        return pd.DataFrame(
            columns=[
                "date",
                "description",
                "amount",
                "currency",
                "account_id",
                "reference",
                "source",
            ]
        )

    records = [
        {
            "date": tx.booking_date.isoformat() if tx.booking_date else "",
            "description": tx.description or "",
            "amount": float(tx.amount),
            "currency": tx.currency,
            "account_id": tx.account_id,
            "reference": tx.reference,
            "source": tx.source,
        }
        for tx in txs
    ]
    return pd.DataFrame(records)

to_transactions()

Parse the SEPA file into a list of Transaction models.

Returns:

Type Description
list[Transaction]

List of parsed Transaction instances.

Source code in bankstatementparser_loader_sepa/loader.py
450
451
452
453
454
455
456
def to_transactions(self) -> list[Transaction]:
    """Parse the SEPA file into a list of Transaction models.

    Returns:
        List of parsed Transaction instances.
    """
    return load_sepa_file(self.file_name)

get_summary()

Get summary metadata and metrics for the SEPA file.

Returns:

Type Description
SepaSummaryRecord

Message statistics. total_amount is Decimal, as

SepaSummaryRecord

SummaryRecord declares.

Source code in bankstatementparser_loader_sepa/loader.py
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
def get_summary(self) -> SepaSummaryRecord:
    """Get summary metadata and metrics for the SEPA file.

    Returns:
        Message statistics. ``total_amount`` is ``Decimal``, as
        ``SummaryRecord`` declares.
    """
    if self._summary_cache is None:
        content = Path(self.file_name).read_bytes()
        self._summary_cache = summarize_sepa(content)

    s = self._summary_cache
    return {
        "message_type": s.message_type,
        "message_id": s.message_id,
        "creation_date": (
            s.creation_date.isoformat() if s.creation_date else None
        ),
        "account_id": s.account_id,
        "currency": s.currency,
        "item_count": s.item_count,
        "total_amount": s.total_amount,
    }

load_sepa(xml_content)

Parse a SEPA PAIN.002 or PAIN.008 XML payload into Transaction objects.

Parameters:

Name Type Description Default
xml_content str | bytes

XML payload string or bytes.

required

Returns:

Type Description
list[Transaction]

List of parsed Transaction instances.

Source code in bankstatementparser_loader_sepa/loader.py
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
def load_sepa(xml_content: str | bytes) -> list[Transaction]:
    """Parse a SEPA PAIN.002 or PAIN.008 XML payload into Transaction objects.

    Args:
        xml_content: XML payload string or bytes.

    Returns:
        List of parsed Transaction instances.
    """
    _, records = _parse_sepa_xml(xml_content)
    transactions: list[Transaction] = []

    for idx, rec in enumerate(records):
        tx = Transaction(
            account_id=rec.get("account_id"),
            currency=rec.get("currency", "EUR"),
            amount=rec["amount"],
            booking_date=rec.get("booking_date"),
            value_date=rec.get("value_date"),
            description=rec.get("description"),
            reference=rec.get("reference"),
            category=rec.get("category"),
            source=SOURCE,
            source_index=idx,
        )
        transactions.append(tx)

    return transactions

load_sepa_file(path)

Read and parse a SEPA PAIN.002 / PAIN.008 file from disk.

Parameters:

Name Type Description Default
path str | PathLike[str]

Path to the SEPA XML file.

required

Returns:

Type Description
list[Transaction]

List of Transaction instances.

Source code in bankstatementparser_loader_sepa/loader.py
365
366
367
368
369
370
371
372
373
374
375
def load_sepa_file(path: str | os.PathLike[str]) -> list[Transaction]:
    """Read and parse a SEPA PAIN.002 / PAIN.008 file from disk.

    Args:
        path: Path to the SEPA XML file.

    Returns:
        List of Transaction instances.
    """
    data = Path(path).read_bytes()
    return load_sepa(data)

summarize_sepa(xml_content)

Generate financial and message summary for a SEPA document.

Parameters:

Name Type Description Default
xml_content str | bytes

XML payload string or bytes.

required

Returns:

Type Description
SepaMessageSummary

A SepaMessageSummary instance.

Source code in bankstatementparser_loader_sepa/loader.py
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
def summarize_sepa(xml_content: str | bytes) -> SepaMessageSummary:
    """Generate financial and message summary for a SEPA document.

    Args:
        xml_content: XML payload string or bytes.

    Returns:
        A SepaMessageSummary instance.
    """
    header, records = _parse_sepa_xml(xml_content)
    total_amount = Decimal("0.00")
    for r in records:
        total_amount += abs(r["amount"])

    return SepaMessageSummary(
        message_type=header["message_type"],
        message_id=header["message_id"],
        creation_date=header["creation_date"],
        account_id=header["account_id"],
        currency=header["currency"],
        item_count=len(records),
        total_amount=total_amount,
    )