Skip to content

API reference

The importable Python surface: the loading and summary functions, the Bai2Summary dataclass, and Bai2StatementParser, the BankStatementParser the core discovers through the bankstatementparser.loaders entry point. Generated from the docstrings by mkdocstrings.

bankstatementparser_loader_bai2.loader

BAI2 -> bankstatementparser Transaction loader.

BAI2 <https://www.bai.org/>_ (Bank Administration Institute, version 2) is the de-facto US cash-management file format that banks ship for intraday and prior-day balance reporting. The published bankstatementparser <https://pypi.org/project/bankstatementparser/>_ library does not parse BAI2; this companion loader fills that gap by turning a BAI2 payload into a flat list of :class:bankstatementparser.transaction_models.Transaction objects that downstream deterministic logic can consume.

Supported (pragmatic) subset

BAI2 files are line-oriented. Each physical record is a sequence of comma-delimited fields and ends with a / record delimiter. Every record begins with a numeric type code identifying the record kind. This loader implements the following records:

01 File Header 01,senderId,receiverId,fileDate,fileTime,fileId,... -- the file must start with this record. fileId is captured for the summary.

02 Group Header 02,ultimateReceiver,originator,groupStatus,asOfDate,asOfTime,currency,... -- the group currency and asOfDate are captured. The as-of date becomes each transaction's booking_date; the group currency is the fallback currency for accounts that omit one.

03 Account Identifier 03,accountNumber,currencyCode,typeCode,amount,itemCount,fundsType,... -- accountNumber and the optional account currencyCode are captured. The account currency, when present, overrides the group currency for every transaction under this account.

16 Transaction Detail 16,typeCode,amount,fundsType,[funds-type subfields,]bankRefNum,customerRefNum,text -- one transaction. amount is an integer in the account currency's minor units (see "Amounts" below). text becomes the description.

The ``text`` field is **free-form and runs to the end of the
record, commas included**. Real-world BAI2 puts structured prose
there (``ACH Credit Payment,Entry Description: EXP; -, SEC: CCD,
...``), so the loader splits only the fixed leading fields and keeps
the remainder verbatim rather than naively splitting the whole
record on commas.

The ``fundsType`` field selects how many subfields sit between it
and ``bankRefNum``: ``V`` (value-dated) inserts ``valueDate`` and
``valueTime``; ``S`` (distributed availability) inserts three
availability amounts; everything else (``0``/``1``/``2``/``Z`` or
empty) inserts none. The loader counts these so ``bankRefNum``,
``customerRefNum``, and ``text`` are located correctly regardless of
funds type.

88 Continuation Continues the text of the immediately preceding 03 or 16 record; its content (everything after the leading 88 field, commas included) is appended to that record's description. A 88 that continues an 03 account summary, or one that has no preceding detail to attach to, is dropped rather than mis-attached.

49 Account Trailer, 98 Group Trailer, 99 File Trailer Control-total records. This loader ignores them -- it does not validate the control sums. Ignoring is a deliberate, documented choice: the goal is faithful transaction extraction, not file-level reconciliation.

Any other (or unknown) leading type code is ignored so that vendor extensions do not abort the parse.

Amounts

BAI2 amounts are unsigned integers expressed in the account currency's minor units (e.g. cents), with no decimal point. They are converted to :class:decimal.Decimal by dividing by 100 -- Decimal is used throughout (never float) to avoid binary rounding error. An empty amount field is treated as 0.

Sign convention (debit / credit)

BAI2 transaction type codes are grouped into documented numeric ranges that encode the direction of funds. This loader applies the following convention based on the numeric range of the 16 record's type code:

  • 100-399 -> credit (amount kept positive)
  • 400-699 -> debit (amount made negative)
  • 700-799 -> loan detail. Loan codes describe disbursements, advances, and payments on the loan side of a relationship file. This loader treats them as a debit-side movement (amount made negative), matching the "money leaving the reported balance" reading used for the 400-699 range.
  • 900-999 -> custom / summary / status. These are non-detail codes (institution-specific status and summary lines, not individual postings). This loader does not emit a Transaction for them; they are skipped so a status line never pollutes the posting list. Any continuations attached to a skipped status code are dropped with it.
  • anything else (including non-numeric codes) -> kept positive; the raw type code is preserved.

The raw BAI2 type code is always preserved on every emitted Transaction in both the category field (as bai2:<code>) and the reference field, so no information is lost.

Type-code descriptions

A small, optional lookup of well-known BAI2 transaction type codes (for example 142 "ACH credit" or 475 "Check paid") is used to enrich the Transaction.description when the 16 record itself carries no free-text. When the lookup has no entry, or the record already has text, the record's own text is used unchanged.

Bai2Summary dataclass

High-level counts and identifiers for a parsed BAI2 file.

Attributes:

Name Type Description
file_id str | None

The fileId field from the 01 File Header.

group_count int

Number of 02 Group Header records.

account_count int

Number of 03 Account Identifier records.

transaction_count int

Number of emitted transactions -- one per 16 Transaction Detail record, excluding skipped 900-999 custom/summary/status codes.

currency str | None

The first currency seen (account currency preferred, otherwise the group currency), or None if none was given.

Source code in bankstatementparser_loader_bai2/loader.py
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
@dataclass
class Bai2Summary:
    """High-level counts and identifiers for a parsed BAI2 file.

    Attributes:
        file_id: The ``fileId`` field from the ``01`` File Header.
        group_count: Number of ``02`` Group Header records.
        account_count: Number of ``03`` Account Identifier records.
        transaction_count: Number of emitted transactions -- one per
            ``16`` Transaction Detail record, excluding skipped
            ``900``-``999`` custom/summary/status codes.
        currency: The first currency seen (account currency preferred,
            otherwise the group currency), or ``None`` if none was given.
    """

    file_id: str | None
    group_count: int
    account_count: int
    transaction_count: int
    currency: str | None

Bai2StatementParser

Bases: BankStatementParser

BankStatementParser-compatible wrapper for BAI2 bank statement files.

Source code in bankstatementparser_loader_bai2/loader.py
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
class Bai2StatementParser(BankStatementParser):
    """BankStatementParser-compatible wrapper for BAI2 bank statement files."""

    def __init__(self, file_name: str | Path) -> None:
        """Initialize parser with path to BAI2 bank statement file."""
        super().__init__(file_name)
        self._parsed_df: pd.DataFrame | None = None
        self._summary: SummaryRecord | None = None

    def parse(self) -> pd.DataFrame:
        """Parse BAI2 statement transactions into a pandas DataFrame."""
        if self._parsed_df is not None:
            return self._parsed_df.copy()
        txs = load_bai2_file(self.file_name)
        records = [tx.model_dump() for tx in txs]
        self._parsed_df = pd.DataFrame(records)
        return self._parsed_df.copy()

    def get_summary(self) -> SummaryRecord:
        """Return standardized summary record for the BAI2 statement."""
        if self._summary is not None:
            return self._summary
        df = self.parse()
        text = Path(self.file_name).read_text(encoding="utf-8")
        s = summarize_bai2(text)
        self._summary = {
            "account_id": (
                str(df["account_id"].iloc[0])
                if not df.empty
                and "account_id" in df.columns
                and df["account_id"].iloc[0] is not None
                else None
            ),
            "statement_date": (
                str(df["booking_date"].iloc[-1])
                if not df.empty
                and "booking_date" in df.columns
                and df["booking_date"].iloc[-1] is not None
                else None
            ),
            "transaction_count": s.transaction_count,
            "total_amount": (
                sum(df["amount"], Decimal("0"))
                if not df.empty and "amount" in df.columns
                else Decimal("0")
            ),
            "opening_balance": None,
            "closing_balance": None,
            "currency": s.currency,
        }
        return self._summary

__init__(file_name)

Initialize parser with path to BAI2 bank statement file.

Source code in bankstatementparser_loader_bai2/loader.py
671
672
673
674
675
def __init__(self, file_name: str | Path) -> None:
    """Initialize parser with path to BAI2 bank statement file."""
    super().__init__(file_name)
    self._parsed_df: pd.DataFrame | None = None
    self._summary: SummaryRecord | None = None

parse()

Parse BAI2 statement transactions into a pandas DataFrame.

Source code in bankstatementparser_loader_bai2/loader.py
677
678
679
680
681
682
683
684
def parse(self) -> pd.DataFrame:
    """Parse BAI2 statement transactions into a pandas DataFrame."""
    if self._parsed_df is not None:
        return self._parsed_df.copy()
    txs = load_bai2_file(self.file_name)
    records = [tx.model_dump() for tx in txs]
    self._parsed_df = pd.DataFrame(records)
    return self._parsed_df.copy()

get_summary()

Return standardized summary record for the BAI2 statement.

Source code in bankstatementparser_loader_bai2/loader.py
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
def get_summary(self) -> SummaryRecord:
    """Return standardized summary record for the BAI2 statement."""
    if self._summary is not None:
        return self._summary
    df = self.parse()
    text = Path(self.file_name).read_text(encoding="utf-8")
    s = summarize_bai2(text)
    self._summary = {
        "account_id": (
            str(df["account_id"].iloc[0])
            if not df.empty
            and "account_id" in df.columns
            and df["account_id"].iloc[0] is not None
            else None
        ),
        "statement_date": (
            str(df["booking_date"].iloc[-1])
            if not df.empty
            and "booking_date" in df.columns
            and df["booking_date"].iloc[-1] is not None
            else None
        ),
        "transaction_count": s.transaction_count,
        "total_amount": (
            sum(df["amount"], Decimal("0"))
            if not df.empty and "amount" in df.columns
            else Decimal("0")
        ),
        "opening_balance": None,
        "closing_balance": None,
        "currency": s.currency,
    }
    return self._summary

load_bai2(text)

Parse a BAI2 payload into a flat list of Transaction objects.

Every 16 Transaction Detail record across all groups and accounts becomes one transaction, carrying its account number and currency. 88 continuation records extend the description of the preceding 03 or 16 record.

Parameters:

Name Type Description Default
text str

The raw BAI2 payload. CRLF / LF endings, blank lines, and an optional trailing / per record are all tolerated.

required

Returns:

Type Description
list[Transaction]

The parsed transactions in file order. May be empty if the file

list[Transaction]

contains headers but no 16 records.

Raises:

Type Description
ValueError

If the file does not start with an 01 File Header record.

Source code in bankstatementparser_loader_bai2/loader.py
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
def load_bai2(text: str) -> list[Transaction]:
    """Parse a BAI2 payload into a flat list of ``Transaction`` objects.

    Every ``16`` Transaction Detail record across all groups and
    accounts becomes one transaction, carrying its account number and
    currency. ``88`` continuation records extend the description of the
    preceding ``03`` or ``16`` record.

    Args:
        text: The raw BAI2 payload. CRLF / LF endings, blank lines, and
            an optional trailing ``/`` per record are all tolerated.

    Returns:
        The parsed transactions in file order. May be empty if the file
        contains headers but no ``16`` records.

    Raises:
        ValueError: If the file does not start with an ``01`` File
            Header record.
    """
    records = list(_iter_records(text))
    if not records or _split_record(records[0])[0] != "01":
        raise ValueError("BAI2 payload must start with an '01' File Header")

    transactions: list[Transaction] = []
    # The single in-progress ``16`` transaction, or ``None``. A live
    # ``pending`` is the *only* thing an ``88`` continuation attaches to:
    # every non-``16`` record (and a skipped status ``16``) flushes it to
    # ``None`` first, so a continuation after one of those is dropped.
    pending: _PendingTransaction | None = None
    group_currency: str | None = None
    group_as_of: date | None = None
    account_number: str | None = None
    account_currency: str | None = None

    def _flush() -> None:
        """Append any in-progress transaction to the output list."""
        nonlocal pending
        if pending is not None:
            transactions.append(pending.to_transaction())
            pending = None

    for record in records:
        code = _record_code(record)
        if code == "02":
            _flush()
            fields = _split_record(record)
            group_as_of = _parse_bai2_date(_field(fields, 4))
            group_currency = _field(fields, 6) or None
            account_number = None
            account_currency = None
        elif code == "03":
            _flush()
            fields = _split_record(record)
            account_number = _field(fields, 1) or None
            account_currency = _field(fields, 2) or None
        elif code == "16":
            _flush()
            type_code, amount, bank_ref, customer_ref, txt = _split_16(record)
            if _is_status_type_code(type_code):
                # 900-999 custom/summary/status codes are not postings:
                # emit nothing. The _flush above already cleared pending,
                # so any continuation that follows is dropped with it.
                continue
            pending = _PendingTransaction(
                type_code=type_code,
                amount=_amount_to_decimal(amount),
                bank_ref=bank_ref,
                customer_ref=customer_ref,
                text_parts=[txt],
                account_number=account_number,
                currency=account_currency or group_currency,
                booking_date=group_as_of,
                index=len(transactions),
            )
        elif code == "88":
            # Continuation text is everything after the leading '88',
            # commas and slashes included, kept verbatim.
            if pending is not None:
                pending.text_parts.append(_continuation_text(record))
            # A continuation of an '03' account note (or one with no
            # preceding detail) has no pending transaction to attach to;
            # it is informational and dropped here.
        elif code in {"49", "98", "99"}:
            # Trailer / control-total records are intentionally ignored.
            _flush()
        # 01 and any unknown code: nothing to accumulate.

    _flush()
    return transactions

load_bai2_file(path)

Parse a BAI2 file from disk into Transaction objects.

Parameters:

Name Type Description Default
path str | Path

Filesystem path to the BAI2 file. UTF-8 is assumed.

required

Returns:

Type Description
list[Transaction]

The parsed transactions, identical to calling :func:load_bai2

list[Transaction]

on the file's text content.

Raises:

Type Description
ValueError

If the file does not start with an 01 record.

OSError

If the file cannot be read.

Source code in bankstatementparser_loader_bai2/loader.py
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
def load_bai2_file(path: str | Path) -> list[Transaction]:
    """Parse a BAI2 file from disk into ``Transaction`` objects.

    Args:
        path: Filesystem path to the BAI2 file. UTF-8 is assumed.

    Returns:
        The parsed transactions, identical to calling :func:`load_bai2`
        on the file's text content.

    Raises:
        ValueError: If the file does not start with an ``01`` record.
        OSError: If the file cannot be read.
    """
    return load_bai2(Path(path).read_text(encoding="utf-8"))

summarize_bai2(text)

Summarise a BAI2 payload without materialising every transaction.

Parameters:

Name Type Description Default
text str

The raw BAI2 payload.

required

Returns:

Name Type Description
A Bai2Summary

class:Bai2Summary with the file id, group / account /

Bai2Summary

transaction counts, and the first currency observed.

Raises:

Type Description
ValueError

If the file does not start with an 01 record.

Source code in bankstatementparser_loader_bai2/loader.py
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
def summarize_bai2(text: str) -> Bai2Summary:
    """Summarise a BAI2 payload without materialising every transaction.

    Args:
        text: The raw BAI2 payload.

    Returns:
        A :class:`Bai2Summary` with the file id, group / account /
        transaction counts, and the first currency observed.

    Raises:
        ValueError: If the file does not start with an ``01`` record.
    """
    records = list(_iter_records(text))
    if not records or _record_code(records[0]) != "01":
        raise ValueError("BAI2 payload must start with an '01' File Header")

    file_id = _field(_split_record(records[0]), 5) or None
    group_count = 0
    account_count = 0
    transaction_count = 0
    currency: str | None = None
    group_currency: str | None = None

    for record in records:
        code = _record_code(record)
        if code == "02":
            group_count += 1
            group_currency = _field(_split_record(record), 6) or None
            if currency is None and group_currency is not None:
                currency = group_currency
        elif code == "03":
            account_count += 1
            account_currency = _field(_split_record(record), 2) or None
            if account_currency is not None:
                currency = account_currency
        elif code == "16":
            # Count only emitted postings; 900-999 custom/summary/status
            # codes are skipped by load_bai2, so they are not counted here
            # either, keeping the summary and the transaction list in step.
            if not _is_status_type_code(_split_16(record)[0]):
                transaction_count += 1

    return Bai2Summary(
        file_id=file_id,
        group_count=group_count,
        account_count=account_count,
        transaction_count=transaction_count,
        currency=currency,
    )