Skip to content

API reference

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

bankstatementparser_loader_mt942.loader

SWIFT MT942 Interim Transaction Report loader.

The core :mod:bankstatementparser library parses PDF and CSV bank statements but does not understand the SWIFT MT942 Interim Transaction Report wire format. This module fills that gap: it parses the MT942 tag grammar and hands back the same :class:bankstatementparser.transaction_models.Transaction objects the core library produces, so MT942 feeds drop straight into any downstream consumer (deduplication, categorisation, exports).

MT942 is an interim statement: unlike MT940 it carries no :60F: opening or :62F: closing balance. Instead it reports a floor limit (:34F:), an optional date/time stamp (:13D:), the booked statement lines (:61: / :86:) accumulated so far, and debit/credit summaries (:90D: / :90C:). This loader models that structure faithfully and never invents balances that are not present in the source.

Supported tags:

  • :20: Transaction reference number (mandatory).
  • :25: Account identification (mandatory) — the account id.
  • :28C: Statement / sequence number.
  • :34F: Floor limit indicator <CCY>[D|C]<amount> — the currency for every transaction is taken from here.
  • :13D: Date/time stamp YYMMDDHHMM±HHMM (optional).
  • :61: Statement line (one per booked entry, repeatable).
  • :86: Information to account owner — attaches its free-form description to the immediately preceding :61: line.
  • :90D: Debit summary <count><CCY><amount>.
  • :90C: Credit summary <count><CCY><amount>.

Amounts use the SWIFT comma decimal separator (500,00); they are converted to :class:decimal.Decimal (Decimal("500.00")) throughout. The fractional part is optional: a SWIFT amount may end on the decimal comma with no digits after it (5000, → Decimal("5000"), 0, → Decimal("0")). D, RC and ED lines yield a negative amount; C, RD and EC a positive one. Unknown tags and the trailing - end-of-message marker are tolerated and ignored.

Real-world MT942 messages are frequently wrapped in a SWIFT message envelope — the basic/application/user header blocks {1:...}, {2:...}, {3:...} and the text-block opener {4: with a matching -} terminator. This loader strips that envelope before tokenising so the :tag: body parses cleanly; envelope lines are never mistaken for content.

Two :61: constructs that appear in genuine bank exports are handled:

  • Supplementary details after :61: — a SWIFT statement line may carry an optional supplementary-details subfield on the line(s) immediately following the :61: line (before any :86:), e.g. a bare Transfer or wording/NBKT. This loader captures those line(s) and folds them into the transaction's description (they are never silently dropped): the description is the supplementary text and the following :86: content joined by newlines, in that order.
  • Multi-line :86: — the :86: information field continues on following lines that do not start with a :tag: head (e.g. /BAI/..., /BENM/..., /ACNO/...). Those continuation lines are appended to the :86: description verbatim, newlines preserved.

Mt942Summary dataclass

Header-level summary of a parsed MT942 message.

Captures the metadata and the debit/credit roll-ups that an MT942 carries in its own right, independent of the individual transactions. Every field maps directly to a source tag; nothing is derived or invented.

Attributes:

Name Type Description
reference str

The :20: transaction reference number.

account_id str

The :25: account identification.

currency str | None

The currency from the :34F: floor limit, or None if no floor limit was present.

statement_datetime datetime | None

The :13D: date/time stamp as a timezone-aware :class:datetime.datetime, or None when the optional tag is absent.

debit_count int | None

The number of debit entries from :90D:, or None when the tag is absent.

debit_sum Decimal | None

The summed debit amount from :90D: as a :class:decimal.Decimal, or None when absent.

credit_count int | None

The number of credit entries from :90C:, or None when the tag is absent.

credit_sum Decimal | None

The summed credit amount from :90C: as a :class:decimal.Decimal, or None when absent.

transaction_count int

The number of :61: statement lines actually parsed from the message.

Source code in bankstatementparser_loader_mt942/loader.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
@dataclass(frozen=True)
class Mt942Summary:
    """Header-level summary of a parsed MT942 message.

    Captures the metadata and the debit/credit roll-ups that an MT942
    carries in its own right, independent of the individual
    transactions. Every field maps directly to a source tag; nothing is
    derived or invented.

    Attributes:
        reference: The ``:20:`` transaction reference number.
        account_id: The ``:25:`` account identification.
        currency: The currency from the ``:34F:`` floor limit, or
            ``None`` if no floor limit was present.
        statement_datetime: The ``:13D:`` date/time stamp as a
            timezone-aware :class:`datetime.datetime`, or ``None`` when
            the optional tag is absent.
        debit_count: The number of debit entries from ``:90D:``, or
            ``None`` when the tag is absent.
        debit_sum: The summed debit amount from ``:90D:`` as a
            :class:`decimal.Decimal`, or ``None`` when absent.
        credit_count: The number of credit entries from ``:90C:``, or
            ``None`` when the tag is absent.
        credit_sum: The summed credit amount from ``:90C:`` as a
            :class:`decimal.Decimal`, or ``None`` when absent.
        transaction_count: The number of ``:61:`` statement lines
            actually parsed from the message.
    """

    reference: str
    account_id: str
    currency: str | None
    statement_datetime: datetime | None
    debit_count: int | None
    debit_sum: Decimal | None
    credit_count: int | None
    credit_sum: Decimal | None
    transaction_count: int

Mt942StatementParser

Bases: BankStatementParser

BankStatementParser-compatible wrapper for SWIFT MT942 statement files.

Source code in bankstatementparser_loader_mt942/loader.py
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
class Mt942StatementParser(BankStatementParser):
    """BankStatementParser-compatible wrapper for SWIFT MT942 statement files."""

    def __init__(self, file_name: str | Path) -> None:
        """Initialize parser with path to SWIFT MT942 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 SWIFT MT942 statement transactions into a pandas DataFrame."""
        if self._parsed_df is not None:
            return self._parsed_df.copy()
        txs = load_mt942_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 SWIFT MT942 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_mt942(text)
        self._summary = {
            "account_id": s.account_id,
            "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": (s.credit_sum or Decimal("0"))
            - (s.debit_sum or Decimal("0")),
            "opening_balance": None,
            "closing_balance": None,
            "currency": s.currency,
        }
        return self._summary

__init__(file_name)

Initialize parser with path to SWIFT MT942 bank statement file.

Source code in bankstatementparser_loader_mt942/loader.py
646
647
648
649
650
def __init__(self, file_name: str | Path) -> None:
    """Initialize parser with path to SWIFT MT942 bank statement file."""
    super().__init__(file_name)
    self._parsed_df: pd.DataFrame | None = None
    self._summary: SummaryRecord | None = None

parse()

Parse SWIFT MT942 statement transactions into a pandas DataFrame.

Source code in bankstatementparser_loader_mt942/loader.py
652
653
654
655
656
657
658
659
def parse(self) -> pd.DataFrame:
    """Parse SWIFT MT942 statement transactions into a pandas DataFrame."""
    if self._parsed_df is not None:
        return self._parsed_df.copy()
    txs = load_mt942_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 SWIFT MT942 statement.

Source code in bankstatementparser_loader_mt942/loader.py
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
def get_summary(self) -> SummaryRecord:
    """Return standardized summary record for the SWIFT MT942 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_mt942(text)
    self._summary = {
        "account_id": s.account_id,
        "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": (s.credit_sum or Decimal("0"))
        - (s.debit_sum or Decimal("0")),
        "opening_balance": None,
        "closing_balance": None,
        "currency": s.currency,
    }
    return self._summary

load_mt942(text)

Parse an MT942 payload into a list of transactions.

Each :61: statement line becomes one :class:~bankstatementparser.transaction_models.Transaction with source="mt942". Debit lines carry a negative amount, credit lines a positive amount. The account id (:25:) and currency (:34F:) are applied to every transaction; the :86: description is attached to its preceding :61: line.

Parameters:

Name Type Description Default
text str

The MT942 payload as a string. CRLF/LF differences, blank lines, and the trailing - end-of-message marker are tolerated; unknown tags are ignored.

required

Returns:

Type Description
list[Transaction]

A list of parsed transactions in document order. Malformed

list[Transaction]

:61: lines are skipped, so the list length may be shorter

list[Transaction]

than the number of :61: tags present.

Raises:

Type Description
ValueError

If the payload is missing the mandatory :20: or :25: field.

Source code in bankstatementparser_loader_mt942/loader.py
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
def load_mt942(text: str) -> list[Transaction]:
    """Parse an MT942 payload into a list of transactions.

    Each ``:61:`` statement line becomes one
    :class:`~bankstatementparser.transaction_models.Transaction` with
    ``source="mt942"``. Debit lines carry a negative amount, credit
    lines a positive amount. The account id (``:25:``) and currency
    (``:34F:``) are applied to every transaction; the ``:86:``
    description is attached to its preceding ``:61:`` line.

    Args:
        text: The MT942 payload as a string. CRLF/LF differences, blank
            lines, and the trailing ``-`` end-of-message marker are
            tolerated; unknown tags are ignored.

    Returns:
        A list of parsed transactions in document order. Malformed
        ``:61:`` lines are skipped, so the list length may be shorter
        than the number of ``:61:`` tags present.

    Raises:
        ValueError: If the payload is missing the mandatory ``:20:`` or
            ``:25:`` field.
    """
    state, _, account_id = _accumulate(text)
    transactions: list[Transaction] = []
    for index, record in enumerate(state.records):
        enriched: dict[str, object] = dict(record)
        enriched["account_id"] = account_id
        enriched["currency"] = state.currency
        transactions.append(
            Transaction.from_record(
                enriched, source=SOURCE, source_index=index
            )
        )
    return transactions

load_mt942_file(path)

Read an MT942 file from disk and parse it.

Parameters:

Name Type Description Default
path str | PathLike[str]

Filesystem path to a UTF-8 encoded MT942 file.

required

Returns:

Type Description
list[Transaction]

A list of parsed transactions, identical to calling

list[Transaction]

func:load_mt942 on the file's contents.

Raises:

Type Description
ValueError

If the payload is missing the mandatory :20: or :25: field.

OSError

If the file cannot be read.

Source code in bankstatementparser_loader_mt942/loader.py
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
def load_mt942_file(path: str | os.PathLike[str]) -> list[Transaction]:
    """Read an MT942 file from disk and parse it.

    Args:
        path: Filesystem path to a UTF-8 encoded MT942 file.

    Returns:
        A list of parsed transactions, identical to calling
        :func:`load_mt942` on the file's contents.

    Raises:
        ValueError: If the payload is missing the mandatory ``:20:`` or
            ``:25:`` field.
        OSError: If the file cannot be read.
    """
    with open(path, encoding="utf-8") as handle:
        return load_mt942(handle.read())

summarize_mt942(text)

Parse an MT942 payload into a header-level summary.

Unlike :func:load_mt942, this returns the message metadata and the :90D: / :90C: roll-ups rather than the individual transactions, while still counting the :61: lines that parsed.

Parameters:

Name Type Description Default
text str

The MT942 payload as a string.

required

Returns:

Name Type Description
An Mt942Summary

class:Mt942Summary describing the message.

Raises:

Type Description
ValueError

If the payload is missing the mandatory :20: or :25: field.

Source code in bankstatementparser_loader_mt942/loader.py
612
613
614
615
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
def summarize_mt942(text: str) -> Mt942Summary:
    """Parse an MT942 payload into a header-level summary.

    Unlike :func:`load_mt942`, this returns the message metadata and the
    ``:90D:`` / ``:90C:`` roll-ups rather than the individual
    transactions, while still counting the ``:61:`` lines that parsed.

    Args:
        text: The MT942 payload as a string.

    Returns:
        An :class:`Mt942Summary` describing the message.

    Raises:
        ValueError: If the payload is missing the mandatory ``:20:`` or
            ``:25:`` field.
    """
    state, reference, account_id = _accumulate(text)
    return Mt942Summary(
        reference=reference,
        account_id=account_id,
        currency=state.currency,
        statement_datetime=state.statement_datetime,
        debit_count=state.debit_count,
        debit_sum=state.debit_sum,
        credit_count=state.credit_count,
        credit_sum=state.credit_sum,
        transaction_count=len(state.records),
    )