Skip to content

API reference

The importable Python surface: the loading and summary functions, the CfonbSummary dataclass, and CfonbStatementParser, the BankStatementParser the core discovers through the cfonb and afb120 entry points in bankstatementparser.loaders. Generated from the docstrings by mkdocstrings.

bankstatementparser_loader_cfonb.loader

Core CFONB 120 / AFB120 Fixed-Width Banking Statement Loader.

CfonbSummary dataclass

Financial and header summary for a parsed CFONB 120 statement.

Source code in bankstatementparser_loader_cfonb/loader.py
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
@dataclass(frozen=True)
class CfonbSummary:
    """Financial and header summary for a parsed CFONB 120 statement."""

    account_id: str
    bank_code: str
    branch_code: str
    currency: str
    opening_balance: Decimal | None
    closing_balance: Decimal | None
    opening_date: date | None
    closing_date: date | None
    transaction_count: int
    total_credit: Decimal
    total_debit: Decimal

CfonbStatementParser

Bases: BankStatementParser

BankStatementParser plugin implementation for French CFONB 120 statements.

Source code in bankstatementparser_loader_cfonb/loader.py
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
class CfonbStatementParser(BankStatementParser):
    """BankStatementParser plugin implementation for French CFONB 120 statements."""

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

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

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

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

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

        Returns:
            Statement statistics. ``opening_balance`` and ``closing_balance``
            are ``Decimal`` (or ``None`` when the file has no balance record),
            as ``SummaryRecord`` declares.
        """
        if self._summary_cache is None:
            content = Path(self.file_name).read_text(
                encoding="utf-8", errors="replace"
            )
            self._summary_cache = summarize_cfonb(content)

        s = self._summary_cache
        return {
            "account_id": s.account_id,
            "bank_code": s.bank_code,
            "branch_code": s.branch_code,
            "currency": s.currency,
            "opening_balance": s.opening_balance,
            "closing_balance": s.closing_balance,
            "opening_date": (
                s.opening_date.isoformat() if s.opening_date else None
            ),
            "closing_date": (
                s.closing_date.isoformat() if s.closing_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 CFONB statement parser.

Parameters:

Name Type Description Default
file_name str | Path

Path to the CFONB 120 statement file.

required
**kwargs Any

Extra options passed to the base parser.

{}
Source code in bankstatementparser_loader_cfonb/loader.py
336
337
338
339
340
341
342
343
344
def __init__(self, file_name: str | Path, **kwargs: Any) -> None:
    """Initialize the CFONB statement parser.

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

parse()

Parse the CFONB file into a pandas DataFrame.

Returns:

Type Description
DataFrame

A pandas DataFrame containing standardized statement transactions.

Source code in bankstatementparser_loader_cfonb/loader.py
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
def parse(self) -> pd.DataFrame:
    """Parse the CFONB 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,
            "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 CFONB file into a list of Transaction models.

Returns:

Type Description
list[Transaction]

List of parsed Transaction instances.

Source code in bankstatementparser_loader_cfonb/loader.py
380
381
382
383
384
385
386
def to_transactions(self) -> list[Transaction]:
    """Parse the CFONB file into a list of Transaction models.

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

get_summary()

Get summary metadata and balance metrics for the CFONB file.

Returns:

Type Description
CfonbSummaryRecord

Statement statistics. opening_balance and closing_balance

CfonbSummaryRecord

are Decimal (or None when the file has no balance record),

CfonbSummaryRecord

as SummaryRecord declares.

Source code in bankstatementparser_loader_cfonb/loader.py
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
def get_summary(self) -> CfonbSummaryRecord:
    """Get summary metadata and balance metrics for the CFONB file.

    Returns:
        Statement statistics. ``opening_balance`` and ``closing_balance``
        are ``Decimal`` (or ``None`` when the file has no balance record),
        as ``SummaryRecord`` declares.
    """
    if self._summary_cache is None:
        content = Path(self.file_name).read_text(
            encoding="utf-8", errors="replace"
        )
        self._summary_cache = summarize_cfonb(content)

    s = self._summary_cache
    return {
        "account_id": s.account_id,
        "bank_code": s.bank_code,
        "branch_code": s.branch_code,
        "currency": s.currency,
        "opening_balance": s.opening_balance,
        "closing_balance": s.closing_balance,
        "opening_date": (
            s.opening_date.isoformat() if s.opening_date else None
        ),
        "closing_date": (
            s.closing_date.isoformat() if s.closing_date else None
        ),
        "transaction_count": s.transaction_count,
        "total_credit": float(s.total_credit),
        "total_debit": float(s.total_debit),
    }

load_cfonb(text_or_lines)

Parse CFONB 120 formatted text into a list of Transaction models.

Parameters:

Name Type Description Default
text_or_lines str | Iterable[str]

Raw CFONB string or iterable of lines.

required

Returns:

Type Description
list[Transaction]

List of parsed Transaction domain models.

Source code in bankstatementparser_loader_cfonb/loader.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
def load_cfonb(text_or_lines: str | Iterable[str]) -> list[Transaction]:
    """Parse CFONB 120 formatted text into a list of Transaction models.

    Args:
        text_or_lines: Raw CFONB string or iterable of lines.

    Returns:
        List of parsed Transaction domain models.
    """
    lines = (
        text_or_lines.splitlines()
        if isinstance(text_or_lines, str)
        else text_or_lines
    )
    state = _parse_cfonb_stream(lines)
    transactions: list[Transaction] = []

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

    return transactions

load_cfonb_file(path)

Read and parse a CFONB 120 statement file from disk.

Parameters:

Name Type Description Default
path str | PathLike[str]

Path to the CFONB file.

required

Returns:

Type Description
list[Transaction]

List of parsed Transaction domain models.

Source code in bankstatementparser_loader_cfonb/loader.py
279
280
281
282
283
284
285
286
287
288
289
def load_cfonb_file(path: str | os.PathLike[str]) -> list[Transaction]:
    """Read and parse a CFONB 120 statement file from disk.

    Args:
        path: Path to the CFONB file.

    Returns:
        List of parsed Transaction domain models.
    """
    content = Path(path).read_text(encoding="utf-8", errors="replace")
    return load_cfonb(content)

summarize_cfonb(text_or_lines)

Generate a structured financial summary for a CFONB statement.

Parameters:

Name Type Description Default
text_or_lines str | Iterable[str]

Raw CFONB string or iterable of lines.

required

Returns:

Type Description
CfonbSummary

A CfonbSummary dataclass containing balances, dates, and aggregates.

Source code in bankstatementparser_loader_cfonb/loader.py
292
293
294
295
296
297
298
299
300
301
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
def summarize_cfonb(text_or_lines: str | Iterable[str]) -> CfonbSummary:
    """Generate a structured financial summary for a CFONB statement.

    Args:
        text_or_lines: Raw CFONB string or iterable of lines.

    Returns:
        A CfonbSummary dataclass containing balances, dates, and aggregates.
    """
    lines = (
        text_or_lines.splitlines()
        if isinstance(text_or_lines, str)
        else text_or_lines
    )
    state = _parse_cfonb_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 CfonbSummary(
        account_id=state.account_id,
        bank_code=state.bank_code,
        branch_code=state.branch_code,
        currency=state.currency,
        opening_balance=state.opening_balance,
        closing_balance=state.closing_balance,
        opening_date=state.opening_date,
        closing_date=state.closing_date,
        transaction_count=len(state.records),
        total_credit=total_credit,
        total_debit=total_debit,
    )