A comprehensive, headless Python accounting application that implements double-entry bookkeeping with CLI, REST API, and MCP (Model Context Protocol) interfaces. Now with full GAAP compliance!
- Multi-Entity Support: Manage multiple companies/organizations with isolated data
- Double-Entry Accounting: Full implementation of double-entry bookkeeping principles
- Enhanced Account Management: Opening balances, opening dates, and comprehensive account structure
- Comprehensive Transaction Types: Cash sales, cash purchases, opening balances, and standard journal entries
- Advanced Journal Entries: Narration, quantity tracking, unit prices, and tax rate support
- Tax Handling: Automatic tax calculations with dedicated tax payable/receivable accounts
- Invoice Management: Complete invoice system with customer management, line items, and payment tracking
- Purchase Order Management: Full purchase order system with supplier management, receipt tracking, and status management
- Payment Clearing: Advanced payment clearing with aging schedules and reconciliation
- Financial Reports: Balance Sheet, Income Statement, and Cash Flow reporting
- Revenue Recognition (ASC 606): Point-in-time and over-time recognition methods
- Expense Matching: Links expenses to related revenues with matching ratios
- Materiality: Automatic assessment with customizable thresholds (default: 5% of total assets)
- Consistency: Method consistency tracking with change justification
- Conservatism: Understate assets, overstate liabilities for prudent reporting
- Going Concern: Assets vs. liabilities validation for financial viability
- Audit Trails: Complete transaction history with principle-based categorization
- Multiple Interfaces: CLI, REST API, and MCP server for AI assistant integration
- Database Persistence: SQLite database with automatic balance updates
- Professional Testing: Comprehensive test suite validating accounting principles
- PDF Generation: Professional invoice PDF generation with modern design
- Modern Python: Leverages Python 3.12+ features for better performance and type safety
- Python 3.12+ (required for modern type hints and features)
- pip
Note: This project requires Python 3.12 or higher to take advantage of modern Python features, improved type hints, and better performance. The CI/CD pipeline tests against Python 3.12 and 3.13.
# Clone the repository
git clone git@github.com:dickhfchan/pyledger.git
cd pyledger
# Create virtual environment
python3 -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -e .# Initialize database
python3 -m pyledger.main db-init
# Add your first entity
python3 -m pyledger.main db-add-entity# Add accounts with opening balances
python3 -m pyledger.main db-add-account# Create a cash sale
python3 -m pyledger.main db-cash-sale
# Or create a journal entry
python3 -m pyledger.main db-add-entry# Run accounting tests to verify everything works
python3 -m pyledger.accounting_tests
# Test GAAP compliance
python3 -m pyledger.gaap_compliance_tests# Start the REST API server
uvicorn pyledger.api:app --reload --host 0.0.0.0 --port 8000# Initialize database
python3 -m pyledger.main db-init
# Add entities
python3 -m pyledger.main db-add-entity
# List entities
python3 -m pyledger.main db-list-entities
# Add accounts with opening balances
python3 -m pyledger.main db-add-account
# List accounts
python3 -m pyledger.main db-list-accounts# Add journal entries
python3 -m pyledger.main db-add-entry
# List journal entries
python3 -m pyledger.main db-list-entries
# View entry details
python3 -m pyledger.main db-entry-lines <entry_id>
# Create cash sale transaction
python3 -m pyledger.main db-cash-sale
# Create cash purchase transaction
python3 -m pyledger.main db-cash-purchase
# Create opening balance transaction
python3 -m pyledger.main db-opening-balance# Add invoice
python3 -m pyledger.main db-add-invoice
# List invoices
python3 -m pyledger.main db-list-invoices
# Get invoice details
python3 -m pyledger.main db-get-invoice
# Record invoice payment
python3 -m pyledger.main db-record-invoice-payment
# Generate PDF invoice
python3 -m pyledger.main db-generate-invoice-pdf# Add purchase order
python3 -m pyledger.main db-add-po
# List purchase orders
python3 -m pyledger.main db-list-pos
# Get purchase order details
python3 -m pyledger.main db-get-po
# Record purchase order receipt
python3 -m pyledger.main db-record-po-receipt# Run accounting tests
python3 -m pyledger.accounting_tests
# Run GAAP compliance tests
python3 -m pyledger.gaap_compliance_testsStart the API server:
uvicorn pyledger.api:app --reload --host 0.0.0.0 --port 8000Entities
GET /entities- List all entitiesPOST /entities- Create new entityGET /entities/{id}- Get entity details
Accounts
GET /accounts- List all accountsPOST /accounts- Create new account with opening balanceGET /accounts/{code}- Get account detailsGET /accounts/{code}/balance- Get account balance history
Journal Entries
GET /journal_entries- List all journal entriesPOST /journal_entries- Create new journal entryGET /journal_entries/{id}- Get journal entry detailsGET /journal_entries/{id}/lines- Get journal entry lines
Transaction Types
POST /transactions/cash-sale- Create cash sale transactionPOST /transactions/cash-purchase- Create cash purchase transactionPOST /transactions/opening-balance- Create opening balance transaction
Invoices
GET /invoices- List all invoicesPOST /invoices- Create new invoiceGET /invoices/{invoice_number}- Get invoice detailsGET /invoices/{invoice_number}/lines- Get invoice line itemsPOST /invoices/{invoice_number}/payment- Record invoice paymentGET /invoices/{invoice_number}/pdf- Generate PDF invoice
Purchase Orders
GET /purchase_orders- List all purchase ordersPOST /purchase_orders- Create new purchase orderGET /purchase_orders/{po_number}- Get purchase order detailsGET /purchase_orders/{po_number}/lines- Get purchase order line itemsPOST /purchase_orders/{po_number}/receipt- Record purchase order receipt
Reports
GET /reports/balance_sheet- Generate balance sheetGET /reports/income_statement- Generate income statementGET /reports/cash_flow- Generate cash flow report
Revenue Recognition
POST /gaap/revenue_recognition- Validate revenue recognition per ASC 606PUT /gaap/revenue_recognition/{invoice_number}- Update revenue recognition
Expense Matching
POST /gaap/expense_matching- Validate expense matching principle
Materiality & Conservatism
POST /gaap/materiality_assessment- Assess materiality of transactionsPOST /gaap/conservatism- Apply conservatism principle
Compliance Reporting
GET /gaap/going_concern- Validate going concern assumptionGET /gaap/compliance_report- Generate GAAP compliance reportGET /gaap/audit_trail- Get audit trail entries
# Create an entity
curl -X POST "http://localhost:8000/entities" \
-H "Content-Type: application/json" \
-d '{"name": "Acme Corporation", "code": "ACME", "description": "Test company"}'
# Create an account with opening balance
curl -X POST "http://localhost:8000/accounts" \
-H "Content-Type: application/json" \
-d '{
"code": "1000",
"name": "Cash",
"type": "ASSET",
"balance": 0.0,
"opening_balance": 10000.0,
"opening_date": "2024-01-01"
}'
# Create a journal entry with enhanced features
curl -X POST "http://localhost:8000/journal_entries" \
-H "Content-Type: application/json" \
-d '{
"description": "Owner investment",
"entry_date": "2024-01-01",
"transaction_type": "journal_entry",
"reference": "INV-001",
"lines": [
{
"account_code": "1000",
"amount": 1000.0,
"is_debit": true,
"narration": "Owner investment",
"quantity": 1.0,
"unit_price": 1000.0,
"tax_rate": 0.0
},
{
"account_code": "3000",
"amount": 1000.0,
"is_debit": false,
"narration": "Owner equity",
"quantity": 1.0,
"unit_price": 1000.0,
"tax_rate": 0.0
}
]
}'
# GAAP Compliance - Revenue Recognition
curl -X POST "http://localhost:8000/gaap/revenue_recognition" \
-H "Content-Type: application/json" \
-d '{
"invoice_number": "INV-2024-001",
"recognition_method": "point_in_time",
"performance_obligations": ["Delivery of goods"],
"start_date": "2024-01-15",
"end_date": "2024-01-15"
}'
# GAAP Compliance - Materiality Assessment
curl -X POST "http://localhost:8000/gaap/materiality_assessment" \
-H "Content-Type: application/json" \
-d '{
"assessment_type": "journal_entry",
"actual_amount": 5000.0
}'
# Get GAAP compliance report
curl "http://localhost:8000/gaap/compliance_report"The MCP (Model Context Protocol) server allows AI assistants to interact with the accounting system.
Start the MCP server:
python3 -m pyledger.mcp_serverEntities & Accounts
list_entities- List all entitiesadd_entity- Create new entitylist_accounts- List all accountsadd_account- Create new account with opening balanceget_account_balance- Get account balance history
Journal Entries & Transactions
add_journal_entry- Create journal entry with enhanced featureslist_journal_entries- List all journal entriesget_journal_lines- Get journal entry detailscreate_cash_sale- Create cash sale transactioncreate_cash_purchase- Create cash purchase transactioncreate_opening_balance- Create opening balance transaction
Invoices
add_invoice- Create new invoicelist_invoices- List all invoicesget_invoice- Get invoice detailsrecord_invoice_payment- Record invoice paymentgenerate_invoice_pdf- Generate PDF invoice in A4 format
Purchase Orders
add_purchase_order- Create new purchase orderlist_purchase_orders- List all purchase ordersget_purchase_order- Get purchase order detailsrecord_purchase_order_receipt- Record purchase order receipt
Reports
balance_sheet- Generate balance sheetincome_statement- Generate income statementcash_flow_report- Generate cash flow report
pyledger/
βββ accounts.py # Account and Chart of Accounts classes
βββ journal.py # Journal entries and ledger
βββ transaction_types.py # Transaction type management (cash sales, purchases, etc.)
βββ invoices.py # Invoice management system
βββ purchase_orders.py # Purchase order management system
βββ payment_clearing.py # Payment clearing and aging schedules
βββ reports.py # Financial reporting functions
βββ db.py # Database operations
βββ api.py # FastAPI REST API
βββ mcp_server.py # MCP server implementation
βββ main.py # CLI interface
βββ gaap_compliance.py # GAAP compliance module β NEW
βββ gaap_compliance_tests.py # GAAP compliance test suite β NEW
βββ accounting_tests.py # Professional accounting test suite
βββ test_db.py # Database function tests
βββ test_mcp.py # MCP server tests
βββ test_pyledger.py # Core functionality tests
βββ test_enhanced_features.py # Enhanced features test suite
The system implements standard double-entry accounting:
- Accounting Equation: Assets = Liabilities + Equity
- Double-Entry: Every transaction affects at least two accounts
- Balance Validation: All journal entries must balance (debits = credits)
- Account Types: Assets, Liabilities, Equity, Revenue, Expense
- Closing Entries: Proper period-end closing procedures
PyLedger includes comprehensive GAAP (Generally Accepted Accounting Principles) compliance features:
- Revenue Recognition (ASC 606): Point-in-time and over-time recognition methods
- Expense Matching: Links expenses to related revenues with matching ratios
- Materiality: Automatic assessment with customizable thresholds (default: 5% of total assets)
- Consistency: Method consistency tracking with change justification
- Conservatism: Understate assets, overstate liabilities for prudent reporting
- Going Concern: Assets vs. liabilities validation for financial viability
- Audit Trails: Complete transaction history with principle-based categorization
- Automated Validation: All transactions validated against GAAP principles
- Real-Time Monitoring: Continuous compliance checking
- Comprehensive Audit Trails: Complete transaction history with before/after values
- Compliance Reporting: Detailed GAAP compliance reports
- API Integration: Full REST API support for GAAP compliance operations
# Run GAAP compliance tests
python3 -m pyledger.gaap_compliance_testsThe GAAP compliance test suite validates:
- Revenue recognition per ASC 606
- Expense matching principle
- Materiality assessment
- Consistency checks
- Conservatism principle
- Going concern assumption
- Audit trail functionality
- Compliance report generation
For detailed GAAP compliance documentation, see GAAP_COMPLIANCE_DOCUMENTATION.md.
Run the comprehensive test suite:
# Run all accounting tests
python3 -m pyledger.accounting_tests
# Run GAAP compliance tests
python3 -m pyledger.gaap_compliance_tests
# Run enhanced features tests
python3 test_enhanced_features.py
# Run specific test modules
python3 -m pyledger.test_db
python3 -m pyledger.test_mcp
python3 -m pyledger.test_pyledgerThe test suite validates:
- Multi-entity support with data isolation
- Enhanced account management with opening balances
- Comprehensive transaction types (cash sales, purchases, opening balances)
- Advanced journal entries with narration, quantities, and tax rates
- Tax handling with automatic calculations
- GAAP compliance with all major principles
- Accounting equation compliance
- Double-entry validation
- Revenue/expense tracking
- Balance sheet accuracy
- Income statement accuracy
- Real-world business scenarios
The SQLite database includes:
entitiestable: Multi-entity support with company/organization dataaccountstable: Account information with opening balances and datesjournal_entriestable: Journal entry metadata with transaction typesjournal_linestable: Individual debit/credit lines with narration, quantities, and tax ratesinvoicestable: Invoice management with customer datainvoice_linestable: Invoice line items with quantities and pricespurchase_orderstable: Purchase order management with supplier datapurchase_order_linestable: Purchase order line items with quantities and prices
gaap_audit_trailtable: Complete audit trail with principle-based categorizationrevenue_recognitiontable: Revenue recognition tracking per ASC 606expense_matchingtable: Expense matching with ratios and periodsmateriality_assessmentstable: Materiality assessments with thresholdsconsistency_checkstable: Method consistency tracking and changes
- Create feature branch:
git checkout -b feature/new-feature - Implement changes
- Add tests
- Run test suite:
python3 -m pyledger.accounting_tests - Commit and push:
git commit -m "Add new feature" && git push
- Professional Standards: Full GAAP compliance for professional accounting
- Audit Readiness: Complete audit trails and compliance reporting
- Risk Mitigation: Materiality assessment and conservatism principles
- Automated Validation: Real-time GAAP compliance checking
- Comprehensive Reporting: Detailed GAAP compliance reports
- Multi-Interface Support: CLI, REST API, and MCP server
- Modern Python: Leverages Python 3.12+ features
- Open Source: MIT license with full code access
This project is licensed under the MIT License.
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
For issues and questions, please open an issue on GitHub.
For detailed comparisons between PyLedger and other accounting systems:
- PyLedger vs Odoo: See ODOO_COMPARISON.md
- PyLedger vs Python-Accounting: See PYTHON_ACCOUNTING_COMPARISON.md
- Small to Medium Businesses: Cost-effective accounting solution
- Developers: API-first approach with programmatic access
- AI Integration: Built-in MCP server for AI assistant interaction
- Multi-Entity Operations: Managing multiple companies/organizations
- Professional Accounting: Full GAAP compliance for audit readiness
- Automation Projects: Integrating accounting with other business processes
- Headless Applications: Building applications without web interfaces
- Modern Architecture: API-first design with CLI and MCP interfaces
- GAAP Compliant: Professional accounting standards
- Multi-Entity Support: Full support for multiple companies/organizations
- Enhanced Features: Opening balances, advanced journal entries, tax handling
- AI Integration: Built-in MCP server for AI assistant interaction
- Lightweight: Simple SQLite database, easy deployment
- Open Source: MIT license with full code access
from pyledger.gaap_compliance import GAAPCompliance, RevenueRecognitionMethod
# Initialize GAAP compliance
gaap = GAAPCompliance(conn)
# Revenue recognition
gaap.validate_revenue_recognition(
invoice_number='INV-2024-001',
recognition_method=RevenueRecognitionMethod.POINT_IN_TIME,
performance_obligations=["Delivery of goods"]
)
# Materiality assessment
assessment = gaap.assess_materiality(
assessment_type="journal_entry",
actual_amount=5000.0
)
# Conservatism principle
gaap.apply_conservatism(
account_code='1100',
adjustment_amount=1000.0,
reason="Conservative estimate for doubtful accounts"
)
# Generate compliance report
report = gaap.get_gaap_compliance_report()# Run comprehensive GAAP compliance tests
python3 -m pyledger.gaap_compliance_tests
# Expected output:
# π§ͺ Running GAAP Compliance Test Suite
# β
All GAAP compliance tests passed!
# π GAAP Compliance Test Results:
# β
Passed: 10
# β Failed: 0
# π Success Rate: 100.0%PyLedger - Professional accounting with full GAAP compliance, modern Python, and comprehensive testing. Perfect for developers, small businesses, and professional accounting practices! π