Skip to content

API reference

The importable Python surface: the loading and summary functions, the BacsSummary dataclass, and BacsStatementParser, the BankStatementParser the core discovers through the bacs and std18 entry points in bankstatementparser.loaders. Generated from the docstrings by mkdocstrings.

bankstatementparser_loader_bacs.loader

Core UK BACS Standard 18 & Faster Payments Statement Loader.

BacsSummary dataclass

Summary metrics and headers for a BACS Standard 18 submission.

Source code in bankstatementparser_loader_bacs/loader.py
67
68
69
70
71
72
73
74
75
76
77
78
@dataclass(frozen=True)
class BacsSummary:
    """Summary metrics and headers for a BACS Standard 18 submission."""

    service_user_number: str | None
    originating_sort_code: str | None
    originating_account: str | None
    currency: str
    submission_date: date | None
    transaction_count: int
    total_credit: Decimal
    total_debit: Decimal

BacsStatementParser

Bases: BankStatementParser

BankStatementParser plugin implementation for UK BACS Standard 18 files.

Source code in bankstatementparser_loader_bacs/loader.py
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
class BacsStatementParser(BankStatementParser):
    """BankStatementParser plugin implementation for UK BACS Standard 18 files."""

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

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

    def parse(self) -> pd.DataFrame:
        """Parse the BACS 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 BACS file into a list of Transaction models.

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

    def get_summary(self) -> BacsSummaryRecord:
        """Get summary metadata and balance metrics for the BACS file.

        Returns:
            Dictionary with statement statistics.
        """
        if self._summary_cache is None:
            content = Path(self.file_name).read_text(
                encoding="utf-8", errors="replace"
            )
            self._summary_cache = summarize_bacs(content)

        s = self._summary_cache
        return {
            "service_user_number": s.service_user_number,
            "originating_sort_code": s.originating_sort_code,
            "originating_account": s.originating_account,
            "currency": s.currency,
            "submission_date": (
                s.submission_date.isoformat() if s.submission_date else None
            ),
            "transaction_count": s.transaction_count,
            "total_credit": float(s.total_credit),
            "total_debit": float(s.total_debit),
        }

__init__(file_name, **kwargs)

Initialize the BACS statement parser.

Parameters:

Name Type Description Default
file_name str | Path

Path to the BACS statement file.

required
**kwargs Any

Extra options passed to base parser.

{}
Source code in bankstatementparser_loader_bacs/loader.py
305
306
307
308
309
310
311
312
313
def __init__(self, file_name: str | Path, **kwargs: Any) -> None:
    """Initialize the BACS statement parser.

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

parse()

Parse the BACS file into a pandas DataFrame.

Returns:

Type Description
DataFrame

A pandas DataFrame containing standardized statement transactions.

Source code in bankstatementparser_loader_bacs/loader.py
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
def parse(self) -> pd.DataFrame:
    """Parse the BACS 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 BACS file into a list of Transaction models.

Returns:

Type Description
list[Transaction]

List of parsed Transaction instances.

Source code in bankstatementparser_loader_bacs/loader.py
349
350
351
352
353
354
355
def to_transactions(self) -> list[Transaction]:
    """Parse the BACS file into a list of Transaction models.

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

get_summary()

Get summary metadata and balance metrics for the BACS file.

Returns:

Type Description
BacsSummaryRecord

Dictionary with statement statistics.

Source code in bankstatementparser_loader_bacs/loader.py
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
def get_summary(self) -> BacsSummaryRecord:
    """Get summary metadata and balance metrics for the BACS file.

    Returns:
        Dictionary with statement statistics.
    """
    if self._summary_cache is None:
        content = Path(self.file_name).read_text(
            encoding="utf-8", errors="replace"
        )
        self._summary_cache = summarize_bacs(content)

    s = self._summary_cache
    return {
        "service_user_number": s.service_user_number,
        "originating_sort_code": s.originating_sort_code,
        "originating_account": s.originating_account,
        "currency": s.currency,
        "submission_date": (
            s.submission_date.isoformat() if s.submission_date else None
        ),
        "transaction_count": s.transaction_count,
        "total_credit": float(s.total_credit),
        "total_debit": float(s.total_debit),
    }

load_bacs(text_or_lines)

Parse BACS Standard 18 text into domain Transaction models.

Parameters:

Name Type Description Default
text_or_lines str | Iterable[str]

Raw BACS payload or line iterable.

required

Returns:

Type Description
list[Transaction]

List of Transaction instances.

Source code in bankstatementparser_loader_bacs/loader.py
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
def load_bacs(text_or_lines: str | Iterable[str]) -> list[Transaction]:
    """Parse BACS Standard 18 text into domain Transaction models.

    Args:
        text_or_lines: Raw BACS payload or line iterable.

    Returns:
        List of Transaction instances.
    """
    lines = (
        text_or_lines.splitlines()
        if isinstance(text_or_lines, str)
        else text_or_lines
    )
    state = _parse_bacs_stream(lines)
    transactions: list[Transaction] = []

    for idx, rec in enumerate(state.records):
        tx = Transaction(
            account_id=rec.get("account_id"),
            currency=rec.get("currency", "GBP"),
            amount=rec["amount"],
            booking_date=rec.get("booking_date"),
            value_date=rec.get("value_date"),
            description=rec.get("description"),
            reference=rec.get("reference"),
            category=f"bacs:{rec['tx_code']}" if rec.get("tx_code") else None,
            source=SOURCE,
            source_index=idx,
        )
        transactions.append(tx)

    return transactions

load_bacs_file(path)

Read and parse a BACS statement file from disk.

Parameters:

Name Type Description Default
path str | PathLike[str]

Path to the BACS file.

required

Returns:

Type Description
list[Transaction]

List of Transaction instances.

Source code in bankstatementparser_loader_bacs/loader.py
251
252
253
254
255
256
257
258
259
260
261
def load_bacs_file(path: str | os.PathLike[str]) -> list[Transaction]:
    """Read and parse a BACS statement file from disk.

    Args:
        path: Path to the BACS file.

    Returns:
        List of Transaction instances.
    """
    content = Path(path).read_text(encoding="utf-8", errors="replace")
    return load_bacs(content)

summarize_bacs(text_or_lines)

Generate financial metrics and headers summary for a BACS statement.

Parameters:

Name Type Description Default
text_or_lines str | Iterable[str]

Raw BACS payload or line iterable.

required

Returns:

Type Description
BacsSummary

A BacsSummary instance.

Source code in bankstatementparser_loader_bacs/loader.py
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
def summarize_bacs(text_or_lines: str | Iterable[str]) -> BacsSummary:
    """Generate financial metrics and headers summary for a BACS statement.

    Args:
        text_or_lines: Raw BACS payload or line iterable.

    Returns:
        A BacsSummary instance.
    """
    lines = (
        text_or_lines.splitlines()
        if isinstance(text_or_lines, str)
        else text_or_lines
    )
    state = _parse_bacs_stream(lines)

    total_credit = Decimal("0.00")
    total_debit = Decimal("0.00")

    for rec in state.records:
        amt = rec["amount"]
        if amt > 0:
            total_credit += amt
        else:
            total_debit += abs(amt)

    return BacsSummary(
        service_user_number=state.sun or None,
        originating_sort_code=state.orig_sort or None,
        originating_account=state.orig_acct or None,
        currency=state.currency,
        submission_date=state.sub_date,
        transaction_count=len(state.records),
        total_credit=total_credit,
        total_debit=total_debit,
    )