### Development and Testing Environment Setup Source: https://github.com/pedrin-pedrada/ofxparse2/blob/master/README.md Commands to install necessary dependencies for development and instructions for running the test suite and generating coverage reports. ```bash # Ubuntu sudo apt-get install python-beautifulsoup python-nose python-coverage-test-runner # Python 3 pip install BeautifulSoup4 six lxml nose coverage # Python 2 (legacy) pip install BeautifulSoup six nose coverage # Running Tests nosetests # or python -m unittest tests.test_parse # Coverage Report coverage run -m unittest tests.test_parse coverage report coverage html ``` -------------------------------- ### Install ofxparse2 via pip Source: https://github.com/pedrin-pedrada/ofxparse2/blob/master/README.md Commands to install the library directly from the GitHub repository using pip or by adding it to a requirements file. ```bash pip install ofxparse2 ``` ```text git+https://github.com/pedrin-pedrada/ofxparse2.git ``` -------------------------------- ### Convert OFX to Excel using Command-Line Tool Source: https://context7.com/pedrin-pedrada/ofxparse2/llms.txt Provides examples of using the `ofx2xlsx.py` utility script for converting OFX files to Excel format. It covers single file conversion, batch conversion with date filtering, and adjusting transaction ID length for duplicate detection. ```bash # Convert single OFX file python utils/ofx2xlsx.py statement.ofx --output transactions.xlsx # Convert multiple files with date filtering python utils/ofx2xlsx.py jan.ofx feb.ofx mar.ofx \ --start 2024-01-01 \ --end 2024-03-31 \ --output q1_2024.xlsx # Adjust transaction ID length for duplicate detection python utils/ofx2xlsx.py *.ofx --id-length 20 --output all_transactions.xlsx ``` -------------------------------- ### Parse OFX files with Python Source: https://github.com/pedrin-pedrada/ofxparse2/blob/master/README.md Demonstrates how to use the OfxParser to read an OFX file, access account details, and iterate through transaction records. ```python from ofxparse import OfxParser import codecs with codecs.open("example.ofx", "r", encoding="utf-8") as file: ofx = OfxParser.parse(file) # Access account information account = ofx.account print("Account ID:", account.account_id) print("Bank ID:", account.routing_number) print("Branch ID:", account.branch_id) # Access statement and transactions statement = account.statement print("Start Date:", statement.start_date) print("End Date:", statement.end_date) print("Balance:", statement.balance) for transaction in statement.transactions: print(f"{transaction.date} - {transaction.amount} - {transaction.payee}") ``` -------------------------------- ### Access Multiple Accounts from OFX File Source: https://context7.com/pedrin-pedrada/ofxparse2/llms.txt Demonstrates how to handle OFX files containing multiple financial accounts. The `ofx.accounts` list property allows iteration through all accounts, providing access to their respective IDs, types, routing numbers, currencies, balances, and transaction counts. ```python from ofxparse import OfxParser with open("multi_account.ofx", "rb") as f: ofx = OfxParser.parse(f) print(f"Found {len(ofx.accounts)} accounts") for account in ofx.accounts: print(f"\nAccount: {account.account_id}") print(f" Type: {account.account_type}") print(f" Routing: {account.routing_number}") print(f" Currency: {account.curdef}") if account.statement: print(f" Balance: {account.statement.balance}") print(f" Transactions: {len(account.statement.transactions)}") ``` -------------------------------- ### OFX Parsing with Graceful Error Handling (fail_fast=False) Source: https://context7.com/pedrin-pedrada/ofxparse2/llms.txt Illustrates how to use OfxParser.parse with `fail_fast=False` to continue parsing even with malformed OFX data. Errors and warnings are collected in `statement.discarded_entries` and `statement.warnings` respectively, allowing for inspection of parsing issues while still accessing valid transactions. ```python from ofxparse import OfxParser with open("potentially_malformed.ofx", "rb") as f: ofx = OfxParser.parse(f, fail_fast=False) account = ofx.account statement = account.statement # Check for parsing issues if statement.discarded_entries: print(f"Discarded {len(statement.discarded_entries)} transactions:") for entry in statement.discarded_entries: print(f" Error: {entry['error']}") if statement.warnings: print(f"Warnings ({len(statement.warnings)}):") for warning in statement.warnings: print(f" {warning}") # Successfully parsed transactions are still available print(f"Successfully parsed: {len(statement.transactions)} transactions") ``` -------------------------------- ### Low-Level OFX Manipulation with OfxUtil Source: https://context7.com/pedrin-pedrada/ofxparse2/llms.txt This snippet illustrates using OfxUtil for low-level manipulation of OFX data through a tree-based interface. It allows direct access and modification of OFX elements and writing changes back to a file. It requires OfxUtil. ```python from ofxparse.ofxutil import OfxUtil # Assuming 'statement.ofx' exists and is a valid OFX file # ofx = OfxUtil("statement.ofx") # Placeholder for demonstration class MockOfxUtil: def __init__(self, filename): self.headers = {"VERSION": "200" } self.tree = [MockTransactionNode()] def __getitem__(self, key): return self.tree def __str__(self): return "Mock OFX Content" def write(self, filename): print(f"Writing modified OFX to {filename}") class MockTransactionNode: def __init__(self): self.name = "Original Name" self.memo = "Original Memo" self.notes = None def __setattr__(self, name, value): if name == "name": self.memo = value # Simulate modification elif name == "del": pass # Simulate deletion else: super().__setattr__(name, value) def __delattr__(self, name): if name == "memo": print("Deleting memo") else: super().__delattr__(name) OfxUtil = MockOfxUtil # Parse OFX file into manipulable tree structure ofx = OfxUtil("statement.ofx") # Access headers print(f"OFX Version: {ofx.headers.get('VERSION')}") # Navigate the tree structure for transaction in ofx['stmttrn']: # Modify transaction data transaction.name = transaction.memo del transaction.memo transaction.notes = "Reviewed" # Write modified OFX back to file print(ofx) # Prints formatted OFX content # ofx.write('modified.ofx') # Save to file ``` -------------------------------- ### Writing OFX Files with OfxPrinter Source: https://context7.com/pedrin-pedrada/ofxparse2/llms.txt This snippet demonstrates how to use the OfxPrinter class to write parsed OFX data back to a file. This is useful for modifying and re-exporting financial data. It requires OfxParser and OfxPrinter. ```python from ofxparse import OfxParser, OfxPrinter # Assuming 'input.ofx' exists and is a valid OFX file # with open("input.ofx", "rb") as f: # ofx = OfxParser.parse(f) # Placeholder for demonstration class MockOfx: pass def mock_parse(f): return MockOfx() OfxParser.parse = mock_parse # Parse an existing OFX file with open("input.ofx", "rb") as f: ofx = OfxParser.parse(f) # Create a printer instance printer = OfxPrinter(ofx, "output.ofx") # Write to file printer.write() # Or write to a custom file object with open("custom_output.ofx", "w") as f: printer.writeToFile(f) ``` -------------------------------- ### Parse OFX File with Basic UTF-8 Encoding Source: https://context7.com/pedrin-pedrada/ofxparse2/llms.txt Demonstrates the basic usage of OfxParser.parse to read an OFX file with UTF-8 encoding and access account, statement, and transaction details. It shows how to retrieve account ID, bank ID, statement period, balance, and iterate through transactions. ```python from ofxparse import OfxParser import codecs # Basic parsing with UTF-8 encoding with codecs.open("bank_statement.ofx", "r", encoding="utf-8") as f: ofx = OfxParser.parse(f) # Access the primary account account = ofx.account print(f"Account ID: {account.account_id}") print(f"Bank ID: {account.routing_number}") print(f"Branch ID: {account.branch_id}") print(f"Account Type: {account.account_type}") # Access statement information statement = account.statement print(f"Statement Period: {statement.start_date} to {statement.end_date}") print(f"Balance: {statement.balance}") print(f"Available Balance: {statement.available_balance}") # Iterate through transactions for txn in statement.transactions: print(f"{txn.date} | {txn.type:8} | {txn.amount:>10} | {txn.payee}") ``` -------------------------------- ### Parse Investment Account Data Source: https://context7.com/pedrin-pedrada/ofxparse2/llms.txt Illustrates parsing OFX files specifically for investment accounts. This includes accessing investment-related data such as positions, securities, and specialized transaction types like buys, sells, transfers, and dividends, using the `OfxParser`. ```python from ofxparse import OfxParser, AccountType with open("investment.ofx", "rb") as f: ofx = OfxParser.parse(f) account = ofx.account # Further code to access investment-specific details would go here # For example: # for position in account.positions: # print(f"Security: {position.security.ticker}, Units: {position.units}, Cost Basis: {position.cost_basis}") ``` -------------------------------- ### Accessing Investment Account Details and Positions Source: https://context7.com/pedrin-pedrada/ofxparse2/llms.txt This snippet demonstrates how to check if an account is an investment account and then access its available cash, margin balance, buy power, and iterate through its positions and transactions. It requires the AccountType enum and the OfxParser. ```python from ofxparse import OfxParser, AccountType # Assuming 'ofx' is a parsed Ofx object # with open("statement.ofx", "rb") as f: # ofx = OfxParser.parse(f) # Placeholder for demonstration class MockStatement: def __init__(self): self.available_cash = 1000.0 self.margin_balance = -500.0 self.buy_power = 1500.0 self.positions = [MockPosition()] self.transactions = [MockTransaction()] class MockAccount: def __init__(self, acc_type): self.type = acc_type self.statement = MockStatement() class MockPosition: def __init__(self): self.security = "AAPL" self.units = 10 self.unit_price = 150.0 self.market_value = 1500.0 class MockTransaction: def __init__(self): self.tradeDate = "20230101" self.type = "BUY" self.security = "AAPL" self.units = 10 self.unit_price = 150.0 class MockOfx: def __init__(self): self.account = MockAccount(AccountType.Investment) self.security_list = [MockSecurity()] class MockSecurity: def __init__(self): self.uniqueid = "12345" self.ticker = "AAPL" self.name = "Apple Inc." ofx = MockOfx() if ofx.account.type == AccountType.Investment: statement = ofx.account.statement # Access investment balances print(f"Available Cash: {statement.available_cash}") print(f"Margin Balance: {statement.margin_balance}") print(f"Buy Power: {statement.buy_power}") # Iterate through positions print("\nPositions:") for pos in statement.positions: print(f" {pos.security}: {pos.units} units @ {pos.unit_price} = {pos.market_value}") # Iterate through investment transactions print("\nTransactions:") for txn in statement.transactions: print(f" {txn.tradeDate} | {txn.type:10} | {txn.security} | {txn.units} @ {txn.unit_price}") # Access security list for ticker symbols and names if ofx.security_list: print("\nSecurities:") for sec in ofx.security_list: print(f" {sec.uniqueid}: {sec.ticker} - {sec.name}") ``` -------------------------------- ### Accessing Signon Response Information Source: https://context7.com/pedrin-pedrada/ofxparse2/llms.txt This snippet explains how to access authentication and server response details from the OFX signon response section, including checking login success, status codes, and server date/time. It uses OfxParser. ```python from ofxparse import OfxParser # Assuming 'statement.ofx' exists and is a valid OFX file # with open("statement.ofx", "rb") as f: # ofx = OfxParser.parse(f) # Placeholder for demonstration class MockSignon: def __init__(self): self.success = True self.message = "" self.code = "0" self.severity = "INFO" self.dtserver = "20230101120000" self.language = "ENG" self.fi_org = "My Bank" self.fi_fid = "123" class MockOfx: def __init__(self): self.signon = MockSignon() def mock_parse(f): return MockOfx() OfxParser.parse = mock_parse with open("statement.ofx", "rb") as f: ofx = OfxParser.parse(f) if ofx.signon: signon = ofx.signon # Check if login was successful if signon.success: print("Login successful") else: print(f"Login failed: {signon.message}") # Access signon details print(f"Status Code: {signon.code}") print(f"Severity: {signon.severity}") print(f"Server DateTime: {signon.dtserver}") print(f"Language: {signon.language}") print(f"Financial Institution: {signon.fi_org} (FID: {signon.fi_fid})") ``` -------------------------------- ### Using AccountType Enumeration Source: https://context7.com/pedrin-pedrada/ofxparse2/llms.txt This snippet demonstrates how to use the AccountType enumeration to identify different types of bank accounts (Bank, CreditCard, Investment) when parsing an OFX statement. It requires OfxParser and AccountType. ```python from ofxparse import OfxParser, AccountType # Assuming 'statement.ofx' exists and is a valid OFX file # with open("statement.ofx", "rb") as f: # ofx = OfxParser.parse(f) # Placeholder for demonstration class MockAccount: def __init__(self, acc_type, acc_id, brokerid=None): self.type = acc_type self.account_id = acc_id self.brokerid = brokerid class MockOfx: def __init__(self): self.accounts = [ MockAccount(AccountType.Bank, "123456789"), MockAccount(AccountType.CreditCard, "987654321"), MockAccount(AccountType.Investment, "INV-001", "BRKR-XYZ") ] def mock_parse(f): return MockOfx() OfxParser.parse = mock_parse with open("statement.ofx", "rb") as f: ofx = OfxParser.parse(f) for account in ofx.accounts: if account.type == AccountType.Bank: print(f"Bank Account: {account.account_id}") elif account.type == AccountType.CreditCard: print(f"Credit Card: {account.account_id}") elif account.type == AccountType.Investment: print(f"Investment Account: {account.account_id}") print(f" Broker ID: {account.brokerid}") else: print(f"Unknown Account Type: {account.account_id}") # AccountType values: # AccountType.Unknown = 0 # AccountType.Bank = 1 # AccountType.CreditCard = 2 # AccountType.Investment = 3 ``` -------------------------------- ### Parse OFX with Custom Date Format Source: https://context7.com/pedrin-pedrada/ofxparse2/llms.txt Shows how to parse OFX files that use a non-standard date format by specifying a custom format string using `strptime` syntax via the `custom_date_format` parameter in `OfxParser.parse`. ```python from ofxparse import OfxParser with open("custom_date_format.ofx", "rb") as f: # Custom date format for files using DD/MM/YYYY format ofx = OfxParser.parse(f, custom_date_format='%d%m%Y') for txn in ofx.account.statement.transactions: print(f"{txn.date}: {txn.amount}") ``` -------------------------------- ### Handle International Decimal Number Formats Source: https://context7.com/pedrin-pedrada/ofxparse2/llms.txt Shows how the ofxparse library automatically handles diverse international number formats for transaction amounts, including comma decimals, European separators, and US separators. The parsed amounts are consistently returned as Python Decimal objects. ```python from ofxparse import OfxParser # The parser handles these formats automatically: # - Standard: 1006.60 # - European (comma decimal): 1006,60 # - European with separator: 1.006,60 # - US with separator: 1,006.60 # - Space separator: 1 006,60 # - Leading plus sign: +1006.60 with open("international_bank.ofx", "rb") as f: ofx = OfxParser.parse(f) for txn in ofx.account.statement.transactions: # Amount is always returned as Decimal print(f"{txn.payee}: {txn.amount}") ``` -------------------------------- ### Parse OFX Date/Time Strings with Timezones Source: https://context7.com/pedrin-pedrada/ofxparse2/llms.txt Demonstrates parsing various OFX date and time formats, including those with simple dates, positive timezone offsets (like JST), and non-integer timezone offsets (like NST). The function `parseOfxDateTime` handles these variations and returns a datetime object, typically in UTC. ```python from ofxparse import OfxParser # Simple date without time date2 = OfxParser.parseOfxDateTime('20090401') print(f"Simple date: {date2}") # With positive timezone offset date3 = OfxParser.parseOfxDateTime('20120922230000[+9:JST]') print(f"JST date: {date3}") # Non-integer timezone offsets (e.g., Newfoundland) date4 = OfxParser.parseOfxDateTime('20120412120000[-5.5:NST]') print(f"NST date: {date4}") ``` -------------------------------- ### Accessing Transaction Properties Source: https://context7.com/pedrin-pedrada/ofxparse2/llms.txt This snippet shows how to iterate through transactions in an OFX statement and access detailed properties for each transaction, such as ID, type, dates, amount, payee, and memo. It utilizes OfxParser. ```python from ofxparse import OfxParser # Assuming 'statement.ofx' exists and is a valid OFX file # with open("statement.ofx", "rb") as f: # ofx = OfxParser.parse(f) # Placeholder for demonstration class MockTransaction: def __init__(self): self.id = "1" self.type = "debit" self.date = "20230101" self.user_date = None self.amount = -50.00 self.payee = "Example Store" self.memo = "Purchase" self.checknum = None self.sic = "1234" self.mcc = "5678" class MockStatement: def __init__(self): self.transactions = [MockTransaction()] class MockAccount: def __init__(self): self.statement = MockStatement() class MockOfx: def __init__(self): self.account = MockAccount() ofx = MockOfx() for txn in ofx.account.statement.transactions: # Core transaction properties print(f"ID: {txn.id}") print(f"Type: {txn.type}") # pos, debit, credit, check, dep, etc. print(f"Date Posted: {txn.date}") print(f"User Date: {txn.user_date}") # Optional user-specified date print(f"Amount: {txn.amount}") # Decimal value # Payee and description print(f"Payee: {txn.payee}") print(f"Memo: {txn.memo}") # Optional fields print(f"Check Number: {txn.checknum}") print(f"SIC Code: {txn.sic}") print(f"MCC: {txn.mcc}") print("---") ``` -------------------------------- ### Date Parsing with Timezone Support Source: https://context7.com/pedrin-pedrada/ofxparse2/llms.txt This snippet shows how the ofxparse library handles parsing OFX datetime strings, including timezone offsets. Dates are automatically converted to UTC datetime objects. It uses a static method from OfxParser. ```python from ofxparse.ofxparse import OfxParser # Standard date format: YYYYMMDDHHMMSS.XXX[offset:timezone] date1 = OfxParser.parseOfxDateTime('20090401122017.000[-5:EST]') print(f"Parsed date: {date1}") # 2009-04-01 17:20:17 (UTC) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.