### Run Example Scripts
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/examples/README.md
Navigate to the examples directory and execute Python scripts to run demonstrations.
```bash
cd examples
python parse_camt_basic.py
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/README.md
Clone the repository, set up a virtual environment, and install project dependencies using Poetry. This includes development dependencies.
```bash
git clone https://github.com/sebastienrousseau/bankstatementparser.git
cd bankstatementparser
python3 -m venv .venv
source .venv/bin/activate
pip install poetry
poetry install --with dev
make install-hooks # pre-commit hook runs `make verify` before every commit
```
--------------------------------
### Clone and Install Project Dependencies
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/CONTRIBUTING.md
Clone the repository and set up the Python virtual environment. Install project dependencies using Poetry, including development extras.
```bash
git clone https://github.com/sebastienrousseau/bankstatementparser.git
cd bankstatementparser
python3 -m venv .venv
source .venv/bin/activate
pip install poetry
poetry install --with dev
make install-hooks # wires the pre-commit hook (runs `make verify` on every commit)
```
--------------------------------
### Generate Sample PDFs for LLM Examples
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/examples/README.md
Produce reproducible synthetic UK-bank PDFs, both digital and scanned, for use in LLM-based examples.
```python
hybrid/generate_sample_pdfs.py
```
--------------------------------
### Install bankstatementparser API
Source: https://context7.com/sebastienrousseau/bankstatementparser/llms.txt
Installs the bankstatementparser library with the optional API extra, enabling the FastAPI microservice.
```bash
# Install
pip install 'bankstatementparser[api]'
```
--------------------------------
### Run Vision Ingestion Example (Mock Mode)
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/examples/hybrid/README.md
Run the vision ingestion example in mock mode. Set environment variables to use live vision models.
```python
python examples/hybrid/03_smart_ingest_vision.py # mock mode
```
--------------------------------
### Install Hybrid Pipeline Dependencies
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/examples/hybrid/README.md
Install the necessary packages for the hybrid pipeline, including support for vision capabilities.
```bash
pip install 'bankstatementparser[hybrid-vision]'
pip install reportlab pillow
```
--------------------------------
### Run Text LLM Ingestion Example (Mock Mode)
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/examples/hybrid/README.md
Run the text LLM ingestion example in mock mode. Set environment variables to use live LLM.
```python
python examples/hybrid/02_smart_ingest_text_llm.py # mock mode
```
--------------------------------
### Install Bank Statement Parser Core
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/README.md
Installs the core library with deterministic parsers for CAMT, PAIN.001, CSV, OFX, QFX, and MT940 formats. This installation has zero AI dependencies.
```bash
pip install bankstatementparser
```
--------------------------------
### Use Legacy API Wrappers
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/README.md
Provides examples of using compatibility wrappers for legacy API access.
```python
from bankstatementparser.compatibility_wrappers import legacy_parser
# Use legacy API wrappers for compatibility
for item in legacy_parser("old_format.txt"):
print(item)
```
--------------------------------
### Install Optional Hybrid Pipeline Extras
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/CONTRIBUTING.md
Install optional Poetry extras for hybrid pipeline development. Choose 'hybrid' for text-LLM path, 'hybrid-plus' for higher-fidelity table extraction, or 'hybrid-vision' for vision-LLM path.
```bash
# Text-LLM path (digital PDFs) — adds litellm + pypdf
poetry install --with dev -E hybrid
# Higher-fidelity table extraction — adds pdfplumber on top of [hybrid]
poetry install --with dev -E hybrid-plus
# Vision-LLM path (scanned/photocopied PDFs) — adds pypdfium2
poetry install --with dev -E hybrid-vision
```
--------------------------------
### Install Bank Statement Parser with Multimodal Vision Support
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/README.md
Installs the core library with support for the multimodal vision path, enabling processing of scanned or photocopied PDFs. Adds pypdfium2 as a dependency.
```bash
pip install 'bankstatementparser[hybrid-vision]'
```
--------------------------------
### Install Bank Statement Parser with Enrichment Features
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/README.md
Installs the core library with LLM-powered transaction categorization features. This enables advanced enrichment of transaction data.
```bash
pip install 'bankstatementparser[enrichment]'
```
--------------------------------
### Install Bank Statement Parser with REST API
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/README.md
Installs the core library along with the dependencies for the REST API microservice, including FastAPI and uvicorn. This allows for a web-based interface to the parser.
```bash
pip install 'bankstatementparser[api]'
```
--------------------------------
### CLI Commands for Parsing and Export
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/examples/README.md
Examples of using command-line interface commands for parsing CAMT and PAIN.001 files, and for exporting data.
```bash
cli_examples.sh
```
--------------------------------
### Start bankstatementparser API Server
Source: https://context7.com/sebastienrousseau/bankstatementparser/llms.txt
Starts the FastAPI microservice for bank statement ingestion. Can be configured to run on localhost only or on all interfaces.
```bash
# Start server (localhost only by default)
bankstatementparser-api --port 8000
# For container deployments
bankstatementparser-api --host 0.0.0.0 --port 8000
```
--------------------------------
### Run Golden Rule Verification Example
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/examples/hybrid/README.md
Execute the script demonstrating the Golden Rule verification process for ingested bank statements.
```python
python examples/hybrid/04_golden_rule.py
```
--------------------------------
### Install Bank Statement Parser with Enhanced Text-LLM Support
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/README.md
Installs the core library with enhanced text-LLM capabilities, including higher-fidelity table extraction. Adds pdfplumber as a dependency.
```bash
pip install 'bankstatementparser[hybrid-plus]'
```
--------------------------------
### Install Hybrid Parsing Support
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/FAQ.md
Install the bankstatementparser library with hybrid parsing capabilities for PDF support. This enables advanced features for processing PDF bank statements.
```bash
pip install 'bankstatementparser[hybrid]'
```
--------------------------------
### Start Bank Statement Parser API Server
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/README.md
Start the bank statement parser REST API server on a specified port. The default host is localhost.
```bash
bankstatementparser-api --port 8000
```
--------------------------------
### Run Deterministic Ingestion Example
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/examples/hybrid/README.md
Execute the script for deterministic ingestion, which handles structured formats like CAMT, PAIN, OFX, MT940, and CSV.
```python
python examples/hybrid/01_smart_ingest_deterministic.py
```
--------------------------------
### Run Deduplicate Recurring Transactions Example
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/examples/hybrid/README.md
Run the script for deduplicating recurring transactions within bank statement data.
```python
python examples/hybrid/05_dedupe_recurring.py
```
--------------------------------
### API Error Response Example
Source: https://context7.com/sebastienrousseau/bankstatementparser/llms.txt
Illustrates an error response from the API when an unrecognized file format is provided for ingestion. Returns an HTTP 422 status code with an error message.
```bash
# Error response (unrecognized file format)
curl -F file=@bad.txt http://localhost:8000/ingest
# HTTP 422: {"error": "Unable to detect statement format: bad.txt"}
```
--------------------------------
### CamtParser - Parse CAMT.053 XML statements
Source: https://context7.com/sebastienrousseau/bankstatementparser/llms.txt
Demonstrates how to parse CAMT.053 bank statement files from disk, in-memory XML strings, or raw bytes using the CamtParser class. It also shows how to retrieve account balances, statement statistics, summary information, and perform PII redaction. Examples include parsing from files, bytes, and strings, as well as exporting to Excel, CSV, and JSON.
```APIDOC
## CamtParser — Parse CAMT.053 XML statements
`CamtParser` parses ISO 20022 CAMT.053 bank statement files from disk, an in-memory XML string, or raw bytes. It exposes transaction data, account balances, statement statistics, and export methods.
```python
from bankstatementparser import CamtParser
from bankstatementparser.exceptions import ParserError
# --- From file ---
parser = CamtParser("statement.xml")
transactions_df = parser.parse()
# Returns a DataFrame with columns:
# Amount, Currency, DrCr, Debtor, Creditor, Reference, ValDt, BookgDt, AccountId
print(transactions_df)
# Amount Currency DrCr Debtor Creditor ValDt AccountId
# 105678.5 SEK CRDT MUELLER 2010-10-18 50000000054910
# -200000.0 SEK DBIT 2010-10-18 50000000054910
# --- Balances ---
balances = parser.get_account_balances()
# Columns: Amount, Currency, Code, Description, DrCr, Date
# --- Statement statistics ---
stats = parser.get_statement_stats()
# Columns: StatementId, AccountId, StatementCreated, NumTransactions, NetAmount
# --- Summary dict ---
summary = parser.get_summary()
# {'account_id': '50000000054910', 'statement_date': '2010-10-20T12:00:00',
# 'transaction_count': 3, 'total_amount': -64321.5, 'currency': 'SEK',
# 'opening_balance': 500000.0, 'closing_balance': 435678.5}
# --- PII redaction (address fields masked) ---
transactions_redacted = parser.parse(redact_pii=True)
# --- From in-memory bytes (no disk I/O) ---
xml_bytes = download_from_sftp() # your own function
parser = CamtParser.from_bytes(xml_bytes, source_name="daily.xml")
transactions_df = parser.parse()
# --- From in-memory string ---
xml_str = "..."
parser = CamtParser.from_string(xml_str, source_name="inline.xml")
# --- Export to Excel (Balances, Transactions, Stats sheets) ---
parser.camt_to_excel("output.xlsx")
# --- Export to CSV/JSON via base class ---
parser.export_csv("output.csv")
parser.export_json("output.json")
```
```
--------------------------------
### Load CAMT.053 File and Print Transactions
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/README.md
Demonstrates loading a CAMT.053 file and iterating through its transactions.
```python
from bankstatementparser import parse_camt_basic
# Load a CAMT.053 file and print transactions
for transaction in parse_camt_basic("camt053.xml"):
print(transaction)
```
--------------------------------
### CLI Walkthrough for Bash (macOS/Linux/WSL)
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/examples/hybrid/README.md
Demonstrates four variations of the '--type ingest' CLI subcommand using bash. This script is intended for macOS, Linux, and WSL environments. Ensure the necessary BSP_HYBRID_* environment variables are set.
```bash
06_cli_walkthrough.sh
```
--------------------------------
### Generate Sample PDFs
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/examples/hybrid/README.md
Generate synthetic PDF files for testing the hybrid pipeline. This is a one-off step.
```python
python examples/hybrid/generate_sample_pdfs.py
```
--------------------------------
### Configure Local Ollama for LLM and Vision
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/examples/hybrid/README.md
Set up environment variables to use a locally running Ollama instance for text and vision LLM paths.
```bash
# Local + private (recommended for finance data)
ollama serve &
ollama pull llama3 # text path
ollama pull minicpm-v # vision path (v0.0.7+ recommended default)
export BSP_HYBRID_MODEL=ollama/llama3
export BSP_HYBRID_VISION_MODEL=ollama/minicpm-v
```
--------------------------------
### Export CAMT Data to Excel
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/examples/README.md
Export parsed CAMT data into an Excel workbook (.xlsx) using this example.
```python
export_camt_excel.py
```
--------------------------------
### Verify Reproducibility Locally
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/FAQ.md
Run these commands to verify the project's reproducibility locally. Ensure all tests pass and dependencies are correctly verified.
```bash
poetry run pytest # 718 tests, 100% branch coverage
```
```bash
poetry run python scripts/verify_locked_hashes.py # SHA-256 hash verification
```
```bash
git log --show-signature -1 # Verify commit signature
```
--------------------------------
### Set Up Ollama for Text LLM
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/FAQ.md
Configure Ollama to serve models and set the environment variable for the hybrid text model. Recommended for clean JSON extractions.
```bash
ollama serve &
ollama pull llama3
export BSP_HYBRID_MODEL=ollama/llama3
```
--------------------------------
### Use Legacy API Wrappers
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/examples/README.md
Demonstrates the use of legacy API wrappers for CAMT.053 and PAIN.001 parsing.
```python
compatibility_wrappers.py
```
--------------------------------
### CLI Walkthrough for PowerShell (Native Windows)
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/examples/hybrid/README.md
Demonstrates the '--type ingest' CLI subcommand using PowerShell. This script is intended for native Windows environments (PowerShell 7+). Ensure the necessary BSP_HYBRID_* environment variables are set.
```powershell
06_cli_walkthrough.ps1
```
--------------------------------
### Check if Model is Ollama
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/CHANGELOG.md
Helper function to determine if a given model name starts with 'ollama/'. Used for auto-selection of completion functions.
```python
def is_ollama_model(model):
pass
```
--------------------------------
### Parse CAMT from XML String
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/examples/README.md
This example demonstrates parsing CAMT data directly from an in-memory XML string, avoiding disk I/O.
```python
parse_camt_from_string.py
```
--------------------------------
### Configure WSL to Use Windows Ollama
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/examples/hybrid/README.md
Set the base API URL to point to Ollama running on the Windows host when using WSL.
```bash
export BSP_HYBRID_API_BASE=http://host.docker.internal:11434
```
--------------------------------
### API: Health Check
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/README.md
Perform a health check on the running bank statement parser API server using a `curl` GET request.
```bash
curl http://localhost:8000/health
```
--------------------------------
### Configure Hosted LLM Provider
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/examples/hybrid/README.md
Set environment variables to use a hosted LLM provider like Anthropic via LiteLLM.
```bash
export BSP_HYBRID_MODEL=anthropic/claude-3-haiku-20240307
export ANTHROPIC_API_KEY=sk-ant-...
```
--------------------------------
### Hybrid Pipeline CLI Walkthrough (Bash)
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/examples/README.md
Provides four variations of the new `--type ingest` CLI subcommand, demonstrated using bash.
```bash
hybrid/06_cli_walkthrough.sh
```
--------------------------------
### Convert Parser Output to Polars DataFrame
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/README.md
Convert the output of any bank statement parser into a Polars DataFrame for efficient data manipulation. Requires `polars` to be installed.
```python
polars_df = parser.to_polars()
lazy_df = parser.to_polars_lazy()
```
--------------------------------
### AccountMapper - Load Rules from JSON
Source: https://context7.com/sebastienrousseau/bankstatementparser/llms.txt
Loads account mapping rules from a JSON configuration file.
```Python
# mapping.json:
# {
# "default": "Expenses:Uncategorized",
# "rules": [{"pattern": "SALARY", "account": "Income:Salary"}]
# }
from bankstatementparser.enrichment.account_mapper import AccountMapper
mapper = AccountMapper.from_json("mapping.json")
```
--------------------------------
### Run 02_smart_ingest_text_llm.py in Live Mode
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/examples/hybrid/README.md
Execute the text-based LLM ingestion script in live mode by setting the BSP_HYBRID_MODEL environment variable. This script will interact with a real LLM provider. Ensure the LLM service is reachable.
```text
$ BSP_HYBRID_MODEL=ollama/llama3 python examples/hybrid/02_smart_ingest_text_llm.py
Mode: LIVE
Model: ollama/llama3
...
```
--------------------------------
### Generate Sample PDFs for Hybrid Pipeline
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/README.md
Script to produce reproducible synthetic UK-bank PDFs, including digital and scanned versions, for testing the hybrid pipeline.
```python
from bankstatementparser.hybrid.generate_sample_pdfs import generate_pdfs
# Generate sample PDFs for testing
generate_pdfs(output_dir="./samples")
```
--------------------------------
### Verify Repository with Linters and Tests
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/README.md
Commands to run linters (ruff, mypy, bandit) and the test suite (pytest) to verify the repository's code quality and correctness.
```bash
# Run code checks and tests locally
ruff check bankstatementparser tests examples scripts
python -m mypy bankstatementparser
python -m pytest
bandit -r bankstatementparser examples scripts -q
```
--------------------------------
### Configure Hosted Vision Model
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/FAQ.md
Set the environment variable for a hosted vision model and provide the corresponding API key. Recommended for production-grade vision tasks.
```bash
export BSP_HYBRID_VISION_MODEL=anthropic/claude-opus-4-6
export ANTHROPIC_API_KEY=sk-ant-...
```
--------------------------------
### Account Mapping with Regex
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/CHANGELOG.md
Utilizes an AccountMapper class with regex rules loaded from a JSON configuration for flexible account mapping.
```python
AccountMapper()
```
--------------------------------
### Walkthrough CLI with Shell Script
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/examples/hybrid/README.md
Execute a shell script that walks through the command-line interface functionalities of the bank statement parser.
```bash
bash examples/hybrid/06_cli_walkthrough.sh
```
--------------------------------
### Hybrid Pipeline CLI Walkthrough (PowerShell)
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/examples/README.md
The PowerShell equivalent for the `--type ingest` CLI subcommand, suitable for native Windows environments without WSL.
```powershell
hybrid/06_cli_walkthrough.ps1
```
--------------------------------
### Smart Ingest: Deterministic Path (No LLM)
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/examples/README.md
Demonstrates the `smart_ingest()` function using a CAMT.053 file, without involving LLM processing.
```python
hybrid/01_smart_ingest_deterministic.py
```
--------------------------------
### Programmatic Usage - Create API App
Source: https://context7.com/sebastienrousseau/bankstatementparser/llms.txt
Demonstrates how to programmatically create the FastAPI application for the bank statement parser.
```Python
from bankstatementparser.api import create_app
app = create_app(title="My Finance API", version="1.0.0")
# To run the server, use a tool like uvicorn:
# uvicorn bankstatementparser.api:app --host 0.0.0.0 --port 8000
```
--------------------------------
### Run 02_smart_ingest_text_llm.py in Mock Mode
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/examples/hybrid/README.md
Execute the text-based LLM ingestion script in mock mode. This demonstrates the default behavior without making actual API calls. Ensure the script is run without specific environment variables for LLM providers.
```text
$ python examples/hybrid/02_smart_ingest_text_llm.py
Mode: MOCK
Set BSP_HYBRID_MODEL=ollama/llama3 (and run `ollama serve`)
to call a real model instead of the mock.
...
Source method: llm
Verification: VERIFIED
```
--------------------------------
### Run Full Validation Suite
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/CONTRIBUTING.md
Execute the complete validation pipeline using the 'make verify' command. This ensures all checks (ruff, mypy, pytest, bandit) pass.
```bash
make verify
```
--------------------------------
### CLI Commands for CAMT and PAIN.001
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/README.md
Shows command-line interface usage for processing CAMT and PAIN.001 files.
```bash
# Process CAMT files using the CLI
bankstatementparser camt --input camt053.xml --output output.csv
# Process PAIN.001 files using the CLI
bankstatementparser pain001 --input pain001.xml --output output.json
```
--------------------------------
### Verify Transaction Balances with verify_balance
Source: https://context7.com/sebastienrousseau/bankstatementparser/llms.txt
Use verify_balance for single-currency statements and verify_balance_multi_currency for statements with multiple currencies. These functions check if opening balance + total credits - total debits equals the closing balance within a specified tolerance. They require a list of transactions and the opening/closing balances.
```python
from decimal import Decimal
from bankstatementparser.hybrid.verification import (
verify_balance,
verify_balance_multi_currency,
VerificationStatus,
)
from bankstatementparser import CamtParser, Deduplicator
parser = CamtParser("statement.xml")
dedup = Deduplicator()
transactions = dedup.from_dataframe(parser.parse())
# Single-currency verification
v = verify_balance(
transactions,
opening_balance=Decimal("5000.00"),
closing_balance=Decimal("3765.44"),
tolerance=Decimal("0.01"), # one cent tolerance
)
print(v.status) # VerificationStatus.VERIFIED
print(v.total_credits) # Decimal('250.00')
print(v.total_debits) # Decimal('1484.56')
print(v.discrepancy) # Decimal('0.00')
print(v.message) # "Balance verified within tolerance"
# Multi-currency (e.g. GBP + EUR transactions in same statement)
results = verify_balance_multi_currency(
transactions,
balances={
"GBP": (Decimal("5000.00"), Decimal("3765.44")),
"EUR": (Decimal("2000.00"), Decimal("1800.00")),
},
)
for currency, v in results.items():
print(f"{currency}: {v.status.value}")
# GBP: verified
# EUR: discrepancy (if totals don't match)
```
--------------------------------
### Ingest Bank Statement Files
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/README.md
Use `smart_ingest()` to route any input file through the most cost-effective extraction path. Deterministic parsers are used first, followed by text or vision LLMs for unstandardized PDFs. LLM providers can be configured via LiteLLM.
```python
from bankstatementparser import smart_ingest
# Example usage:
# result = smart_ingest("path/to/your/bankstatement.pdf")
# print(result.transactions)
```
--------------------------------
### Extract CAMT Balances, Stats, and Summaries
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/README.md
Illustrates how to extract financial balances, statistics, and summaries from CAMT files.
```python
from bankstatementparser import inspect_camt
# Inspect a CAMT file for balances, stats, and summaries
inspection = inspect_camt("camt053.xml")
print(inspection.balances)
print(inspection.stats)
print(inspection.summaries)
```
--------------------------------
### Use New Strip Mode for Dense Pages with VisionExtractor
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/CHANGELOG.md
Instantiate VisionExtractor with strip_rows=True and n_strips=4 to process dense pages more effectively. This requires importing VisionExtractor and smart_ingest from bankstatementparser.hybrid.
```python
from bankstatementparser.hybrid import VisionExtractor, smart_ingest
vision = VisionExtractor(strip_rows=True, n_strips=4)
result = smart_ingest("dense_statement.pdf", vision_extractor=vision)
```
--------------------------------
### Stream PAIN.001 Payments Incrementally
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/README.md
Illustrates processing PAIN.001 payments incrementally, suitable for large files.
```python
from bankstatementparser import stream_pain001
# Stream payments from a PAIN.001 file incrementally
for payment in stream_pain001("pain001.xml"):
print(payment)
```
--------------------------------
### Verify Multi-currency Balances
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/README.md
Verify the accuracy of balances across multiple currencies by comparing provided opening and closing balances against the transactions. Returns a status for each currency indicating whether the balance is verified.
```python
from bankstatementparser.hybrid import verify_balance_multi_currency
results = verify_balance_multi_currency(
transactions,
balances={"GBP": (opening, closing), "EUR": (opening, closing)},
)
for currency, v in results.items():
print(f"{currency}: {v.status.value}")
```
--------------------------------
### AccountMapper - Inline Construction
Source: https://context7.com/sebastienrousseau/bankstatementparser/llms.txt
Constructs an AccountMapper with inline rules for categorizing transactions.
```Python
from bankstatementparser.enrichment.account_mapper import AccountMapper, AccountRule
from bankstatementparser import CamtParser, Deduplicator
mapper = AccountMapper(
rules=[
AccountRule(pattern=r"COFFEE|STARBUCKS|COSTA", account="Expenses:Food:Coffee"),
AccountRule(pattern=r"SALARY|PAYROLL", account="Income:Salary"),
AccountRule(pattern=r"RENT|LANDLORD", account="Expenses:Housing:Rent"),
AccountRule(pattern=r"AWS|GITHUB|GOOGLE CLOUD", account="Expenses:Tech:Cloud"),
],
default="Expenses:Uncategorized",
)
parser = CamtParser("statement.xml")
dedup = Deduplicator()
transactions = dedup.from_dataframe(parser.parse())
accounts = mapper.map_batch(transactions)
for tx, account in zip(transactions, accounts):
print(f"{tx.description[:40]:<40} -> {account}")
```
--------------------------------
### Smart Ingest with Multimodal Vision Extraction
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/README.md
Path C of the hybrid pipeline: uses `smart_ingest()` with multimodal vision capabilities and auto-routing for low text density documents.
```python
from bankstatementparser.hybrid import smart_ingest
# Path C: Multimodal vision extraction with auto-routing
result = smart_ingest(input_file="scanned_statement.pdf", vision_model="gpt-4o")
print(result)
```
--------------------------------
### Pull and Set Minicpm-v for Vision LLM
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/FAQ.md
Download the minicpm-v model and configure the environment variable for the hybrid vision model. This model is recommended for document understanding tasks.
```bash
ollama pull minicpm-v
export BSP_HYBRID_VISION_MODEL=ollama/minicpm-v
```
--------------------------------
### CLI: Parse PAIN.001 to CSV
Source: https://context7.com/sebastienrousseau/bankstatementparser/llms.txt
Uses the command-line interface to parse a PAIN.001 file and export the payment data to a CSV file.
```bash
# Parse PAIN.001
bankstatementparser --type pain001 --input payment.xml --output payments.csv
```
--------------------------------
### OfxParser / Mt940Parser
Source: https://context7.com/sebastienrousseau/bankstatementparser/llms.txt
Parses OFX, QFX, and MT940 bank statement files. OfxParser uses regex for tag extraction, while Mt940Parser specifically handles MT940 SWIFT files by parsing key fields. Both return parsed data in a DataFrame and provide statement summaries.
```APIDOC
## OfxParser / Mt940Parser — Parse OFX/QFX and MT940 statements
`OfxParser` handles OFX and QFX files via regex-based tag extraction. `Mt940Parser` handles MT940 SWIFT files by parsing `:25:`, `:60F:`, `:61:`, and `:86:` field tags.
```python
from bankstatementparser import OfxParser, Mt940Parser
# OFX / QFX
ofx = OfxParser("transactions.ofx")
df = ofx.parse()
# Columns: date, description, amount, currency, account_id,
# transaction_id, transaction_type
print(df[["date", "description", "amount"]].head())
ofx_summary = ofx.get_summary()
# {'account_id': '123456789', 'statement_date': '20240131',
# 'transaction_count': 12, 'total_amount': -450.75, 'currency': 'USD'}
# MT940
mt = Mt940Parser("statement.sta")
df = mt.parse()
# Columns: date (YYMMDD), amount (signed), transaction_id, account_id,
# currency, description
print(df)
mt_summary = mt.get_summary()
# {'account_id': 'NL91ABNA0417164300', 'statement_date': '240131',
# 'transaction_count': 8, 'total_amount': 2350.00,
# 'opening_balance': 10000.0, 'closing_balance': 12350.0, 'currency': 'EUR'}
```
```
--------------------------------
### Auto-Detect and Parse Various Formats
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/README.md
Shows how the parser can automatically detect and process multiple formats including CSV, OFX, MT940, and XML.
```python
from bankstatementparser import parse_detected_formats
# Auto-detect and parse formats like CSV, OFX, MT940, and XML
for transaction in parse_detected_formats("statement.file"):
print(transaction)
```
--------------------------------
### Auto-detect Statement Format and Create Parser
Source: https://context7.com/sebastienrousseau/bankstatementparser/llms.txt
Use detect_statement_format() to identify the financial statement format based on file extension and content. create_parser() then instantiates the appropriate parser without manual format specification.
```python
from bankstatementparser import detect_statement_format, create_parser
from bankstatementparser.input_validator import ValidationError
# Auto-detect from extension and content sniffing
try:
fmt = detect_statement_format("transactions.ofx")
# Returns one of: "camt", "pain001", "csv", "ofx", "qfx", "mt940"
print(fmt) # "ofx"
parser = create_parser("transactions.ofx", fmt)
records = parser.parse()
# Or let create_parser detect the format automatically
parser = create_parser("statement.xml")
records = parser.parse()
except ValidationError as e:
print(f"Unknown format: {e}")
# Supported format strings:
# "camt" -> CamtParser (CAMT.053 XML)
# "pain001" -> Pain001Parser (PAIN.001 XML)
# "csv" -> CsvStatementParser
# "ofx" -> OfxParser
# "qfx" -> QfxParser (alias for OfxParser)
# "mt940" -> Mt940Parser
```
--------------------------------
### Command Line: Review Ingest Result JSON
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/README.md
Utilize the command-line interface (v0.0.6) to review a previously saved IngestResult JSON file.
```bash
bankstatementparser --type review --input result.json
```
--------------------------------
### CLI: Parse CAMT and Display to Stdout
Source: https://context7.com/sebastienrousseau/bankstatementparser/llms.txt
Uses the command-line interface to parse a CAMT file and print the results directly to standard output.
```bash
# Parse CAMT and display to stdout
bankstatementparser --type camt --input statement.xml
```
--------------------------------
### Configure Git for Signed Commits
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/CONTRIBUTING.md
Configure Git globally to sign commits and tags using SSH. Set the user signing key to your SSH public key file.
```bash
git config --global commit.gpgsign true
git config --global tag.gpgSign true
git config --global gpg.format ssh
git config --global user.signingkey ""
```
--------------------------------
### Programmatic API Usage with FastAPI
Source: https://context7.com/sebastienrousseau/bankstatementparser/llms.txt
Creates a FastAPI application instance programmatically for integration into custom ASGI servers. Allows customization of the app's title and version.
```python
# ASGI / programmatic usage
from bankstatementparser.api import create_app
app = create_app(title="My Finance API", version="1.0.0")
# uvicorn bankstatementparser.api:app --host 0.0.0.0 --port 8000
```
--------------------------------
### CLI: Stream Transactions with PII Visible
Source: https://context7.com/sebastienrousseau/bankstatementparser/llms.txt
Parses a CAMT file using the CLI in streaming mode, with Personally Identifiable Information (PII) displayed.
```bash
# Stream with PII visible
bankstatementparser --type camt --input statement.xml --streaming --show-pii
```
--------------------------------
### Process Secure ZIP Archive
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/README.md
Demonstrates how to securely process transactions from a ZIP archive, with built-in protection against ZIP bombs and other threats.
```python
from bankstatementparser import parse_camt_zip
# Process transactions from a secure ZIP archive
for transaction in parse_camt_zip("archive.zip"):
print(transaction)
```
--------------------------------
### Hybrid Extraction with PDFs
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/README.md
Utilize smart_ingest for unified file processing, including digital and scanned PDFs. Configure LLM or vision models via environment variables.
```python
from bankstatementparser.hybrid import smart_ingest
# Path A — deterministic parser (free, fastest, $0)
result = smart_ingest("statement.xml")
print(result.source_method) # "deterministic"
# Path B — text-LLM for digital PDFs (set BSP_HYBRID_MODEL=ollama/llama3)
result = smart_ingest("statement.pdf")
print(result.source_method) # "llm"
print(result.verification.status) # VERIFIED | DISCREPANCY | FAILED
# Path C — multimodal vision for scanned PDFs (set BSP_HYBRID_VISION_MODEL)
# auto-routed when pypdf cannot extract enough text
result = smart_ingest("scan.pdf")
print(result.source_method) # "vision"
```
--------------------------------
### Command Line: Parse and Display Statement
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/README.md
Use the `bankstatementparser` command-line script to parse a CAMT statement and display its content.
```bash
bankstatementparser --type camt --input statement.xml
```
--------------------------------
### Scan Directory and Ingest Statements
Source: https://github.com/sebastienrousseau/bankstatementparser/blob/main/README.md
Recursively scan a directory for statement files (e.g., PDFs) matching a pattern, ingest them, and deduplicate transactions across the entire batch. Reports the total number of files processed and unique transactions found.
```python
from bankstatementparser.hybrid import scan_and_ingest
batch = scan_and_ingest("statements/2026/", pattern="**/*.pdf")
print(f"{batch.file_count} files, {batch.total_unique} unique transactions")
```