### Install Python Accounting Source: https://github.com/ekmungai/python-accounting/blob/main/README.md Install the library using pip. Requires Python 3.9+. ```bash pip install python-accounting ``` -------------------------------- ### Tax Inclusive Calculation Example Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/_sources/examples.md.txt Demonstrates how to calculate amounts with tax included. Ensure the tax rate is correctly configured before use. ```python from accounting import Tax tax = Tax(rate=0.20) # Calculate price inclusive of tax price_inclusive_tax = tax.calculate_inclusive_price(100.00) print(f"Price inclusive of tax: {price_inclusive_tax:.2f}") # Calculate tax amount from a price inclusive of tax tax_amount = tax.calculate_tax_from_inclusive_price(120.00) print(f"Tax amount from inclusive price: {tax_amount:.2f}") # Calculate price exclusive of tax from a price inclusive of tax price_exclusive_tax = tax.calculate_exclusive_price_from_inclusive_price(120.00) print(f"Price exclusive of tax from inclusive price: {price_exclusive_tax:.2f}") ``` -------------------------------- ### Configure Database and Create Tables Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/index.html Configure the database connection URL and create necessary tables using SQLAlchemy. This setup is required before using the library's models. ```python from python_accounting import config from python_accounting.models import Base from sqlalchemy import create_engine database = config.database engine = create_engine(database["url"]) Base.metadata.create_all(engine) # run migrations to create tables ``` -------------------------------- ### Setup Chart of Accounts Source: https://github.com/ekmungai/python-accounting/blob/main/docs/index.md Defines and adds various account types (Control, Bank, Revenue, Receivable, Payable, Expense, Asset) for a given entity and currency. ```python from python_accounting.models import Account tax_account = Account( name="Tax Account", account_type=Account.AccountType.CONTROL, currency_id=currency.id, entity_id=entity.id, ) bank_account = Account( name="Bank Account", account_type=Account.AccountType.BANK, currency_id=currency.id, entity_id=entity.id, ) revenue_account = Account( name="Revenue Account", account_type=Account.AccountType.OPERATING_REVENUE, currency_id=currency.id, entity_id=entity.id, ) client_account = Account( name="Client Account", account_type=Account.AccountType.RECEIVABLE, currency_id=currency.id, entity_id=entity.id, ) supplier_account = Account( name="Supplier Account", account_type=Account.AccountType.PAYABLE, currency_id=currency.id, entity_id=entity.id, ) opex_account = Account( name="Opex Account", account_type=Account.AccountType.OPERATING_EXPENSE, currency_id=currency.id, entity_id=entity.id, ) expense_account = Account( name="Expense Account", account_type=Account.AccountType.DIRECT_EXPENSE, currency_id=currency.id, entity_id=entity.id, ) asset_account = Account( name="Asset Account", account_type=Account.AccountType.NON_CURRENT_ASSET, currency_id=currency.id, entity_id=entity.id, ) session.add_all([ tax_account, bank_account, revenue_account, client_account, supplier_account, opex_account, expense_account, asset_account ]) session.commit() ``` -------------------------------- ### Setup Chart of Accounts Source: https://github.com/ekmungai/python-accounting/blob/main/README.md Defines and adds various account types (Control, Bank, Revenue, Receivable, Payable, Expense, Asset) for the entity. ```python from python_accounting.models import Account tax_account = Account( name="Tax Account", account_type=Account.AccountType.CONTROL, currency_id=currency.id, entity_id=entity.id, ) bank_account = Account( name="Bank Account", account_type=Account.AccountType.BANK, currency_id=currency.id, entity_id=entity.id, ) revenue_account = Account( name="Revenue Account", account_type=Account.AccountType.OPERATING_REVENUE, currency_id=currency.id, entity_id=entity.id, ) client_account = Account( name="Client Account", account_type=Account.AccountType.RECEIVABLE, currency_id=currency.id, entity_id=entity.id, ) supplier_account = Account( name="Supplier Account", account_type=Account.AccountType.PAYABLE, currency_id=currency.id, entity_id=entity.id, ) ope x_account = Account( name="Opex Account", account_type=Account.AccountType.OPERATING_EXPENSE, currency_id=currency.id, entity_id=entity.id, ) expense_account = Account( name="Expense Account", account_type=Account.AccountType.DIRECT_EXPENSE, currency_id=currency.id, entity_id=entity.id, ) asset_account = Account( name="Asset Account", account_type=Account.AccountType.NON_CURRENT_ASSET, currency_id=currency.id, entity_id=entity.id, ) session.add_all([ tax_account, bank_account, revenue_account, client_account, supplier_account, opex_account, expense_account, asset_account ]) session.commit() ``` -------------------------------- ### get() Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/genindex.html Retrieves an object from the database session. ```APIDOC ## get() ### Description Retrieves an object from the database session. ### Method (Method signature not provided in source) ### Endpoint (Endpoint not applicable for this method) ### Parameters (Parameters not specified in source) ### Request Example (Request example not provided in source) ### Response (Response details not provided in source) ``` -------------------------------- ### Create and Post a Cash Purchase Source: https://context7.com/ekmungai/python-accounting/llms.txt Use `CashPurchase` for immediate expenses paid from a bank account. The main account must be `BANK`, and line items should use purchasable account types. This example demonstrates creating a purchase, adding expense line items, and posting. ```python from python_accounting.transactions import CashPurchase with get_session(engine) as session: purchase = CashPurchase( narration="Office supplies", transaction_date=datetime(2024, 6, 5), account_id=bank.id, entity_id=entity.id, ) session.add(purchase) session.flush() opex = Account(name="Office Supplies", account_type=Account.AccountType.OPERATING_EXPENSE, currency_id=currency.id, entity_id=entity.id) session.add(opex) session.commit() line = LineItem(narration="Paper and pens", account_id=opex.id, amount=50, quantity=2, entity_id=entity.id) session.add(line) session.flush() purchase.line_items.add(line) session.add(purchase) purchase.post(session) print(purchase.transaction_no) # CP01/0001 print(purchase.amount) # Decimal('100.0000') ``` -------------------------------- ### Create and Post a Supplier Payment Source: https://context7.com/ekmungai/python-accounting/llms.txt Use `SupplierPayment` to record payments made to suppliers. The main account must be `PAYABLE`. This example shows creating a payment, adding a bank line item, and posting it. ```python from python_accounting.transactions import SupplierPayment with get_session(engine) as session: payment = SupplierPayment( narration="Payment to supplier", transaction_date=datetime(2024, 7, 15), account_id=payable.id, entity_id=entity.id, ) session.add(payment) session.flush() line = LineItem(narration="Bank payment", account_id=bank.id, amount=5000, entity_id=entity.id) session.add(line) session.flush() payment.line_items.add(line) session.add(payment) payment.post(session) ``` -------------------------------- ### Create Accounts for Transactions Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/_sources/tax_inclusive.md.txt Sets up the necessary accounts (Tax, Bank, Revenue) required for posting financial transactions. Ensure these accounts are created before proceeding with transaction setup. ```python from python_accounting.models import Account with get_session(engine) as session: tax_account = Account( name="Tax Account", account_type=Account.AccountType.CONTROL, currency_id=currency.id, entity_id=entity.id, ) bank_account = Account( name="Bank Account", account_type=Account.AccountType.BANK, currency_id=currency.id, entity_id=entity.id, ) revenue_account = Account( name="Revenue Account", account_type=Account.AccountType.OPERATING_REVENUE, currency_id=currency.id, entity_id=entity.id, ) session.add_all([ tax_account, bank_account, revenue_account, ]) session.commit() ``` -------------------------------- ### Compound Transaction Example Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/_sources/examples.md.txt Illustrates how to create and manage compound transactions, which involve multiple accounts or effects. This is useful for complex financial entries. ```python from accounting import Transaction, Account, Currency # Create accounts assets = Account('Assets') liabilities = Account('Liabilities') equity = Account('Equity') revenue = Account('Revenue') expenses = Account('Expenses') # Create a transaction transaction = Transaction( description="Sale of goods", currency=Currency.USD, debits=[ (assets, 1000.00), (expenses, 200.00) ], credits=[ (revenue, 1200.00) ] ) print(transaction) print(f"Total debits: {transaction.total_debits}") print(f"Total credits: {transaction.total_credits}") # Verify if the transaction is balanced print(f"Is balanced: {transaction.is_balanced}") ``` -------------------------------- ### Generate and Print Cashflow Statement Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/_sources/cashflow_statement.md.txt Instantiate the CashflowStatement object and print its formatted output. This example demonstrates how to generate a cashflow statement for a given accounting session. ```python cashflow_statememt = BalanceSheet(session) print(cashflow_statememt) Test Entity Cashflow Statement For the period: 01, Jan 2024 to 23, Feb 2024 Operating Cash Flow Net Profit 100.0000 Receivables -70.0000 Payables 120.0000 Taxation 20.0000 _______________ Total Operating Cash Flow 170.0000 Investment Cash Flow Non Current Assets -120.0000 _______________ Total Investment Cash Flow -120.0000 Financing Cash Flow Equity 0.0000 _______________ Total Financing Cash Flow 0.0000 Net Cash Flow Beginning Cash Balance 0.0000 Net Cash Flow 50.0000 _______________ Ending Cash Balance 50.0000 =============== _______________ Cashbook Balance 50.0000 =============== ``` -------------------------------- ### Configure Database and Run Migrations Source: https://github.com/ekmungai/python-accounting/blob/main/README.md Initializes the library's configuration, creates a database engine, and runs migrations to set up necessary tables. ```python from python_accounting.config import config from python_accounting.models import Base from sqlalchemy import create_engine database = config.database engine = create_engine(database["url"]) Base.metadata.create_all(engine) # run migrations to create tables ``` -------------------------------- ### get_dates Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/_sources/autoapi/utils/dates/index.rst.txt Calculates and returns start, end, and period start dates based on provided inputs. ```APIDOC ## get_dates ### Description Returns the start, end and period start dates given the inputs provided. ### Signature `get_dates(session, start_date: datetime.datetime = None, end_date: datetime.datetime = None) -> tuple` ### Parameters - **session**: The session object. - **start_date** (datetime): The start date. Optional. - **end_date** (datetime): The end date. Optional. ### Returns A tuple containing the start date, end date, and period start date. ``` -------------------------------- ### Create and Query Account Balances Source: https://context7.com/ekmungai/python-accounting/llms.txt Demonstrates creating various account types (Bank, Receivable, Revenue) and querying their balances using methods like closing_balance, balance_movement, and opening_balance. Requires an active session and engine. ```python from python_accounting.models import Account with get_session(engine) as session: bank = Account( name="Main Bank", account_type=Account.AccountType.BANK, currency_id=currency.id, entity_id=entity.id, ) receivable = Account( name="Trade Debtors", account_type=Account.AccountType.RECEIVABLE, currency_id=currency.id, entity_id=entity.id, ) revenue = Account( name="Sales Revenue", account_type=Account.AccountType.OPERATING_REVENUE, currency_id=currency.id, entity_id=entity.id, ) session.add_all([bank, receivable, revenue]) session.commit() # Available AccountType values: # Balance Sheet – Assets: NON_CURRENT_ASSET, CONTRA_ASSET, INVENTORY, BANK, # CURRENT_ASSET, RECEIVABLE # Balance Sheet – Liabilities: NON_CURRENT_LIABILITY, CONTROL, CURRENT_LIABILITY, PAYABLE # Balance Sheet – Equity: EQUITY, RECONCILIATION # Income Statement: OPERATING_REVENUE, NON_OPERATING_REVENUE, # OPERATING_EXPENSE, DIRECT_EXPENSE, # OVERHEAD_EXPENSE, OTHER_EXPENSE # Query balances from datetime import datetime print(bank.closing_balance(session)) # Decimal('0.0000') print(bank.balance_movement(session, datetime(2024, 1, 1), datetime(2024, 12, 31))) print(bank.opening_balance(session, year=2024)) ``` -------------------------------- ### Create and Inspect Balance - Client Invoice Source: https://context7.com/ekmungai/python-accounting/llms.txt Demonstrates creating a `Balance` record for a prior-period carry-forward amount from a client invoice. It also shows how to inspect the opening trial balance using `opening_trial_balance`. ```python from python_accounting.models import Balance from datetime import datetime with get_session(engine) as session: opening = Balance( transaction_date=datetime(2023, 12, 1), # must pre-date current period transaction_no="IN00/0042", transaction_type=Balance.BalanceTransactions.CLIENT_INVOICE, amount=750, balance_type=Balance.BalanceType.DEBIT, account_id=receivable.id, entity_id=entity.id, ) session.add(opening) session.commit() # Inspect opening trial balance trial = Balance.opening_trial_balance(session) # trial = {"debits": Decimal('750'), "credits": Decimal('0'), "accounts": []} print(trial["debits"]) ``` -------------------------------- ### Get Reporting Period and Update Status Source: https://context7.com/ekmungai/python-accounting/llms.txt Shows how to retrieve a `ReportingPeriod` for a specific date and update its status. It also demonstrates how to get the calendar year for a given date. ```python from python_accounting.models import ReportingPeriod from datetime import datetime with get_session(engine) as session: period = ReportingPeriod.get_period(session, datetime(2024, 6, 15)) print(period) # 2024 print(period.status) # Status.OPEN print(period.interval()) # {"start": datetime(2024,1,1,0,0,0), "end": datetime(2024,12,31,23,59,59)} # Transition period to adjusting (audit adjustments only) period.status = ReportingPeriod.Status.ADJUSTING session.add(period) session.commit() # Get calendar year for a date year = ReportingPeriod.date_year(datetime(2024, 3, 15), entity) print(year) # 2024 ``` -------------------------------- ### database_init() function Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/genindex.html Initializes the database. ```APIDOC ## database_init() (in module database.database_init) ### Description Initializes the database system. ### Function `database.database_init.database_init()` ``` -------------------------------- ### get_dates() Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/genindex.html Utility function to get dates. ```APIDOC ## get_dates() ### Description Utility function to get dates. ### Method (Method signature not provided in source) ### Endpoint (Endpoint not applicable for this method) ### Parameters (Parameters not specified in source) ### Request Example (Request example not provided in source) ### Response (Response details not provided in source) ``` -------------------------------- ### database_init Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/_sources/autoapi/database/database_init/index.rst.txt Initializes the database by setting up all tables that do not currently exist. ```APIDOC ## database_init() ### Description Initializes the database by setting up all tables that do not currently exist. ### Parameters None ### Returns None ``` -------------------------------- ### models.entity.Entity.year_start Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/genindex.html Represents the start of the year attribute for an entity. ```APIDOC ## models.entity.Entity.year_start ### Description Represents the start of the year attribute for an entity. ### Method (Not specified, likely an attribute access in Python) ### Endpoint (Not applicable, Python attribute) ### Parameters (Not specified) ### Request Example (Not applicable) ### Response (Not specified) ``` -------------------------------- ### models.balance.Balance.opening_trial_balance() Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/genindex.html Static method to calculate the opening trial balance. ```APIDOC ## Static Method: models.balance.Balance.opening_trial_balance() ### Description Computes the opening trial balance. This is a static method of the Balance class. ``` -------------------------------- ### models.Entity.year_start Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/genindex.html Represents the start of the year attribute for an entity. ```APIDOC ## models.Entity.year_start ### Description Represents the start of the year attribute for an entity. ### Method (Not specified, likely an attribute access in Python) ### Endpoint (Not applicable, Python attribute) ### Parameters (Not specified) ### Request Example (Not applicable) ### Response (Not specified) ``` -------------------------------- ### database.database_init Module Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/genindex.html Module for database initialization. ```APIDOC ## database.database_init module ### Description Handles the initialization of the database. ### Module `database.database_init` ``` -------------------------------- ### get_period() Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/genindex.html Static method to get a reporting period. ```APIDOC ## get_period() ### Description Static method to get a reporting period. ### Method (Method signature not provided in source) ### Endpoint (Endpoint not applicable for this method) ### Parameters (Parameters not specified in source) ### Request Example (Request example not provided in source) ### Response (Response details not provided in source) ``` -------------------------------- ### ClearingMixin.clearances Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/_sources/autoapi/mixins/clearing/index.rst.txt Gets the assignments made to clear the Transaction. ```APIDOC ## clearances(session) ### Description Gets the assignments made to clear the Transaction. ### Parameters #### Path Parameters - **session** (Session) - Required - The accounting session to which the Transaction belongs. ### Returns - **list** - A List of assignments made to clear the Transaction. ``` -------------------------------- ### models.Balance.opening_trial_balance() Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/genindex.html Static method to calculate the opening trial balance. ```APIDOC ## Static Method: models.Balance.opening_trial_balance() ### Description Calculates the opening trial balance. This is a static method. ``` -------------------------------- ### contribution Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/autoapi/models/index.html Gets the amount contributed by the account to the transaction total. ```APIDOC ## contribution ### Description Gets the amount contributed by the account to the transaction total. ### Parameters - **session** (Session): The accounting session to which the Reporting Period belongs. - **account** (Account): The Account whose contribution is to be found. ### Returns - **Decimal**: The amount contributed by the account. ``` -------------------------------- ### closing_balance Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/_sources/autoapi/models/account/index.rst.txt Gets the closing balance of the Account as at a given date. ```APIDOC ## closing_balance(session, end_date: datetime.datetime = None) ### Description Gets the the closing balance of the Account as at the given date. ### Parameters #### Path Parameters - **session** (Session) - The accounting session to which the Account belongs. - **end_date** (datetime) - The latest transaction date for Transaction amounts to be included in the balance. ### Returns - **Decimal** - The total opening balance of the Account for the year. ``` -------------------------------- ### Generate Trial Balance Report Source: https://context7.com/ekmungai/python-accounting/llms.txt Instantiate a Trial Balance report to verify debit and credit equality. The DEBIT and CREDIT amounts must be equal, which can be asserted. ```python from python_accounting.reports import TrialBalance with get_session(engine) as session: report = TrialBalance(session) print(report) # Sections: Income Statement accounts, then Balance Sheet accounts # Results: Total Debits and Total Credits (must be equal) print(report.result_amounts["DEBIT"]) print(report.result_amounts["CREDIT"]) assert report.result_amounts["DEBIT"] == report.result_amounts["CREDIT"] ``` -------------------------------- ### ReportingPeriod.interval Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/autoapi/models/reporting_period/index.html Calculates and returns the start and end dates of the Reporting Period. ```APIDOC ## ReportingPeriod.interval ### Description Returns the start and end dates of the Reporting Period. ### Method Signature `interval(date: datetime.datetime = None) -> dict` ### Parameters * **date** (datetime, optional) – The date for which to determine the reporting period interval. Defaults to the current date. ### Returns A dictionary containing the start and end dates of the reporting period. ``` -------------------------------- ### Create Accounts for Transactions Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/_sources/compound_transaction.md.txt Sets up various accounts like bank, client, supplier, and asset accounts. These accounts are necessary for creating transactions. ```python from python_accounting.models import Account with get_session(engine) as session: bank_account = Account( name="Bank Account", account_type=Account.AccountType.BANK, currency_id=currency.id, entity_id=entity.id, ) client_account = Account( name="Client Account", account_type=Account.AccountType.RECEIVABLE, currency_id=currency.id, entity_id=entity.id, ) supplier_account = Account( name="Supplier Account", account_type=Account.AccountType.PAYABLE, currency_id=currency.id, entity_id=entity.id, ) asset_account = Account( name="Asset Account", account_type=Account.AccountType.NON_CURRENT_ASSET, currency_id=currency.id, entity_id=entity.id, ) session.add_all([ bank_account, client_account, supplier_account, asset_account ]) session.commit() ``` -------------------------------- ### ReportingPeriod.date_year static method Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/genindex.html Gets the year from a reporting period date. ```APIDOC ## date_year() (models.reporting_period.ReportingPeriod static method) ### Description Retrieves the year from the reporting period's date. ### Method `models.reporting_period.ReportingPeriod.date_year()` ### See Also * `models.ReportingPeriod.date_year` ``` -------------------------------- ### Create and Post Client Receipt Source: https://github.com/ekmungai/python-accounting/blob/main/docs/index.md Demonstrates creating a client receipt transaction with line items and posting it to the session. ```python client_receipt = ClientReceipt( narration="Client Receipt Transaction", transaction_date=datetime.now(), account_id=client_account.id, entity_id=entity.id, ) session.add(client_receipt) session.flush() client_receipt_line_item = LineItem( narration="Client Receipt line item", account_id=bank_account.id, amount=50, quantity=1, entity_id=entity.id, ) session.add(client_receipt_line_item) session.flush() client_receipt.line_items.add(client_receipt_line_item) session.add(client_receipt) client_receipt.post(session) ``` -------------------------------- ### Create and Post a Client Receipt Source: https://context7.com/ekmungai/python-accounting/llms.txt Use `ClientReceipt` to record payments received from clients. The main account must be `RECEIVABLE`. This snippet shows how to create a receipt, add line items, and post it to the session. ```python from python_accounting.transactions import ClientReceipt with get_session(engine) as session: receipt = ClientReceipt( narration="Payment for INV-001", transaction_date=datetime(2024, 7, 1), account_id=receivable.id, entity_id=entity.id, ) session.add(receipt) session.flush() line = LineItem(narration="Bank receipt", account_id=bank.id, amount=600, entity_id=entity.id) session.add(line) session.flush() receipt.line_items.add(line) session.add(receipt) receipt.post(session) print(receipt.transaction_no) # RC01/0001 print(receipt.balance(session)) # Decimal('600.0000') — unassigned ``` -------------------------------- ### ClearingMixin.cleared Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/_sources/autoapi/mixins/clearing/index.rst.txt Gets how much of the Transaction amount has been cleared by assignable Transactions. ```APIDOC ## cleared(session) ### Description Gets how much of the Transaction amount has been cleared by assignable Transactions. ### Parameters #### Path Parameters - **session** (Session) - Required - The accounting session to which the Transaction belongs. ### Returns - **Decimal** - The total amount of assignments made against Transaction. ``` -------------------------------- ### models.ReportingPeriod.interval Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/autoapi/models/index.html Returns the start and end dates of the Reporting Period for a given date. ```APIDOC ## models.ReportingPeriod.interval ### Description Returns the start and end dates of the Reporting Period. ### Parameters * **session** (_Session_) – The accounting session to which the Reporting Period belongs. * **date** (_datetime_) – The date for whose Reporting Period’s interval is to be found. ### Raises * **MissingReportingPeriodError** – If there no Reporting Period exists for the given date. ### Returns The Reporting Period. ### Return type [ReportingPeriod](#models.ReportingPeriod "models.ReportingPeriod") ``` -------------------------------- ### statement Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/_sources/autoapi/models/account/index.rst.txt Gets a chronological listing of transactions posted to the Account between specified dates. ```APIDOC ## statement(session, start_date: datetime.datetime = None, end_date: datetime.datetime = None, schedule: bool = False) ### Description Gets a chronological listing of the Transactions posted to the Account between the dates given. ### Parameters #### Path Parameters - **session** (Session) - The accounting session to which the Account belongs. - **start_date** (datetime) - The earliest transaction date for Transaction amounts to be included in the statement. - **end_date** (datetime) - The latest transaction date for Transaction amounts to be included in the statement. - **schedule** (bool) - Whether to exclude assignable Transactions and only list clearable Transactions with outstanding amounts. ### Raises - **InvalidAccountTypeError** - If the Account type is not Receivable or Payable. ### Returns - **dict** - A summary of the opening and closing balance in the case of a statement, the total, cleared and uncleared amounts if its a schedule together with a list of Transactions. Statements: - opening_balance (Decimal): The balance of the Account at the beginning of the statement period. - transactions (list): Transactions posted to the Account during the period. - closing_balance (Decimal): The balance of the Account at the end of the statement period. Schedule: - transactions (list): Outstanding clearable Transactions posted to the Account as at the end date. - total_amount (Decimal): The total amount of the Transactions in the Schdeule. - cleared_amount (Decimal): The amount of the Transactions in the Schdeule that has been cleared. - uncleared_amount (Decimal): The amount of the Transactions in the Schdeule that is still outstanding. ``` -------------------------------- ### InvalidBalanceDateError Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/_sources/autoapi/exceptions/index.rst.txt Raised when the balance date is invalid relative to the reporting period's start date. ```APIDOC class InvalidBalanceDateError(AccountingExeption): """Unless the Entity allows for mid year balances, the balance date must be earlier than its reporting period's start.""" pass ``` -------------------------------- ### Entity Class Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/_sources/autoapi/models/entity/index.rst.txt Represents the Reporting Entity. It holds information about the entity's financial reporting setup. ```APIDOC class Entity: """Represents the Reporting Entity.""" id: sqlalchemy.orm.Mapped[int] """The primary key of the Entity database record.""" name: sqlalchemy.orm.Mapped[str] """The Name of the Entity.""" multi_currency: sqlalchemy.orm.Mapped[bool] = False """Determines if the Entity can have Transactions in currencies other than its base Currency. Defaults to False.""" mid_year_balances: sqlalchemy.orm.Mapped[bool] = False """Determines if the Entity can have Opening Balances withing the current Reporting Period. Defaults to False.""" year_start: sqlalchemy.orm.Mapped[int] = 1 """The month at which the Entity's Reporting Periods begin, expressed as a number between 1 and 12. Defaults to 1 (January).""" locale: sqlalchemy.orm.Mapped[str] = 'en_GB' """The language format to be used to represent amounts. Defaults to en_GB.""" currency_id: sqlalchemy.orm.Mapped[int] """The id of the Reporting Currency of the Entity.""" reporting_period_id: sqlalchemy.orm.Mapped[int] """The id of the current Reporting Period of the Entity.""" currency: sqlalchemy.orm.Mapped[Currency] """The Reporting Currency of the Entity.""" reporting_period: sqlalchemy.orm.Mapped[python_accounting.models.ReportingPeriod] """The current Reporting Period of the Entity.""" users: sqlalchemy.orm.Mapped[List[User]] """A list of Users that belong to the Entity.""" def __repr__(self) -> str: ``` -------------------------------- ### Instantiate and Print Balance Sheet Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/balance_sheet.html Instantiate the BalanceSheet object with a session and print its representation. This will display the formatted balance sheet. ```python balance_sheet = BalanceSheet(session) print(balance_sheet) ``` -------------------------------- ### DuplicateReportingPeriodError Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/autoapi/exceptions/index.html Raised when a duplicate reporting period is detected, meaning a period with the same start and end dates already exists. ```APIDOC ## exceptions.DuplicateReportingPeriodError ### Description Raised when a duplicate reporting period is detected, meaning a period with the same start and end dates already exists. ### Inheritance Bases: `exceptions.AccountingExeption` ``` -------------------------------- ### Create and Post a Credit Note Source: https://context7.com/ekmungai/python-accounting/llms.txt Use `CreditNote` to issue reversals to clients. The main account must be `RECEIVABLE`. This snippet demonstrates creating a credit note, adding a revenue line item, and posting it. ```python from python_accounting.transactions import CreditNote with get_session(engine) as session: note = CreditNote( narration="Credit note for returned goods", transaction_date=datetime(2024, 7, 5), account_id=receivable.id, entity_id=entity.id, ) session.add(note) session.flush() line = LineItem(narration="Returned widgets", account_id=revenue.id, amount=200, entity_id=entity.id) session.add(line) session.flush() note.line_items.add(line) session.add(note) note.post(session) ``` -------------------------------- ### Create and Post a Client Receipt Transaction Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/index.html Illustrates the creation of a Client Receipt transaction and its Line Item, followed by posting. ```python from python_accounting.transactions import ClientReceipt client_receipt = ClientReceipt( narration="Client Receipt Transaction", transaction_date=datetime.now(), account_id=client_account.id, entity_id=entity.id, ) session.add(client_receipt) session.flush() client_receipt_line_item = LineItem( narration="Client Receipt line item", account_id=bank_account.id, amount=50, quantity=1, entity_id=entity.id, ) session.add(client_receipt_line_item) session.flush() client_receipt.line_items.add(client_receipt_line_item) session.add(client_receipt) client_receipt.post(session) ``` -------------------------------- ### Generate and Print Trial Balance Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/trial_balance.html Instantiate the TrialBalance class with a session and print the resulting trial balance report. This is useful for verifying the financial standing of an entity. ```python trial_balance = TrialBalance(session) print(trial_balance) ``` -------------------------------- ### Generate an Income Statement Report Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/index.html Shows how to instantiate and print an Income Statement report using the provided session. ```python from python_accounting.reports import IncomeStatement income_statement = IncomeStatement(session) print(income_statement) ``` -------------------------------- ### CashflowStatement Class Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/autoapi/reports/cashflow_statement/index.html Represents the movement of balances of Balance Sheet accounts during a given period. It inherits from FinancialStatement and requires a session, start date, and end date for initialization. ```APIDOC ## Class: CashflowStatement ### Description This class represents the movement of balances of Balance Sheet accounts during the given period. ### Parameters * `_session_`: The database session. * `_start_date`: The start date of the period (optional, defaults to None). * `_end_date`: The end date of the period (optional, defaults to None). ### Attributes * `config` (str): The configuration section for the report. Defaults to 'cashflow_statement'. * `sub_sections_` (dict): The categories of the contents of the sections of the report. ### Methods * `__repr__()`: Returns a string representation of the object. * `_get_sections(_start_date=None, _end_date=None, _full_balance=True)`: Retrieves the sections of the cash flow statement. * `_print_section(_section, _factor=1)`: Prints a section of the report. ``` -------------------------------- ### Create Multiple Transaction Types Source: https://github.com/ekmungai/python-accounting/blob/main/README.md Demonstrates the creation of various transaction types including Client Invoice, Cash Purchase, and their associated line items. ```python from python_accounting.transactions import ( CashSale, ClientInvoice, CashPurchase, SupplierBill, ClientReceipt, ) client_invoice = ClientInvoice( narration="Client Invoice Transaction", transaction_date=datetime.now(), account_id=client_account.id, entity_id=entity.id, ) session.add(client_invoice) session.flush() client_invoice_line_item = LineItem( narration="Client Invoice line item", account_id=revenue_account.id, amount=50, quantity=3, tax_id=output_tax.id, entity_id=entity.id, ) session.add(client_invoice_line_item) session.flush() client_invoice.line_items.add(client_invoice_line_item) session.add(client_invoice) client_invoice.post(session) cash_purchase = CashPurchase( narration="Cash Purchase Transaction", transaction_date=datetime.now(), account_id=bank_account.id, entity_id=entity.id, ) session.add(cash_purchase) session.flush() cash_purchase_line_item = LineItem( ``` -------------------------------- ### Create and Post a Compound Journal Entry Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/examples.html Demonstrates how to create a compound journal entry with multiple line items and post it to the session. Ensure the session and engine are properly initialized. ```python from python_accounting.transactions import JournalEntry from python_accounting.line_items import LineItem from datetime import datetime # Assume 'engine', 'get_session', 'bank_account', 'client_account', 'supplier_account', 'asset_account', and 'entity' are defined elsewhere. with get_session(engine) as session: journal_entry = JournalEntry( narration="Journal Entry Transaction", transaction_date=datetime.now(), account_id=bank_account.id, entity_id=entity.id, compound=True, # <- Turn on compound flag credited=False, main_account_amount=25, # <- Specify how much to post to the main (bank) account ) session.add(journal_entry) session.flush() client_account_line_item = LineItem( narration="Client Account line item", account_id=client_account.id, credited=True, # <- Specify to credit this line item's amount to is account amount=30, entity_id=entity.id, ) supplier_account_line_item = LineItem( narration="Supplier Account line item", account_id=client_account.id, amount=15, entity_id=entity.id, ) asset_account_line_item = LineItem( narration="Asset Account line item", account_id=asset_account.id, credited=True, # <- Specify to credit this line item's amount to is account amount=10, entity_id=entity.id, ) session.add_all([ client_account_line_item, supplier_account_line_item, asset_account_line_item ]) session.flush() journal_entry.line_items.add(client_account_line_item) journal_entry.line_items.add(supplier_account_line_item) journal_entry.line_items.add(asset_account_line_item) session.add(journal_entry) journal_entry.post(session) print(bank_account.closing_balance(session)) # Expected: 25 print(client_account.closing_balance(session)) # Expected: -30 print(supplier_account.closing_balance(session)) # Expected: 15 print(asset_account.closing_balance(session)) # Expected: -10 ``` -------------------------------- ### Config.configure_database() Method Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/genindex.html Configures the database connection. ```APIDOC ## Config.configure_database() ### Description Method to configure the application's database connection. ### Method `config.Config.configure_database()` ``` -------------------------------- ### Standard Journal Entry Transaction Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/_sources/compound_transaction.md.txt Creates a standard journal entry where the main account is debited and line item accounts are credited. This demonstrates a basic compound transaction setup. ```python from datetime import datetime from python_accounting.models import Transaction, LineItem from python_accounting.transactions import JournalEntry with get_session(engine) as session: journal_entry = JournalEntry( narration="Journal Entry Transaction", transaction_date=datetime.now(), account_id=bank_account.id, entity_id=entity.id, credited=False # <- Debit the main (bank) account ) session.add(journal_entry) session.flush() client_account_line_item = LineItem( narration="Client Account line item", account_id=client_account.id, amount=30, entity_id=entity.id, ) supplier_account_line_item = LineItem( narration="Supplier Account line item", account_id=supplier_account.id, amount=15, entity_id=entity.id, ) asset_account_line_item = LineItem( narration="Asset Account line item", account_id=asset_account.id, amount=10, entity_id=entity.id, ) session.add_all([ client_account_line_item, supplier_account_line_item, asset_account_line_item ]) session.flush() journal_entry.line_items.add(client_account_line_item) journal_entry.line_items.add(supplier_account_line_item) journal_entry.line_items.add(asset_account_line_item) session.add(journal_entry) journal_entry.post(session) print(bank_account.closing_balance(session)) # 55 print(client_account.closing_balance(session)) # -30 print(supplier_account.closing_balance(session)) # -15 print(asset_account.closing_balance(session)) # -10 ``` -------------------------------- ### Balance.opening_trial_balance Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/_sources/autoapi/models/index.rst.txt Retrieves the total opening balances for an Entity's accounts for a specified year. It returns a dictionary containing the total debit and credit balances, along with the accounts that constitute the opening trial balance. ```APIDOC ## Balance.opening_trial_balance(session, year: int = None) ### Description Gets the total opening balances for the Entity's accounts for the given year. ### Parameters #### Path Parameters - **session** (Session) - Required - The accounting session to which the Account belongs. - **year** (int, optional) - The calendar year to retrieve the opening trial balance for. Defaults to the Balance's Entity current Reporting Period's calendar year. ### Returns - **dict**: A summary of the debit and credit balances of the Accounts together with a list of the Accounts themselves. - debits (Decimal): The total debit balance. - credits (Decimal): The total credit balance. - accounts (Decimal): Accounts constituting the opening trial balance. ``` -------------------------------- ### Define Currency Codes Source: https://context7.com/ekmungai/python-accounting/llms.txt Holds a currency label and ISO 4217 code. Each account, transaction, balance, and line item is denominated in a currency. This example adds USD and EUR currencies for a given entity. ```python from python_accounting.models import Currency with get_session(engine) as session: usd = Currency(name="US Dollar", code="USD", entity_id=entity.id) eur = Currency(name="Euro", code="EUR", entity_id=entity.id) session.add_all([usd, eur]) session.commit() print(usd) # US Dollar ``` -------------------------------- ### Generate and Print Trial Balance Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/_sources/trial_balance.md.txt Instantiate the TrialBalance class with an accounting session and print the resulting report. The report details Income Statement and Balance Sheet accounts, their balances, and overall totals. ```python trial_balance = TrialBalance(session) print(trial_balance) Test Entity Trial Balance For the period: 01, Jan 2024 to 24, Feb 2024 Income Statement Operating Revenue -420.0000 Non Operating Revenue -50.0000 Operating Expense 100.0000 Direct Expense 65.0000 Overhead Expense 40.0000 _______________ Total Income Statement -265.0000 Balance Sheet Non Current Asset 100.0000 Inventory 100.0000 Bank 374.5000 Receivable 22.0000 Control -4.5000 Current Liability -100.0000 Payable -220.0000 Equity -77.0000 Reconciliation 70.0000 _______________ Total Balance Sheet 265.0000 _______________ Total Debits 871.5000 =============== _______________ Total Credits 871.5000 =============== ``` -------------------------------- ### opening_trial_balance Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/_sources/autoapi/models/balance/index.rst.txt A static method to retrieve the total opening balances for an Entity's accounts for a specified year. ```APIDOC ## opening_trial_balance(session, year: int = None) -> dict ### Description Gets the total opening balances for the Entity's accounts for the given year. ### Parameters - **session** (Session): The accounting session to which the Account belongs. - **year** (int, optional): The calendar year to retrieve the opening trial balance for. Defaults to the Balance's Entity current Reporting Period's calendar year. ### Returns - **dict**: A summary of the debit and credit balances of the Accounts together with a list of the Accounts themselves. - debits (Decimal): The total debit balance. - credits (Decimal): The total credit balance. - accounts (Decimal): Accounts constituting the opening trial balance. ``` -------------------------------- ### Generate Account Statement or Schedule Source: https://context7.com/ekmungai/python-accounting/llms.txt Retrieves a chronological transaction listing for RECEIVABLE/PAYABLE accounts. Use `schedule=True` to get only outstanding clearable transactions with aging details. Requires an active session and the `receivable` account object. ```python from python_accounting.models import Account from datetime import datetime with get_session(engine) as session: # Account Statement (all transactions) stmt = receivable.statement(session, start_date=datetime(2024, 1, 1)) # stmt = { # "opening_balance": Decimal('0'), # "transactions": [, ...], # "closing_balance": Decimal('180.0000'), # } # Account Schedule (only outstanding clearable transactions) schedule = receivable.statement(session, schedule=True) # schedule = { # "transactions": [], # each has .cleared_amount, .uncleared_amount, .age # "total_amount": Decimal('180.0000'), # "cleared_amount": Decimal('15.0000'), # "uncleared_amount": Decimal('165.0000'), # } for txn in schedule["transactions"]: print(txn.transaction_no, txn.uncleared_amount, txn.age) ``` -------------------------------- ### Module: __ini__ Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/autoapi/index.html Contains initialization logic for the Python Accounting library. ```APIDOC ## Module: __ini__ Contains initialization logic for the Python Accounting library. ``` -------------------------------- ### Create Reporting Entity and Currency Source: https://github.com/ekmungai/python-accounting/blob/main/README.md Sets up the primary reporting entity and its associated currency within the database. ```python from python_accounting.database.session import get_session from python_accounting.models import Entity, Currency with get_session(engine) as session: entity = Entity(name="Example Company") session.add(entity) session.commit() # This automatically sets up a Reporting Period for the Entity currency = Currency(name="US Dollars", code="USD", entity_id=entity.id) session.add(currency) session.commit() ``` -------------------------------- ### Create and Assign Category to Accounts Source: https://context7.com/ekmungai/python-accounting/llms.txt Demonstrates creating a `Category` to group accounts of the same `AccountType` and assigning an existing `Account` to this category. Requires an active session and engine. ```python from python_accounting.models import Category, Account with get_session(engine) as session: cat = Category( name="Current Bank Accounts", category_account_type=Account.AccountType.BANK, entity_id=entity.id, ) session.add(cat) session.commit() # Assign account to category bank.category_id = cat.id session.add(bank) session.commit() # Get balances for all accounts in this category result = cat.account_balances(session) # result = {"total": Decimal('...'), "accounts": [] print(result["total"]) ``` -------------------------------- ### Create and Post a Client Invoice Transaction Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/index.html Shows how to create a Client Invoice transaction and a Line Item for it. The invoice is then posted to the ledger. ```python from python_accounting.transactions import ClientInvoice client_invoice = ClientInvoice( narration="Client Invoice Transaction", transaction_date=datetime.now(), account_id=client_account.id, entity_id=entity.id, ) session.add(client_invoice) session.flush() client_invoice_line_item = LineItem( narration="Client Invoice line item", account_id=revenue_account.id, amount=50, quantity=3, tax_id=output_tax.id, entity_id=entity.id, ) session.add(client_invoice_line_item) session.flush() client_invoice.line_items.add(client_invoice_line_item) session.add(client_invoice) client_invoice.post(session) ``` -------------------------------- ### default_configuration Source: https://github.com/ekmungai/python-accounting/blob/main/docs/_build/html/genindex.html The default configuration object. ```APIDOC ## default_configuration (in module config) ### Description Provides the default configuration settings for the application. ### Variable `config.default_configuration` ``` -------------------------------- ### Create and Post Supplier Bill Source: https://github.com/ekmungai/python-accounting/blob/main/docs/index.md Demonstrates creating a supplier bill transaction with line items and posting it to the session. ```python supplier_bill = SupplierBill( narration="Credit Purchase Transaction", transaction_date=datetime.now(), account_id=supplier_account.id, entity_id=entity.id, ) session.add(supplier_bill) session.flush() supplier_bill_line_item = LineItem( narration="Credit Purchase line item", account_id=asset_account.id, amount=25, quantity=4, tax_id=output_tax.id, entity_id=entity.id, ) session.add(supplier_bill_line_item) session.flush() supplier_bill.line_items.add(supplier_bill_line_item) session.add(supplier_bill) supplier_bill.post(session) ```