### Use ofxget CLI Tool Source: https://context7.com/csingley/ofxtools/llms.txt Provides examples for using the ofxget command-line tool to list institutions, request profiles, scan configurations, and download financial statements. ```bash ofxget list ofxget prof amex ofxget scan https://ofx.example.com/download ofxget acctinfo amex --user myusername --write ofxget stmt amex --start 20240101 --end 20240331 > statement.ofx ofxget stmt vanguard --investment 12345678 --user myusername ``` -------------------------------- ### Command Line Interface - ofxget Source: https://context7.com/csingley/ofxtools/llms.txt Usage examples for the `ofxget` command-line tool, including listing institutions, requesting server profiles, scanning for parameters, and downloading statements. ```APIDOC ## Command Line Interface - ofxget The `ofxget` CLI tool provides convenient access to OFX download functionality from the command line. ```bash # List known financial institutions ofxget list # Request server profile (test connection, no auth needed) ofxget prof amex ofxget prof --org AMEX --fid 3101 --url https://online.americanexpress.com/... # Scan for working OFX version and format parameters ofxget scan https://ofx.example.com/download ofxget scan chase --write # Save working config # Get account information ofxget acctinfo amex --user myusername --write # Download statements ofxget stmt amex --user myusername ofxget stmt amex --start 20240101 --end 20240331 > statement.ofx # Download credit card statement ofxget stmt amex --creditcard 1234567890 --user myusername # Download investment statement ofxget stmt vanguard --investment 12345678 --user myusername # Download with all accounts configured ofxget stmt amex --all --user myusername --write # Configuration file location varies by platform: # Linux: ~/.config/ofxtools/ofxget.cfg # Mac: ~/Library/Preferences/ofxtools/ofxget.cfg # Windows: %APPDATA%\ofxtools\ofxget.cfg # Example configuration file content: # [amex] # url: https://online.americanexpress.com/myca/ofxdl/desktop/desktopDownload.do?request_type=nl_ofxdownload # org: AMEX # fid: 3101 # user: myusername # creditcard: 1111222233334444,5555666677778888 ``` ``` -------------------------------- ### Configure system keyring for password storage Source: https://github.com/csingley/ofxtools/blob/master/docs/client.md Install the keyring dependency and use the --savepass flag to securely store and retrieve credentials for automated downloads. ```bash pip install --user keyring ofxget acctinfo -u --write --savepass ``` -------------------------------- ### Defining OFX Configuration in INI Format Source: https://github.com/csingley/ofxtools/blob/master/docs/client.md Example of how to manually define institution-specific OFX connection settings within the ofxget.cfg file. ```ini [etrade] version = 102 [usaa] version = 151 unclosedelements = true [vanguard] version = 203 pretty = true ``` -------------------------------- ### Setting Global and Server-Specific CLIENTUID with ofxget Source: https://github.com/csingley/ofxtools/blob/master/docs/client.md Shows examples of how to set the CLIENTUID using the 'ofxget' command. This includes generating a global default CLIENTUID by using the --write option with 'scan' or 'prof', and setting a specific CLIENTUID for a server when fetching account information. ```bash # The following generates a global default CLIENTUID $ ofxget scan chase --write # So does this $ ofxget prof chase --write # The following additionally generates a Chase-specific CLIENTUID $ ofxget acctinfo chase -u --savepass --clientuid --write ``` -------------------------------- ### Configure OFX Account Settings Source: https://github.com/csingley/ofxtools/blob/master/docs/client.md An example configuration file structure for ofxget. It stores the server URL, organization ID, financial institution ID, and a comma-separated list of account numbers. ```ini [amex] url: https://online.americanexpress.com/myca/ofxdl/desktop/desktopDownload.do?request_type=nl_ofxdownload org: AMEX fid: 3101 user: creditcard: 888888888888888,999999999999999 ``` -------------------------------- ### Locate ofxget installation path Source: https://github.com/csingley/ofxtools/blob/master/docs/client.md Use the Python interpreter to programmatically determine the file system location of the installed ofxget script. ```python from ofxtools.scripts import ofxget print(ofxget.__file__) ``` -------------------------------- ### Constructing OFX Statement Requests Source: https://context7.com/csingley/ofxtools/llms.txt Provides examples for creating typed request objects for bank, credit card, and investment statements. It also shows how to configure an OFXClient and execute a statement request. ```python import datetime from ofxtools.Client import (OFXClient, StmtRq, CcStmtRq, InvStmtRq, StmtEndRq, CcStmtEndRq) from ofxtools.utils import UTC dtstart = datetime.datetime(2024, 1, 1, tzinfo=UTC) dtend = datetime.datetime(2024, 3, 31, tzinfo=UTC) bank_request = StmtRq(acctid="123456789", accttype="CHECKING", dtstart=dtstart, dtend=dtend, inctran=True) inv_request = InvStmtRq(acctid="999888777", dtstart=dtstart, dtend=dtend, dtasof=dtend, inctran=True, incoo=False, incpos=True, incbal=True) client = OFXClient(url="https://ofxs.ameritrade.com/cgi-bin/apps/OFX", org="Ameritrade Technology Group", fid="AIS", brokerid="ameritrade.com", userid="username", version=203) response = client.request_statements("password", inv_request) ``` -------------------------------- ### Defining OFX Configuration in INI Format Source: https://github.com/csingley/ofxtools/blob/master/docs/client.md Examples of manual configuration file entries using INI format. You can define servers using explicit URL/ORG/FID parameters or by referencing an OFX Home database ID. ```ini # American Express [amex] url: https://online.americanexpress.com/myca/ofxdl/desktop/desktopDownload.do?request_type=nl_ofxdownload org: AMEX fid: 3101 # Alternative using OFX Home ID [amex] ofxhome: 424 ``` -------------------------------- ### Navigating Parsed OFX Data Source: https://context7.com/csingley/ofxtools/llms.txt Provides examples of how to access and navigate the parsed OFX data using Python attribute notation. ```APIDOC ## Navigating Parsed OFX Data ### Description After parsing and converting OFX data using `OFXTree`, you can access the information using convenient Python attribute notation. The library provides shortcuts for navigating nested OFX structures and accessing sub-aggregate attributes. ### Method N/A (This describes data access after parsing) ### Endpoint N/A ### Parameters N/A ### Request Example ```python from ofxtools.Parser import OFXTree from decimal import Decimal # Parse and convert OFX parser = OFXTree() parser.parse('investment_statement.ofx') ofx = parser.convert() # High-level convenience accessors statements = ofx.statements # All STMTRS, CCSTMTRS, INVSTMTRS securities = ofx.securities # SECLIST securities # Example: Accessing transaction details if ofx.statements: first_statement = ofx.statements[0] if hasattr(first_statement, 'banktranlist') and first_statement.banktranlist.transactions: first_transaction = first_statement.banktranlist.transactions[0] print(f"Transaction Amount: {first_transaction.trnamt}") print(f"Transaction Date: {first_transaction.dtposted}") print(f"Transaction Description: {first_transaction.memo}") # Example: Accessing security details if ofx.securities: first_security = ofx.securities[0] print(f"Security ID: {first_security.secid}") print(f"Security Name: {first_security.secname}") ``` ### Response (This section describes data access patterns, not a direct API response) #### Success Response - **ofx.statements** (list) - A list of statement objects (e.g., `StmtRs`, `CcStmtRs`, `InvStmtRs`). - **ofx.securities** (list) - A list of security objects from the `SECLIST`. - **statement_object.banktranlist.transactions** (list) - A list of transaction objects for bank accounts. - **transaction_object.trnamt** (Decimal) - The transaction amount. - **transaction_object.dtposted** (datetime) - The posted date of the transaction. - **transaction_object.memo** (str) - The transaction description or memo. - **security_object.secid** (str) - The security identifier. - **security_object.secname** (str) - The name of the security. #### Response Example (See Request Example for data access patterns) ``` -------------------------------- ### Generating an OFX Bank Statement Response Source: https://github.com/csingley/ofxtools/blob/master/docs/generating.md This example demonstrates how to construct a complete OFX bank statement response by sequentially building the necessary model objects and then serializing them into an XML string with the appropriate OFX header. ```APIDOC ## Generating an OFX Bank Statement Response ### Description This example shows how to create a sample OFX bank statement response using the `ofxtools` library. It covers defining account information, balances, transaction details, and wrapping them in the necessary OFX message structures. ### Method N/A (This is a code generation example, not an API endpoint) ### Endpoint N/A ### Parameters N/A ### Request Body N/A ### Request Example ```python from ofxtools.models import * from ofxtools.utils import UTC from decimal import Decimal from datetime import datetime import xml.etree.ElementTree as ET from ofxtools.header import make_header # 1. Define Ledger Balance ledgerbal = LEDGERBAL(balamt=Decimal('150.65'), dtasof=datetime(2015, 1, 1, tzinfo=UTC)) # 2. Define Account Information acctfrom = BANKACCTFROM(bankid='123456789', acctid='23456', accttype='CHECKING') # 3. Define Statement Response Details stmtrs = STMTRS(curdef='USD', bankacctfrom=acctfrom, ledgerbal=ledgerbal) # 4. Define Status and Transaction Response status = STATUS(code=0, severity='INFO') stmttrnrs = STMTTRNRS(trnuid='5678', status=status, stmtrs=stmtrs) # 5. Define Bank Messages Response bankmsgsrs = BANKMSGSRSV1(stmttrnrs) # 6. Define Financial Institution and Signon Response fi = FI(org='Illuminati', fid='666') sonrs = SONRS(status=status, dtserver=datetime(2015, 1, 2, 17, tzinfo=UTC), language='ENG', fi=fi) signonmsgs = SIGNONMSGSRSV1(sonrs=sonrs) # 7. Assemble the complete OFX object ofx = OFX(signonmsgsrsv1=signonmsgs, bankmsgsrsv1=bankmsgsrs) # 8. Serialize to XML ElementTree root = ofx.to_etree() message = ET.tostring(root).decode() # 9. Create OFX Header header = str(make_header(version=220)) # 10. Combine header and message response = header + message print(response) ``` ### Response #### Success Response (200) N/A (This is a code generation example) #### Response Example ```xml 0INFO20150102170000ENGIlluminati66656780INFOUSD12345678923456CHECKING150.6520150101000000 ``` ``` -------------------------------- ### Persist Data using SQLAlchemy Source: https://github.com/csingley/ofxtools/blob/master/docs/sqlalchemy.md This snippet shows the basic steps to persist data using SQLAlchemy. It involves creating a database engine, setting up a session, adding objects (like accounts, securities, and trades) to the session, and finally committing the changes to the database. Ensure you have SQLAlchemy installed and a database connection string configured. ```python from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker # Assuming 'engine' and 'session' are already defined and connected engine = create_engine('') Session = sessionmaker(bind=engine) session = Session() # Add individual and multiple objects to the session session.add(account) session.add_all(securities.values()) session.add_all(trades) # Commit the transaction to the database session.commit() ``` -------------------------------- ### Scan OFX Server Configuration with ofxget Source: https://github.com/csingley/ofxtools/blob/master/docs/client.md Demonstrates how to use the 'ofxget scan' command to retrieve configuration details from financial institutions like BofA and Chase. The output includes information about supported OFX versions, formats, and specific flags like 'clientuidreq'. ```bash $ ofxget scan bofa [{"versions": [102], "formats": [{"pretty": false, "unclosedelements": true}, {"pretty": false, "unclosedelements": false}, {"pretty": true, "unclosedelements": true}, {"pretty": true, "unclosedelements": false}]}, {"versions": [], "formats": []}, {"chgpinfirst": false, "clientuidreq": true, "authtokenfirst": false, "mfachallengefirst": false}] $ ofxget scan chase [{"versions": [], "formats": []}, {"versions": [200, 201, 202, 203, 210, 211, 220], "formats": [{"pretty": false}, {"pretty": true}]}, {"chgpinfirst": false, "clientuidreq": true, "authtokenfirst": false, "mfachallengefirst": false}] ``` -------------------------------- ### Requesting an OFX Profile via CLI Source: https://github.com/csingley/ofxtools/blob/master/docs/client.md Demonstrates how to fetch an OFX profile from a server using direct URL/ORG/FID parameters, a known nickname, or an OFX Home database ID. This command verifies that the server is reachable and lists available services. ```bash $ ofxget prof --org AMEX --fid 3101 --url https://online.americanexpress.com/myca/ofxdl/desktop/desktopDownload.do\?request_type\=nl_ofxdownload $ ofxget prof amex $ ofxget prof --ofxhome 424 ``` -------------------------------- ### Requesting Financial Statements via CLI Source: https://github.com/csingley/ofxtools/blob/master/docs/client.md Demonstrates how to request credit card or bank statements using the ofxget CLI. It shows both manual parameter entry and the use of pre-configured profiles, as well as filtering by date range. ```bash export URL="https://online.americanexpress.com/myca/ofxdl/desktop/desktopDownload.do?request_type=nl_ofxdownload" ofxget stmt --url $URL --org AMEX --fid 3101 -u -c 888888888888888 -c 999999999999999 unset URL # Using a config profile ofxget stmt amex # Filtering by date range ofxget stmt amex --start 20140101 --end 20140630 > 2014-04_amex.ofx ``` -------------------------------- ### Manage OFX data downloads via CLI Source: https://github.com/csingley/ofxtools/blob/master/docs/client.md Common command-line operations for listing servers, configuring accounts, and downloading financial statements using ofxget. ```bash ofxget list ofxget stmt -u --all ofxget acctinfo -u --write ofxget stmt ``` -------------------------------- ### Download OFX Data with OFXClient Source: https://context7.com/csingley/ofxtools/llms.txt Demonstrates how to use the OFXClient class to connect to financial institutions and download statement data. It covers initialization with connection parameters, creating statement requests for different account types, and making the request. The response is a file-like object containing OFX markup. ```python import datetime from ofxtools import utils from ofxtools.Client import OFXClient, StmtRq, CcStmtRq, InvStmtRq # Initialize client with financial institution parameters client = OFXClient( url="https://ofx.chase.com", userid="your_username", org="B1", # Organization identifier fid="10898", # Financial institution ID version=220, # OFX protocol version prettyprint=True, # Format output with newlines bankid="111000614" # Bank routing number (for bank accounts) ) # Define date range for statement dtstart = datetime.datetime(2024, 1, 1, tzinfo=utils.UTC) dtend = datetime.datetime(2024, 1, 31, tzinfo=utils.UTC) # Create statement requests for different account types bank_stmt = StmtRq( acctid="123456789", accttype="CHECKING", # CHECKING, SAVINGS, MONEYMRKT, CREDITLINE, CD dtstart=dtstart, dtend=dtend, inctran=True # Include transactions ) cc_stmt = CcStmtRq( acctid="9876543210", dtstart=dtstart, dtend=dtend, inctran=True ) # Request statements (multiple accounts in one request) response = client.request_statements( "your_password", # Password as first positional arg bank_stmt, # Statement requests as remaining args cc_stmt, dryrun=False, # Set True to preview request without sending timeout=30.0 # HTTP timeout in seconds ) # Response is a file-like BytesIO object containing OFX markup print(response.read().decode()) ``` -------------------------------- ### Saving OFX Configuration via CLI Source: https://github.com/csingley/ofxtools/blob/master/docs/client.md Shows how to save connection parameters to the local configuration file automatically using the --write flag. This eliminates the need to re-enter credentials and URLs for subsequent requests. ```bash $ ofxget prof myfi --write --org AMEX --fid 3101 --url https://online.americanexpress.com/myca/ofxdl/desktop/desktopDownload.do\?request_type\=nl_ofxdownload $ ofxget prof myfi --ofxhome 424 --write ``` -------------------------------- ### Retrieve Account Information via CLI Source: https://github.com/csingley/ofxtools/blob/master/docs/client.md Uses the ofxget command to authenticate with a financial institution and list available accounts. The output provides the necessary account IDs for statement requests. ```bash $ ofxget acctinfo amex --user ``` -------------------------------- ### Requesting Profile Information with OFXClient Source: https://github.com/csingley/ofxtools/blob/master/docs/client.md Demonstrates how to request profile information from a financial institution using the OFXClient. This is achieved by calling the request_profile method on an initialized OFXClient instance. ```python response = client.request_profile() ``` -------------------------------- ### Generate OFX Data Source: https://context7.com/csingley/ofxtools/llms.txt Demonstrates how to construct an OFX document from scratch using the models module, including sign-on info, bank account details, transactions, and balances. ```python from ofxtools.models import ( OFX, SIGNONMSGSRSV1, SONRS, STATUS, FI, BANKMSGSRSV1, STMTTRNRS, STMTRS, BANKACCTFROM, BANKTRANLIST, STMTTRN, LEDGERBAL ) from ofxtools.header import make_header from ofxtools.utils import UTC from decimal import Decimal from datetime import datetime import xml.etree.ElementTree as ET status = STATUS(code=0, severity='INFO') fi = FI(org='MyBank', fid='12345') sonrs = SONRS( status=status, dtserver=datetime(2024, 1, 15, 12, 0, tzinfo=UTC), language='ENG', fi=fi ) signonmsgs = SIGNONMSGSRSV1(sonrs=sonrs) acctfrom = BANKACCTFROM( bankid='121000358', acctid='123456789', accttype='CHECKING' ) tx1 = STMTTRN( trntype='DEBIT', dtposted=datetime(2024, 1, 10, tzinfo=UTC), trnamt=Decimal('-50.00'), fitid='2024011001', name='Coffee Shop', memo='Morning coffee' ) tx2 = STMTTRN( trntype='CREDIT', dtposted=datetime(2024, 1, 12, tzinfo=UTC), trnamt=Decimal('1500.00'), fitid='2024011201', name='Direct Deposit', memo='Payroll' ) tranlist = BANKTRANLIST( tx1, tx2, dtstart=datetime(2024, 1, 1, tzinfo=UTC), dtend=datetime(2024, 1, 31, tzinfo=UTC) ) ledgerbal = LEDGERBAL( balamt=Decimal('2450.00'), dtasof=datetime(2024, 1, 15, 12, 0, tzinfo=UTC) ) stmtrs = STMTRS( curdef='USD', bankacctfrom=acctfrom, banktranlist=tranlist, ledgerbal=ledgerbal ) stmttrnrs = STMTTRNRS( trnuid='1001', status=status, stmtrs=stmtrs ) bankmsgs = BANKMSGSRSV1(stmttrnrs) ofx = OFX( signonmsgsrsv1=signonmsgs, bankmsgsrsv1=bankmsgs ) root = ofx.to_etree() body = ET.tostring(root, encoding='unicode') header = str(make_header(version=220)) complete_ofx = header + body print(complete_ofx) ``` -------------------------------- ### Constructing an OFX Bank Statement Response Source: https://github.com/csingley/ofxtools/blob/master/docs/generating.md Demonstrates how to instantiate OFX model objects such as LEDGERBAL, BANKACCTFROM, and STMTRS to build a valid bank statement response structure. ```python from ofxtools.models import * from ofxtools.utils import UTC from decimal import Decimal from datetime import datetime ledgerbal = LEDGERBAL(balamt=Decimal('150.65'), dtasof=datetime(2015, 1, 1, tzinfo=UTC)) acctfrom = BANKACCTFROM(bankid='123456789', acctid='23456', accttype='CHECKING') stmtrs = STMTRS(curdef='USD', bankacctfrom=acctfrom, ledgerbal=ledgerbal) ``` -------------------------------- ### List Available Accounts Source: https://context7.com/csingley/ofxtools/llms.txt Iterates through the signup message response to identify and print details for bank, credit card, and investment accounts. ```python acctinfors = ofx.signupmsgsrsv1[0].acctinfors for acctinfo in acctinfors: if hasattr(acctinfo, 'bankacctinfo'): info = acctinfo.bankacctinfo print(f"Bank: {info.bankacctfrom.bankid} / {info.bankacctfrom.acctid}") elif hasattr(acctinfo, 'ccacctinfo'): info = acctinfo.ccacctinfo print(f"Credit Card: {info.ccacctfrom.acctid}") elif hasattr(acctinfo, 'invacctinfo'): info = acctinfo.invacctinfo print(f"Investment: {info.invacctfrom.brokerid} / {info.invacctfrom.acctid}") ``` -------------------------------- ### Automate Configuration and Statement Retrieval Source: https://github.com/csingley/ofxtools/blob/master/docs/client.md Commands to automatically update the configuration file with account info or retrieve statements for all available accounts without manual configuration. ```bash $ ofxget acctinfo amex --user --write $ ofxget stmt amex --user --all ``` -------------------------------- ### Requesting Server Profile and Account Information Source: https://context7.com/csingley/ofxtools/llms.txt Shows how to query an OFX server for its profile capabilities without authentication and how to retrieve account listings using credentials. It includes parsing the response using OFXTree. ```python from ofxtools.Client import OFXClient from ofxtools.Parser import OFXTree import datetime from ofxtools.utils import UTC client = OFXClient(url="https://ofx.example.com/ofx", org="EXAMPLE", fid="12345", userid="your_username", version=203) profile_response = client.request_profile(dryrun=False, timeout=30.0) parser = OFXTree() parser.parse(profile_response) ofx = parser.convert() acctinfo_response = client.request_accounts(password="your_password", dtacctup=datetime.datetime(1990, 1, 1, tzinfo=UTC), dryrun=False) ``` -------------------------------- ### Requesting Account Information with OFXClient Source: https://github.com/csingley/ofxtools/blob/master/docs/client.md Shows how to retrieve account information using the OFXClient. The request_accounts method is called on an initialized OFXClient instance to fetch these details. ```python response = client.request_accounts() ``` -------------------------------- ### OFX Header Handling Source: https://context7.com/csingley/ofxtools/llms.txt Demonstrates how to create and parse OFX headers for both version 1 (SGML) and version 2 (XML) formats using the ofxtools.header module. ```APIDOC ## OFX Header Handling Create and parse OFX headers for both version 1 (SGML) and version 2 (XML) formats. ```python from ofxtools.header import make_header, parse_header, OFXHeaderV1, OFXHeaderV2 from io import BytesIO # Create OFX version 2 header (XML format) header_v2 = make_header(version=220) print(str(header_v2)) # Output: # # # Create OFX version 1 header (SGML format) header_v1 = make_header(version=160) print(str(header_v1)) # Output: # OFXHEADER:100 # DATA:OFXSGML # VERSION:160 # SECURITY:NONE # ENCODING:USASCII # CHARSET:NONE # COMPRESSION:NONE # OLDFILEUID:NONE # NEWFILEUID:NONE # Create header with file UIDs (for request/response tracking) header = make_header( version=220, security='NONE', oldfileuid='NONE', newfileuid='a1b2c3d4-e5f6-7890-abcd-ef1234567890' ) # Parse header from OFX file ofx_content = b'''OFXHEADER:100 DATA:OFXSGML VERSION:160 SECURITY:NONE ENCODING:USASCII CHARSET:1252 COMPRESSION:NONE OLDFILEUID:NONE NEWFILEUID:NONE ...''' source = BytesIO(ofx_content) header, message = parse_header(source) print(f"OFX Version: {header.version}") print(f"Encoding: {header.codec}") # Decoded charset for reading body print(f"Body starts with: {message[:20]}") ``` ``` -------------------------------- ### Manage OFX Headers Source: https://context7.com/csingley/ofxtools/llms.txt Shows how to create and parse OFX headers for both version 1 (SGML) and version 2 (XML) formats using ofxtools.header. ```python from ofxtools.header import make_header, parse_header, OFXHeaderV1, OFXHeaderV2 from io import BytesIO header_v2 = make_header(version=220) print(str(header_v2)) header_v1 = make_header(version=160) print(str(header_v1)) header = make_header(version=220, security='NONE', oldfileuid='NONE', newfileuid='a1b2c3d4-e5f6-7890-abcd-ef1234567890') ofx_content = b'''OFXHEADER:100\nDATA:OFXSGML\nVERSION:160\nSECURITY:NONE\nENCODING:USASCII\nCHARSET:1252\nCOMPRESSION:NONE\nOLDFILEUID:NONE\nNEWFILEUID:NONE\n\n...''' source = BytesIO(ofx_content) header, message = parse_header(source) print(f"OFX Version: {header.version}") ``` -------------------------------- ### List Available Accounts Source: https://context7.com/csingley/ofxtools/llms.txt This snippet demonstrates how to iterate through account information in an OFX object and print details for bank, credit card, and investment accounts. ```APIDOC ## List Available Accounts ### Description Iterates through account information within an OFX object and prints details for different account types (bank, credit card, investment). ### Method N/A (Python Script) ### Endpoint N/A ### Parameters N/A ### Request Example ```python # Assuming 'ofx' is a parsed OFX object # from ofxtools.Parser import OFXTree # parser = OFXTree() # ofx = parser.parse('your_ofx_file.ofx').convert() acctinfors = ofx.signupmsgsrsv1[0].acctinfors for acctinfo in acctinfors: if hasattr(acctinfo, 'bankacctinfo'): info = acctinfo.bankacctinfo print(f"Bank: {info.bankacctfrom.bankid} / {info.bankacctfrom.acctid}") elif hasattr(acctinfo, 'ccacctinfo'): info = acctinfo.ccacctinfo print(f"Credit Card: {info.ccacctfrom.acctid}") elif hasattr(acctinfo, 'invacctinfo'): info = acctinfo.invacctinfo print(f"Investment: {info.invacctfrom.brokerid} / {info.invacctfrom.acctid}") ``` ### Response N/A (Prints to console) ### Response Example ``` Bank: 123456789 / 987654321 Credit Card: 1122334455 Investment: BRKR123 / INV456 ``` ``` -------------------------------- ### Verifying Configuration Path with Python Source: https://github.com/csingley/ofxtools/blob/master/docs/client.md Provides a quick way to identify the exact file system path where ofxtools expects the configuration file to be located on the current operating system. ```python from ofxtools.scripts import ofxget print(ofxget.USERCONFIGPATH) ``` -------------------------------- ### Parse OFX Files with OFXTree Source: https://context7.com/csingley/ofxtools/llms.txt Illustrates how to use the OFXTree parser to deserialize OFX data from files into a Python ElementTree structure and then convert it to typed Python objects. It supports both OFXv1 (SGML) and OFXv2 (XML) formats automatically and shows how to access the raw structure, use ElementTree APIs, and retrieve OFX header information. ```python from ofxtools.Parser import OFXTree # Parse from file path or file object parser = OFXTree() parser.parse('statement.ofx') # From filename # Or from a file object (must be opened in binary mode) with open('statement.ofx', 'rb') as f: parser.parse(f) # Access the raw ElementTree structure root = parser._root # xml.etree.ElementTree.Element print(root.tag) # 'OFX' # Use ElementTree API including XPath status_elements = parser.find('.//STATUS') for elem in parser.findall('.//STMTTRN'): print(elem.find('TRNAMT').text) # Convert to typed Python objects ofx = parser.convert() # Access OFX header information print(parser.header.version) # e.g., 220 print(parser.header.security) # e.g., 'NONE' ``` -------------------------------- ### Requesting Tax 1099 Information with OFXClient Source: https://github.com/csingley/ofxtools/blob/master/docs/client.md Illustrates how to request Tax 1099 information using the OFXClient. This functionality is still under development (WIP) and is accessed via the request_tax1099 method. ```python response = client.request_tax1099() ``` -------------------------------- ### Parse OFX Data into ElementTree Source: https://github.com/csingley/ofxtools/blob/master/docs/parser.md Demonstrates how to use OFXTree to parse an OFX file into an ElementTree structure, allowing for manual manipulation or XPath queries. ```python from ofxtools.Parser import OFXTree parser = OFXTree() with open('2015-09_amtd.ofx', 'rb') as f: parser.parse(f) parser.parse('2015-09_amtd.ofx') # Accessing elements via XPath parser.find('.//STATUS')[:] ``` -------------------------------- ### Download Statements for Specific Accounts Source: https://github.com/csingley/ofxtools/blob/master/docs/client.md Requests activity statements for specific credit card accounts by passing the account IDs as arguments. Multiple accounts can be specified by repeating the flag. ```bash $ ofxget stmt amex --user --creditcard 888888888888888 --creditcard 999999999999999 ``` -------------------------------- ### Access Investment Statement Data Source: https://context7.com/csingley/ofxtools/llms.txt Demonstrates how to iterate through investment positions and access account balances from an OFX statement object. ```python for pos in inv_stmt.invposlist: seckey = (pos.uniqueidtype, pos.uniqueid) security = securities.get(seckey) print(f"Position: {security.ticker if security else pos.uniqueid}") print(f" Units: {pos.units}") print(f" Price: {pos.unitprice}") print(f" Market Value: {pos.mktval}") print(f" As of: {pos.dtpriceasof}") if inv_stmt.invbal: print(f"Available Cash: {inv_stmt.invbal.availcash}") print(f"Margin Balance: {inv_stmt.invbal.marginbalance}") print(f"Short Balance: {inv_stmt.invbal.shortbalance}") ``` -------------------------------- ### Accessing OFX Statement Data Source: https://context7.com/csingley/ofxtools/llms.txt Demonstrates how to iterate through bank and investment statements, access transaction lists, and retrieve account balances. It highlights the use of proxy access to simplify deep navigation within investment statement hierarchies. ```python for stmt in statements: account = stmt.account print(f"Account: {account.acctid}") for tx in stmt.transactions: print(f" {tx.dtposted}: {tx.trnamt} - {tx.memo}") balance = stmt.balance if hasattr(stmt, 'balances'): print(f"Cash: {stmt.balances.availcash}") inv_stmt = ofx.invstmtmsgsrsv1[0].invstmtrs for tx in inv_stmt.invtranlist: print(f"Trade: {tx.dttrade}") print(f"CUSIP: {tx.uniqueid}") print(f"Type: {tx.uniqueidtype}") print(f"Units: {tx.units}") print(f"Total: {tx.total}") ``` -------------------------------- ### Scanning for OFX Connection Formats Source: https://github.com/csingley/ofxtools/blob/master/docs/client.md Uses the ofxget scan command to identify the correct OFX version and formatting settings for a financial institution. This helps resolve connection issues by testing various protocol configurations. ```bash ofxget scan https://ofx.etrade.com/cgi-ofx/etradeofx ofxget scan usaa ofxget scan vanguard # Automatically write discovered config to file ofxget scan myfi --write --url https://ofx.mybank.com/download ``` -------------------------------- ### Requesting Statements with OFXClient Source: https://github.com/csingley/ofxtools/blob/master/docs/client.md Initializes an OFXClient instance with connection details and then uses it to request financial statements. The request_statements method takes a password and various statement request objects as arguments. Dependencies include the datetime module and ofxtools.Client. ```python import datetime import ofxtools from ofxtools.Client import OFXClient, StmtRq, CcStmtEndRq client = OFXClient("https://ofx.chase.com", userid="MoMoney", org="B1", fid="10898", version=220, prettyprint=True, bankid="111000614") dtstart = datetime.datetime(2015, 1, 1, tzinfo=ofxtools.utils.UTC) dtend = datetime.datetime(2015, 1, 31, tzinfo=ofxtools.utils.UTC) s0 = StmtRq(acctid="1", accttype="CHECKING", dtstart=dtstart, dtend=dtend) s1 = StmtRq(acctid="2", accttype="SAVINGS", dtstart=dtstart, dtend=dtend) c0 = CcStmtEndRq(acctid="3", dtstart=dtstart, dtend=dtend) response = client.request_statements("t0ps3kr1t", s0, s1, c0) ``` -------------------------------- ### Extending OFX Banking Message Set for Funds Transfer (Python) Source: https://github.com/csingley/ofxtools/blob/master/docs/contributing.md Demonstrates how to extend the OFX banking message set (BANKMSGSRQV1, BANKMSGSRSV1) to include funds transfer functionality. This involves adding ListAggregate definitions for transfer requests and responses, and defining a new XFERPROF aggregate for transfer profiles. ```python class BANKMSGSRQV1(List): """ OFX section 11.13.1.1.1 """ ... intratrnrq = ListAggregate(INTRATRNRQ) recintratrnrq = ListAggregate(RECINTRATRNRQ) intrasyncrq = ListAggregate(INTRASYNCRQ) recintrasyncrq = ListAggregate(RECINTRASYNCRQ) ... class BANKMSGSRSV1(List): """ OFX section 11.13.1.1.2 """ ... intratrnrs = ListAggregate(INTRATRNRS) recintratrnrs = ListAggregate(RECINTRATRNRS) intrasyncrs = ListAggregate(INTRASYNCRS) recintrasyncrs = ListAggregate(RECINTRASYNCRS) ... class XFERPROF(ElementList): """ OFX section 11.13.2.2 """ procdaysoff = ListElement(OneOf(*DAYS)) procendtm = Time(required=True) cansched = Bool(required=True) canrecur = Bool(required=True) canmodxfer = Bool(required=True) canmodmdls = Bool(required=True) modelwnd = Integer(3, required=True) dayswith = Integer(3, required=True) dfltdaystopay = Integer(3, required=True) class BANKMSGSETV1(Aggregate): """ OFX section 11.13.2.1 """ ... xferprof = SubAggregate(XFERPROF) ... ``` -------------------------------- ### SQLAlchemy Integration Pattern Source: https://context7.com/csingley/ofxtools/llms.txt Illustrates a recommended pattern for persisting OFX data to a database using SQLAlchemy, although ofxtools does not provide direct ORM integration. ```APIDOC ## SQLAlchemy Integration Pattern While ofxtools doesn't include direct ORM integration, here's the recommended pattern for persisting OFX data to a database. ```python from sqlalchemy import create_engine, Column, Integer, String, DateTime, Numeric from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from ofxtools.Parser import OFXTree from ofxtools.models.invest.transactions import BUYSTOCK, SELLSTOCK Base = declarative_base() ``` ``` -------------------------------- ### Generating OFX Data Source: https://context7.com/csingley/ofxtools/llms.txt This snippet shows how to programmatically create OFX documents using the ofxtools models module, useful for building OFX servers or generating test data. ```APIDOC ## Generating OFX Data ### Description Programmatically create OFX documents using the `ofxtools.models` module. This is useful for building OFX servers or generating test data. ### Method N/A (Python Script) ### Endpoint N/A ### Parameters N/A ### Request Example ```python from ofxtools.models import ( OFX, SIGNONMSGSRSV1, SONRS, STATUS, FI, BANKMSGSRSV1, STMTTRNRS, STMTRS, BANKACCTFROM, BANKTRANLIST, STMTTRN, LEDGERBAL ) from ofxtools.header import make_header from ofxtools.utils import UTC from decimal import Decimal from datetime import datetime import xml.etree.ElementTree as ET # Create signon response status = STATUS(code=0, severity='INFO') fi = FI(org='MyBank', fid='12345') sonrs = SONRS( status=status, dtserver=datetime(2024, 1, 15, 12, 0, tzinfo=UTC), language='ENG', fi=fi ) signonmsgs = SIGNONMSGSRSV1(sonrs=sonrs) # Create account identifier acctfrom = BANKACCTFROM( bankid='121000358', # Routing number acctid='123456789', accttype='CHECKING' ) # Create transactions tx1 = STMTTRN( trntype='DEBIT', dtposted=datetime(2024, 1, 10, tzinfo=UTC), trnamt=Decimal('-50.00'), fitid='2024011001', # Unique transaction ID name='Coffee Shop', memo='Morning coffee' ) tx2 = STMTTRN( trntype='CREDIT', dtposted=datetime(2024, 1, 12, tzinfo=UTC), trnamt=Decimal('1500.00'), fitid='2024011201', name='Direct Deposit', memo='Payroll' ) # Create transaction list tranlist = BANKTRANLIST( tx1, tx2, # Transactions as positional args dtstart=datetime(2024, 1, 1, tzinfo=UTC), dtend=datetime(2024, 1, 31, tzinfo=UTC) ) # Create balance ledgerbal = LEDGERBAL( balamt=Decimal('2450.00'), dtasof=datetime(2024, 1, 15, 12, 0, tzinfo=UTC) ) # Assemble statement response stmtrs = STMTRS( curdef='USD', bankacctfrom=acctfrom, banktranlist=tranlist, ledgerbal=ledgerbal ) # Wrap in transaction response stmttrnrs = STMTTRNRS( trnuid='1001', # Transaction UID status=status, stmtrs=stmtrs ) # Create message set bankmsgs = BANKMSGSRSV1(stmttrnrs) # Create complete OFX document ofx = OFX( signonmsgsrsv1=signonmsgs, bankmsgsrsv1=bankmsgs ) # Serialize to XML root = ofx.to_etree() body = ET.tostring(root, encoding='unicode') # Add OFX header (version 220 = OFX 2.2.0) header = str(make_header(version=220)) complete_ofx = header + body print(complete_ofx) ``` ### Response N/A (Prints the generated OFX XML to console) ### Response Example ```xml OFXHEADER:100 DATA:OFXSGML VERSION:220 SECURITY:NONE ENCODING:USASCII CHARSET:1252 COMPRESSION:NONE OLDFILEUID:NONE NEWFILEUID:NONE 0 INFO 20240115120000 ENG MyBank 12345 1001 0 INFO USD 121000358 123456789 CHECKING 20240101000000 20240131235959 DEBIT 20240110000000 -50.00 2024011001 Coffee Shop Morning coffee CREDIT 20240112000000 1500.00 2024011201 Direct Deposit Payroll 2450.00 20240115120000 ``` ```