piecash

repository·master·Indexed 43 days ago

https://github.com/sdementen/piecash

A pure Python library providing a Pythonic interface to GnuCash files stored in SQL backends (sqlite3, Postgres, and MySQL). It allows developers to programmatically read, modify, or create GnuCash documents without requiring the GnuCash application to be installed. Supports GnuCash 3.0.n and older 2.6.x series, with optional extras for pandas, Yahoo quotes, and QIF export.

Tokens
16.3K
Snippets
63
Records
82
Agent score
53%

What's inside piecash

  1. Use Piecash to interact with GnuCash SQL files

    master

    Piecash provides a Pythonic interface for accessing and modifying GnuCash files stored in SQL databases (sqlite3, Postgres, and MySQL). It allows you to open existing documents, modify or add objects (such as accounts, transactions, and prices), or create new documents from scratch. It is a pure Python package and serves as an alternative to official Python bindings or XML parsing.

    from piecash import open_book
    
    with open_book("example.gnucash") as book:
        # Access objects within the book
        print(book.default_currency)
  2. Understand the GnuCash SQL Object Model and Schema

    master

    Piecash maps the GnuCash SQL schema (tables, columns, and relationships) to Python objects. This mapping is designed to ensure data integrity and semantic compatibility with the official GnuCash application.

    Important Usage Warnings:

    • Primary Focus: Piecash is primarily designed for reading GnuCash books and creating new Core objects.
    • Risk Warning: While you can create other objects, modify existing attributes/relationships, or delete objects using piecash, doing so is at your own risk. Always backup your GnuCash books before performing any modifications or deletions.
    • Schema Note: The official GnuCash schema does not define foreign keys; the schema documentation in piecash may include them (e.g., when generated with keep_foreign_keys on MySQL) to aid understanding.
  3. Access GnuCash objects using the Object Model pattern

    master

    The Object Model pattern allows you to navigate the GnuCash hierarchy through natural relations. You can start from the book.root_account and traverse through children to reach specific accounts, commodities, or transactions.

    import piecash
    
    book = piecash.open_book("default_book.gnucash")
    
    # Access the root account
    root = book.root_account
    
    # Traverse children by name
    assets = root.children(name="Assets")
    
    # Traverse children by index
    first_child = assets.children[0]
    
    # Traverse children by type (e.g., 'CASH')
    cash_account = first_child.children(type="CASH")
    
    # Access related objects (e.g., the commodity of an account)
    commo = cash_account.commodity
    
    # Access related objects from a commodity (e.g., accounts linked to it)
    for acc in commo.accounts[:10]:
        print(acc)
  4. Access GnuCash objects using the Table access pattern

    master

    The Table access pattern provides direct access to collections of objects from the Book instance. You can iterate over these collections or use filtering methods to retrieve specific items.

    import piecash
    
    book = piecash.open_book("default_book.gnucash")
    
    # Direct collection access
    all_accounts = book.accounts
    all_commodities = book.commodities
    all_transactions = book.transactions
    
    # Iteration
    for acc in book.accounts:
        if acc.type == "ASSET": 
            print(acc)
    
    # Filtering by name
    account = book.accounts(name="Garbage collection")
    
    # Filtering by type
    expense_account = book.accounts(type="EXPENSE")
    
    # Filtering by fullname
    ss_account = book.accounts(fullname="Expenses:Taxes:Social Security")
    
    # Filtering by multiple criteria
    filtered_acc = book.accounts(commodity=book.commodities[0], name="Gas")
  5. Understand the GnuCash Core Object Model

    master

    The GnuCash data model is built around five core objects that represent the financial state of a document. Understanding the relationship between these objects is essential for interacting with the database:

    1. Book: Represents the entire GnuCash document. It contains the root account and template for scheduled transactions.
    2. Commodity: Represents currencies (e.g., USD, EUR) or assets (e.g., stocks like AMZN).
      • Currencies always have the namespace CURRENCY.
      • Accounts are linked to a specific commodity they handle.
    3. Account: Tracks a specific commodity for a business purpose (e.g., a Savings account or an Expense account). Accounts are organized in a tree structure via a parent field.
    4. Transaction: Represents the movement of money between accounts. Every transaction is denominated in a specific currency.
    5. Split: The building block of a Transaction. A single Transaction must consist of two or more Splits. Each Split links a Transaction to a specific Account and records the change in both quantity (the commodity amount) and value (the transaction currency amount).
    6. Price: An auxiliary object used for exchange rates and stock valuation, linking a commodity to a currency at a specific date.
  6. How slots work in GnuCash objects and Frames

    master

    In piecash, GnuCash objects and Frames behave like Python dictionaries. A key feature of slots is that values are automatically converted between Python objects and their underlying GnuCash representations. For example, datetime objects, decimal.Decimal, and other Python types are handled transparently when setting or retrieving slot values.

    import datetime, decimal
    from piecash import create_book
    
    book = create_book()
    book["myintkey"] = 3
    book["mydatekey"] = datetime.date.today()
    book["mynumerickey"] = decimal.Decimal("12.34567")
  7. Understand Transactions and Splits

    master

    Financial movements are modeled using a combination of Transaction and Split objects.

    The Balancing Invariant: For any given Transaction, the sum of the value of all its associated Splits must equal zero. If a transaction is not balanced, GnuCash automatically creates an extra Split pointing to an 'Account Imbalance' account.

    Data Representation: Both value and quantity are expressed as a numerator/denominator pair.

    • The denominator for value must match the fraction of the transaction's currency.
    • The denominator for quantity must match the commodity_scu of the account.
  8. Overwrite an existing Book

    master

    If you attempt to create a book using a file or database that already exists, piecash will raise an exception. To force piecash to delete the existing file/database and recreate it from scratch, pass the overwrite=True argument.

    import piecash
    
    # Overwrite an existing file
    book = piecash.create_book(sqlite_file="example_file.gnucash", overwrite=True)
    
    # Overwrite using a URI connection
    book = piecash.create_book(uri_conn="sqlite:///example_file.gnucash", overwrite=True)
  9. Open an existing GnuCash book

    master

    Use piecash.open_book to load an existing GnuCash document into a Book object. By default, books are opened in read-only mode.

    To enable read-write access, set readonly=False. When doing so, piecash automatically creates a backup file (formatted as filename.piecash_YYYYMMDD_HHMMSS) unless you specify do_backup=False.

    import piecash
    
    # Open a sqlite3 file (read-only)
    book = piecash.open_book("existing_file.gnucash")
    
    # Open with read-write access
    book = piecash.open_book("existing_file.gnucash", readonly=False)
    
    # Open with read-write access and disable automatic backup
    book = piecash.open_book("existing_file.gnucash", readonly=False, do_backup=False)
    
    # Force open even if the file is locked
    book = piecash.open_book("existing_file.gnucash", open_if_lock=True)
  10. Use sample GnuCash books for schema introspection

    master

    The repository provides several sample GnuCash books that can be used to inspect the underlying SQL schema for testing, examples, or debugging purposes. These books are categorized by the version of GnuCash used to create them and the options enabled:

    • reference/default_2_6_21_basic.gnucash: An empty book created with GnuCash 2.6.21 with no specific options enabled.
    • reference/default_2_6_21_full_options.gnucash: An empty book created with GnuCash 2.6.21 with multiple options enabled (e.g., trading accounts).
    • reference/default_piecash_0_18_basic.gnucash: An empty book created directly by Piecash.
  11. Find GnuCash and Python integration resources

    master

    For developers working with GnuCash and Python, the following official links and community resources are available:

    Community and Discussion

    • Gitter Chat: Join the developer and user discussion at https://gitter.im/sdementen/piecash
    • Mailing List Searches: You can search for Python-related discussions in the GnuCash mailing lists using these Google search queries:
      • User Mailing List: python site:http://lists.gnucash.org/pipermail/gnucash-user
      • Devel Mailing List: python site:http://lists.gnucash.org/pipermail/gnucash-devel
  12. Note on Project Migration and Version Compatibility

    master

    Project Migration

    ⚠️ This repository is no longer maintained. Development has moved to an active fork maintained by @gorf. Please use https://github.com/gorf/piecash for issues, pull requests, and downloads.

    Version Compatibility

    • Piecash 1.0.0+: Supports Python >= 3.6 and GnuCash 3.0.x series books.
    • Piecash 0.19.0: Use this version if you need to work with Python 2.7/3.4 and GnuCash 2.6.x series books.