### Install piecash from source Source: https://github.com/sdementen/piecash/blob/master/docs/source/doc/doc.rst Instructions for installing piecash by unpacking the source distribution and running the setup script. ```bash $ python setup.py install ``` -------------------------------- ### Install piecash using Conda on Windows Source: https://github.com/sdementen/piecash/blob/master/docs/source/doc/doc.rst Guides users on Windows to set up a Conda environment for piecash, including installing Python, pip, and SQLAlchemy via Conda before installing piecash. ```bash $ conda create -n piecash_venv python=3 pip sqlalchemy $ activate piecash_venv $ pip install piecash ``` -------------------------------- ### Open GnuCash Book with piecash Source: https://github.com/sdementen/piecash/blob/master/docs/source/doc/doc.rst A quickstart example demonstrating how to open a GnuCash file using piecash in read-only mode and access its objects. ```python import piecash # open a GnuCash Book book = piecash.open_book("test.gnucash", readonly=True) ``` -------------------------------- ### Create and Open GnuCash Files with Piecash Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/examples.rst Demonstrates the basic process of creating a new GnuCash file or opening an existing one using the piecash library. This is a foundational example for all other operations. ```python from piecash import open_book, Transaction from piecash.direct import book as b, account as a, transaction as t # Create a new book my_book = b.Book() # Add an account root_account = my_book.root_account("Equity", "owner’s equity") my_book.save() # Open an existing book # my_book = open_book("my_gnucash_file.gnucash") ``` -------------------------------- ### Create GnuCash Book with Accounts and Transactions using Piecash Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/examples.rst A comprehensive example demonstrating the creation of a GnuCash book, adding several accounts, and then populating it with a transaction using piecash. ```python from piecash import Transaction, Split from piecash.direct import book as b, account as a # Create a new book my_book = b.Book() # Add some accounts assets = my_book.root_account("Assets", "Assets") checking = assets.add_account("Checking", "Checking Account") expenses = my_book.root_account("Expenses", "Expenses") groceries = expenses.add_account("Groceries", "Groceries Expense") # Create a transaction trn = Transaction( book=my_book, currency=my_book.primary_currency, description="Initial grocery purchase", splits=[ Split(account=checking, value=-75.50), Split(account=groceries, value=75.50), ] ) my_book.save() ``` -------------------------------- ### Install and Test piecash with Pipenv Source: https://github.com/sdementen/piecash/blob/master/docs/source/android.rst Demonstrates creating a project directory, installing piecash using pipenv, activating the virtual environment, and importing piecash in a Python interpreter to verify the installation. ```bash mkdir my-project cd my-project pipenv install piecash pipenv shell python >>> import piecash ``` -------------------------------- ### Open and Read GnuCash Book Example Source: https://github.com/sdementen/piecash/blob/master/docs/source/doc/doc.rst Demonstrates how to open a GnuCash book using piecash and access its default currency and transactions. This example showcases basic book navigation and data retrieval. ```python with open_book("example.gnucash") as book: # get default currency of book print( book.default_currency ) # ==> Commodity # iterating over all splits in all books and print the transaction description: for acc in book.accounts: for sp in acc.splits: print(sp.transaction.description) ``` -------------------------------- ### Install piecash using pipenv Source: https://github.com/sdementen/piecash/blob/master/docs/source/doc/doc.rst Shows how to install the piecash package using pipenv, a tool for managing Python dependencies. ```bash $ pipenv install piecash ``` -------------------------------- ### Install piecash using pip Source: https://github.com/sdementen/piecash/blob/master/docs/source/doc/doc.rst Provides instructions for installing the piecash package using pip, including options for extra functionalities like pandas, yahoo, postgres, mysql, and qif. ```bash $ pip install piecash ``` ```bash $ pip install -U piecash ``` ```bash $ pip install piecash[pandas,qif,postgres] ``` -------------------------------- ### Upload Distribution to PyPI with Setup.py Source: https://github.com/sdementen/piecash/blob/master/DEVELOPER.rst Uploads the generated source distribution to the Python Package Index (PyPI) using the setup.py script. This makes the package available for installation by others. ```bash python setup.py sdist upload ``` -------------------------------- ### Create GnuCash Account with Piecash Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/examples.rst Shows how to create a new account within a GnuCash book using the piecash library. It involves specifying the account type and name. ```python from piecash.direct import book as b # Assuming my_book is an existing Book object # my_book = b.Book("my_gnucash_file.gnucash") # Create a new account under the root 'Assets' account # You might need to get the root account first if not already present # root_assets = my_book.root_account("Assets", "Assets") # new_account = root_assets.add_account("Checking", "My Checking Account") # my_book.save() ``` -------------------------------- ### Build HTML Documentation with Make Source: https://github.com/sdementen/piecash/blob/master/DEVELOPER.rst Builds the HTML version of the project documentation. Ensure that documentation dependencies are installed via 'pipenv install -e .[doc]' before running this command. The output will be in docs/build/html. ```bash cd docs make html ``` -------------------------------- ### Prepare Development Virtual Environment with Pipenv Source: https://github.com/sdementen/piecash/blob/master/DEVELOPER.rst Installs project dependencies including test and documentation requirements into a virtual environment using Pipenv. This is the recommended way to set up the development environment. ```bash pipenv install -e .[test,doc] ``` -------------------------------- ### Create PostgreSQL Book Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/new_objects/create_book.rst Creates a new GnuCash book using a PostgreSQL database. This requires the `psycopg2` package to be installed (`pip install psycopg2`). The connection details are provided via a URI string. Overwriting existing databases is not explicitly shown but follows the same pattern as SQLite. ```python book = piecash.create_book(uri_conn="postgres://user:passwd@localhost/example_gnucash_db") ``` -------------------------------- ### Retrieve Objects from Piecash Book using get() Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/existing_objects/others.rst Demonstrates how to access specific objects like Account, Commodity, Budget, and Vendor from a Piecash book using the generic get() method. This method takes the object class and relevant attributes as keyword arguments to find the desired object within the book's session. ```python book = open_book(gnucash_books + "invoices.gnucash", open_if_lock=True) from piecash import Account, Commodity, Budget, Vendor # accessing specific objects through the get method book.get(Account, name="Assets", parent=book.root_account) book.get(Commodity, namespace="CURRENCY", mnemonic="EUR") book.get(Budget, name="my first budget") book.get(Vendor, name="Looney") ``` -------------------------------- ### Create GnuCash Transaction with Piecash Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/examples.rst Illustrates how to create a new transaction in a GnuCash book with piecash. This typically involves specifying source and destination accounts and amounts. ```python from piecash import Transaction, Split from piecash.direct import book as b # Assuming my_book is an existing Book object # and you have access to source and destination accounts # from piecash.direct.account import Account # source_account: Account = my_book.get_account("Assets:Checking") # dest_account: Account = my_book.get_account("Expenses:Groceries") # Create a transaction # trn = Transaction( # book=my_book, # currency=my_book.primary_currency, # description="Grocery Shopping", # splits=[ # Split(account=source_account, value=-50.00), # Split(account=dest_account, value=50.00), # ] # ) # my_book.save() ``` -------------------------------- ### Install OpenSSH Server in Termux Source: https://github.com/sdementen/piecash/blob/master/docs/source/android.rst Installs the OpenSSH server package within Termux, enabling SSH access to the Android device. Requires configuration of authorized keys and starting the SSH daemon. ```bash pkg install openssh ``` -------------------------------- ### Calculating Account Balances with Piecash (Python) Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/existing_objects/account.rst Shows how to iterate through the children of the root account and calculate their balances using the `get_balance()` method. It also demonstrates how to get the balance with and without natural sign reversal. This requires the `piecash` library and an opened GnuCash book. ```python from piecash import open_book gnucash_books = "/path/to/your/gnucash/files/" book = open_book(gnucash_books + "simple_sample.gnucash", open_if_lock=True) root = book.root_account # calculating the balance of the accounts: for acc in root.children: print(f"Account balance for {acc.name}: {acc.get_balance()} (without sign reversal: {acc.get_balance(natural_sign=False)})") ``` -------------------------------- ### Delete GnuCash Account with Piecash Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/examples.rst Shows the process of deleting an account from a GnuCash book using piecash. It's important to ensure the account is not referenced by other parts of the book to avoid errors. ```python from piecash.direct import book as b # Assuming my_book and the account to delete 'account_to_delete' exist # account_to_delete = my_book.get_account("Expenses:OldCategory") # if account_to_delete: # my_book.delete_account(account_to_delete) # my_book.save() ``` -------------------------------- ### Extract GnuCash Split Information to Pandas DataFrame with Piecash Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/examples.rst Demonstrates how to extract split information from a GnuCash book and load it into a pandas DataFrame using piecash. This facilitates powerful data manipulation and analysis with pandas. ```python import pandas as pd from piecash.direct import book as b # Assuming my_book is an existing Book object # my_book = b.Book("my_gnucash_file.gnucash") # Extract splits to a pandas DataFrame # This would typically involve iterating through transactions and their splits # and collecting the data into a format suitable for DataFrame creation. # The specific example file would contain the detailed code. # Example conceptual DataFrame creation: # splits_data = [] # for trn in my_book.transactions: # for split in trn.splits: # splits_data.append({ # 'transaction_id': trn.id, # 'account': split.account.name, # 'value': split.value, # 'currency': split.currency.iso, # 'memo': split.memo # }) # df = pd.DataFrame(splits_data) ``` -------------------------------- ### Save/Cancel GnuCash Book Changes with Piecash Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/examples.rst Illustrates how to save changes made to a GnuCash book or discard them using piecash. This is crucial for managing data integrity. ```python from piecash.direct import book as b # Assuming my_book is an existing Book object # Save changes # my_book.save() # To cancel changes, you would typically close the book without saving # and reopen it, or handle this logic before calling save. # For example, if you make changes and decide not to save: # my_book.close() # This might implicitly discard uncommitted changes depending on implementation # Re-open the book to get the state before changes # my_book = b.Book("my_gnucash_file.gnucash") ``` -------------------------------- ### Export GnuCash Transactions to CSV with Piecash Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/examples.rst Shows how to export transaction data from a GnuCash book into a CSV file format using the piecash library. This is useful for data analysis or importing into other systems. ```python from piecash.direct import book as b # Assuming my_book is an existing Book object # my_book = b.Book("my_gnucash_file.gnucash") # Export transactions to CSV # This might require a specific function or method not directly shown in simple_export_transaction_csv.py # The actual implementation in the example file would detail the specific parameters and logic. # Example conceptual call: # my_book.export_transactions_to_csv("transactions.csv") ``` -------------------------------- ### Release New Version with Gitflow Source: https://github.com/sdementen/piecash/blob/master/DEVELOPER.rst Steps for releasing a new version of Piecash using the Gitflow branching model. This includes starting a release branch, updating project files, finishing the release, and uploading the distribution. ```bash 0. git flow release start 0.18.0 1. update metadata.py 2. update changelog 3. git flow release finish 4. checkout master branch in git 5. python setup.py sdist upload ``` -------------------------------- ### Retrieve All Transactions in Piecash Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/existing_objects/transaction.rst This snippet demonstrates how to open a Piecash book and iterate through all its transactions. It includes examples of printing all transactions and filtering for those generated from a scheduled transaction. Dependencies: Piecash library. ```python from piecash import open_book gnucash_books = "/path/to/your/books/" book = open_book(gnucash_books + "book_schtx.gnucash", open_if_lock=True) # all transactions (including transactions part of a scheduled transaction description) for tr in book.transactions: print(tr) # selecting first transaction generated from a scheduled transaction tr = [ tr for tr in book.transactions if tr.scheduled_transaction ][0] ``` -------------------------------- ### Export GnuCash Book to Ledger-CLI Format Source: https://github.com/sdementen/piecash/blob/master/docs/source/doc/doc.rst This Python snippet demonstrates how to export a GnuCash book to the ledger-cli format using the piecash library. It shows how to open a book and then use the `ledger` function to print the representation. It also includes an example of using locale-specific currency formatting. ```python book = open_book(gnucash_books + "simple_sample.gnucash", open_if_lock=True) from piecash import ledger # printing the ledger-cli (https://www.ledger-cli.org/) representation of the book print(ledger(book)) # printing the ledger-cli (https://www.ledger-cli.org/) representation of the book using regional settings (locale) for currency output print(ledger(book, locale=True)) ``` -------------------------------- ### Query and Filter GnuCash Data with SQLAlchemy Source: https://context7.com/sdementen/piecash/llms.txt Demonstrates how to use SQLAlchemy within Piecash for advanced filtering, sorting, and querying of transactions and splits based on dates, accounts, and values. It also shows how to calculate account balances and identify accounts exceeding a certain threshold. This functionality requires the SQLAlchemy library to be installed. ```python from piecash import open_book, Account, Transaction, Split from datetime import date, timedelta from decimal import Decimal with open_book("mybook.gnucash") as book: # Get all transactions in date range start_date = date(2024, 1, 1) end_date = date(2024, 12, 31) transactions = ( book.query(Transaction) .filter(Transaction.post_date >= start_date) .filter(Transaction.post_date <= end_date) .order_by(Transaction.post_date) .all() ) # Get splits for specific account checking = book.accounts(fullname="Assets:Checking") splits = ( book.query(Split) .filter(Split.account == checking) .join(Transaction) .order_by(Transaction.post_date) .all() ) # Calculate account transactions summary for split in splits: tx = split.transaction print(f"{tx.post_date}: {tx.description} - {split.value}") # Get accounts with balance > threshold threshold = Decimal("1000") wealthy_accounts = [ acc for acc in book.accounts if acc.get_balance() > threshold ] # Complex query with multiple conditions large_expenses = ( book.query(Split) .join(Account) .join(Transaction) .filter(Account.type == "EXPENSE") .filter(Split.value > Decimal("100")) .filter(Transaction.post_date >= start_date) .all() ) print(f"Found {len(large_expenses)} large expenses") ``` -------------------------------- ### Setup Termux Storage Access Source: https://github.com/sdementen/piecash/blob/master/docs/source/android.rst Grants Termux access to the Android device's storage, allowing interaction with files and folders accessible via USB sync. ```bash termux-setup-storage ``` -------------------------------- ### Modify GnuCash Transactions/Splits with Piecash Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/examples.rst Demonstrates how to modify existing transactions or their associated splits within a GnuCash book using piecash. This allows for updating details like amounts or descriptions. ```python from piecash.direct import book as b # Assuming my_book and a transaction object 'trn' exist # trn.description = "Updated Grocery Purchase" # for split in trn.splits: # if split.account.name == "Assets:Checking": # split.value = -55.00 # my_book.save() ``` -------------------------------- ### Export GnuCash Data to Ledger-CLI Format Source: https://context7.com/sdementen/piecash/llms.txt Provides a simple way to export an entire GnuCash book into the text-based ledger-cli format. The example shows how to generate the ledger output as a string and also how to save it directly to a file. This is useful for users who prefer or need to work with ledger-cli. ```python from piecash import open_book, ledger # Export entire book to ledger format with open_book("mybook.gnucash") as book: ledger_output = ledger(book) print(ledger_output) # Save to file with open("output.ledger", "w") as f: f.write(ledger_output) # Ledger format output example: # ; Start of file # ; Book: mybook.gnucash # # commodity USD # note United States Dollar # format $1,000.00 # # account Assets:Checking # note Checking Account # # 2024-01-15 Grocery shopping # Expenses:Groceries $45.67 # Assets:Checking -$45.67 ``` -------------------------------- ### Generate Filtered GnuCash Transaction Reports with Piecash Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/examples.rst Explains how to generate filtered transaction reports from a GnuCash book using piecash. This allows users to view specific sets of transactions based on criteria like date range or account. ```python from piecash.direct import book as b # Assuming my_book is an existing Book object # my_book = b.Book("my_gnucash_file.gnucash") # Generate a filtered report # The specific filtering logic (e.g., by date, account, etc.) would be implemented # within the 'filtered_transaction_report.py' script. # Example conceptual filtering: # from datetime import date # start_date = date(2023, 1, 1) # end_date = date(2023, 12, 31) # filtered_transactions = [ # trn for trn in my_book.transactions # if start_date <= trn.date.date() <= end_date # ] # print(filtered_transactions) ``` -------------------------------- ### Create and Assign Tax Table to Customer in Piecash (Python) Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/new_objects/create_business.rst Illustrates the creation of a tax table with a percentage-based entry linked to a specific account. This tax table is then assigned to a customer. The process involves importing `Taxtable`, `TaxtableEntry`, and `Decimal`. The example assumes an existing `piecash` book and account. ```python from piecash import Taxtable, TaxtableEntry from decimal import Decimal # let us first create an account to which link a tax table entry acc = Account(name="MyTaxAcc", parent=b.root_account, commodity=b.currencies(mnemonic="EUR"), type="ASSET") # then create a table with on entry (6.5% on previous account tt = Taxtable(name="local taxes", entries=[ TaxtableEntry(type="percentage", amount=Decimal("6.5"), account=acc), ]) # and finally attach it to a customer c2.taxtable = tt b.save() print(b.taxtables) ``` -------------------------------- ### Access SQLAlchemy Session and Query Objects in Piecash Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/existing_objects/others.rst Shows how to obtain the underlying SQLAlchemy session from a Piecash book object. This allows for direct execution of SQLAlchemy queries using Piecash's defined classes, enabling advanced data retrieval and manipulation. For example, it demonstrates looping through all invoices in the session. ```python from piecash import Account, Commodity, Budget, Vendor # get the SQLAlchemy session session = book.session # loop through all invoices for invoice in session.query(Invoice).all(): print(invoice.notes) ``` -------------------------------- ### Start SSH Daemon in Termux Source: https://github.com/sdementen/piecash/blob/master/docs/source/android.rst Starts the SSH daemon (sshd) on the Android device via Termux, allowing remote connections. Requires SSH server to be installed and authorized keys configured. ```bash sshd ``` -------------------------------- ### Install Python and Pipenv in Termux Source: https://github.com/sdementen/piecash/blob/master/docs/source/android.rst Installs Python and pipenv, a package manager and dependency tool, within the Termux environment on Android. These are necessary for installing and managing piecash. ```bash pkg install python pip install pipenv ``` -------------------------------- ### Open Existing GnuCash Book with Piecash Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/existing_objects/open_book.rst Demonstrates opening an existing GnuCash document using piecash.open_book. Supports file paths and URI connection strings for SQLite and PostgreSQL. Options for read-only access, disabling backups, and forcing opening with locks are shown. ```python import piecash # for a sqlite3 document book = piecash.open_book("existing_file.gnucash") # or through an URI connection string for sqlite3 book = piecash.open_book(uri_conn="sqlite:///existing_file.gnucash") # or for postgres book = piecash.open_book(uri_conn="postgres://user:passwd@localhost/existing_gnucash_db") # To allow RW access book = piecash.open_book("existing_file.gnucash", readonly=False) # To avoid creating a backup file book = piecash.open_book("existing_file.gnucash", readonly=False, do_backup=False) # To force opening the file even through there is a lock on it book = piecash.open_book("existing_file.gnucash", open_if_lock=True) ``` -------------------------------- ### Create and Add Customer to Piecash Book (Python) Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/new_objects/create_business.rst Demonstrates creating a new customer, associating an address and currency, adding it to an in-memory book, and flushing the book to assign an ID. It also shows how to create a customer directly within a book, which immediately assigns an ID. Dependencies include the `piecash` library, specifically `create_book`, `Customer`, and `Address`. ```python from piecash import create_book, Customer, Address # create a book (in memory) b = create_book(currency="EUR") # get the currency eur = b.default_currency # create a customer c1 = Customer(name="Mickey", currency=eur, address=Address(addr1="Sesame street 1", email="mickey@example.com")) # the customer has not yet an ID c1 # we add it to the book b.add(c1) # flush the book b.flush() # the customer gets its ID print(c1) # or create a customer directly in a book (by specifying the book argument) c2 = Customer(name="Mickey", currency=eur, address=Address(addr1="Sesame street 1", email="mickey@example.com"), book=b) # the customer gets immediately its ID c2 # the counter of the ID is accessible as b.counter_customer b.save() ``` -------------------------------- ### Generate Source Distribution (sdist) with Setup.py Source: https://github.com/sdementen/piecash/blob/master/DEVELOPER.rst Creates a source distribution archive (tar.gz) for the Piecash project using the setup.py script. This package contains the source code and is used for distribution. ```bash python setup.py sdist ``` -------------------------------- ### Query Stock Prices with piecash Source: https://github.com/sdementen/piecash/blob/master/docs/source/doc/doc.rst Illustrates how to iterate through and print all stock prices stored within an opened GnuCash book using piecash. ```python # example 1, print all stock prices in the Book # display all prices for price in book.prices: print(price) ``` -------------------------------- ### Set up Conda Environments for Testing Source: https://github.com/sdementen/piecash/blob/master/DEVELOPER.rst Creates Conda environments with specific Python versions (e.g., 3.5, 3.6) for testing purposes. These environments should be configured in tox.ini. ```bash conda create -n py35 python=3.5 virtualenv conda create -n py36 python=3.6 virtualenv ... ``` -------------------------------- ### Open GnuCash Book and Access Data with Piecash (Python) Source: https://github.com/sdementen/piecash/blob/master/README.rst Demonstrates how to open a GnuCash file using Piecash and access basic book information like the default currency. It also shows how to iterate through accounts and splits to retrieve transaction descriptions. This snippet requires the piecash library and a valid GnuCash file. ```python from piecash import open_book with open_book("example.gnucash") as book: # get default currency of book print( book.default_currency ) # ==> Commodity # iterating over all splits in all books and print the transaction description: for acc in book.accounts: for sp in acc.splits: print(sp.transaction.description) ``` -------------------------------- ### Create New GnuCash Book - Python Source: https://context7.com/sdementen/piecash/llms.txt Creates a new GnuCash file from scratch, either in-memory or file-based. Allows specifying the default currency and optionally overwriting existing files. Demonstrates creating a default root account and building a custom account hierarchy. Dependencies: piecash library, decimal. Inputs: file path, currency, overwrite flag. Outputs: book object for a new GnuCash file. ```python from piecash import create_book, Account from decimal import Decimal # Create new SQLite book (in-memory or file-based) with create_book(currency="USD") as book: # Default root account is created automatically print(f"Root account: {book.root_account}") # Check if book has unsaved changes print(f"Is saved: {book.is_saved}") # Output: True book.root_account.description = "My financial records" print(f"Is saved: {book.is_saved}") # Output: False # Save changes book.save() print(f"Is saved: {book.is_saved}") # Output: True # Create persistent SQLite book with account structure with create_book("mybook.gnucash", currency="USD", overwrite=True) as book: USD = book.default_currency # Build account hierarchy book.root_account.children = [ Account( name="Assets", type="ASSET", commodity=USD, placeholder=True, children=[ Account(name="Checking", type="BANK", commodity=USD), Account(name="Savings", type="BANK", commodity=USD), ] ), Account( name="Expenses", type="EXPENSE", commodity=USD, placeholder=True, children=[ Account(name="Groceries", type="EXPENSE", commodity=USD), Account(name="Rent", type="EXPENSE", commodity=USD), ] ), ] book.save() ``` -------------------------------- ### Initialize Python Environment for Piecash Source: https://github.com/sdementen/piecash/blob/master/examples/ipython/piecash_dataframes.ipynb Sets up the Python environment by importing necessary libraries like pylab, matplotlib, sys, piecash, and pandas. It also manipulates the system path to include the local piecash directory. This is essential for running subsequent code that interacts with the piecash library. ```python %pylab %matplotlib inline import sys;sys.path.append("/home/sdementen/Projects/piecash/") from piecash import open_book import pandas as pd ``` -------------------------------- ### Accessing and Inspecting Piecash Accounts (Python) Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/existing_objects/account.rst Demonstrates how to open a GnuCash book, access the root account and its children, and retrieve various attributes of an account such as name, commodity, fullname, and type. This snippet requires the `piecash` library and a valid GnuCash file. ```python from piecash import open_book gnucash_books = "/path/to/your/gnucash/files/" book = open_book(gnucash_books + "simple_sample.gnucash", open_if_lock=True) # accessing the root_account root = book.root_account print(root) # accessing the first children account of a book acc = root.children[0] print(acc) # accessing attributes of an account print(f"Account name={acc.name}\n" f" commodity={acc.commodity.namespace}/{acc.commodity.mnemonic}\n" f" fullname={acc.fullname}\n" f" type={acc.type}") ``` -------------------------------- ### Open GnuCash Book with Piecash Source: https://github.com/sdementen/piecash/blob/master/examples/ipython/piecash_dataframes.ipynb Demonstrates how to open a GnuCash book file using the `open_book` function from the piecash library. The `open_if_lock` parameter is set to `True` to allow opening the book even if a lock file exists. This function returns a book object that can be used to access financial data. ```python # open some book with random data b = open_book("/home/sdementen/Projects/piecash/gnucash_books/book_schtx.gnucash", open_if_lock=True) ``` -------------------------------- ### Manage Business Objects (Customers, Vendors, Invoices) Source: https://context7.com/sdementen/piecash/llms.txt Shows how to work with business-related objects in Piecash, including creating new customers and vendors with addresses, querying existing business entities, and accessing invoice details. It demonstrates modifying the book by adding new entities and saving changes. This requires write access to the GnuCash file. ```python from piecash import open_book, Customer, Vendor, Address, Invoice from datetime import datetime with open_book("business.gnucash", readonly=False, open_if_lock=True) as book: USD = book.default_currency # Create customer with address customer = Customer( name="Acme Corporation", currency=USD, address=Address( name="Acme Corp", addr1="123 Business St", addr2="Suite 100", addr3="", addr4="", phone="555-1234", email="billing@acme.com" ), notes="Premium customer since 2020" ) book.add(customer) # Create vendor vendor = Vendor( name="Office Supplies Inc", currency=USD, address=Address( name="Office Supplies Inc", addr1="456 Supply Ave", phone="555-5678", email="orders@supplies.com" ) ) book.add(vendor) # Query business entities all_customers = list(book.customers) active_vendors = [v for v in book.vendors if v.active] # Access invoices all_invoices = list(book.invoices) for invoice in all_invoices: print(f"Invoice {invoice.id}: {invoice.notes}") print(f"Posted: {invoice.date_posted}") print(f"Entries: {len(invoice.entries)}") book.save() ``` -------------------------------- ### Forward ADB Port for SSH Tunneling Source: https://github.com/sdementen/piecash/blob/master/docs/source/android.rst Forwards the ADB port to a local port on the laptop, creating a tunnel that allows SSH access to the Android device through localhost. This is part of the USB Debugging setup. ```bash adb forward tcp:8022 tcp:8022 && ssh localhost -p 8022 ``` -------------------------------- ### Create Book and ISO Currency with Piecash Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/new_objects/create_commodity.rst This snippet shows how to initialize a new Piecash book in memory with a specified currency (EUR) and then create a new ISO currency (USD) using a factory function. The created currency object must be manually added to the book's session. ```python from piecash import create_book, Commodity, factories # create a book (in memory) with some currency book = create_book(currency="EUR") print(book.commodities) # creating a new ISO currency (if not already available in s.commodities) (warning, object should be manually added to session) USD = factories.create_currency_from_ISO("USD") book.add(USD) # add to session ``` -------------------------------- ### Create In-Memory SQLite Book Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/new_objects/create_book.rst Creates a new GnuCash book entirely in memory using SQLite. This is useful for testing and temporary operations as no file is persisted. It requires no external dependencies beyond the `piecash` library itself. ```python import piecash book = piecash.create_book() ``` -------------------------------- ### Create Bitcoin Commodity with Piecash Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/new_objects/create_commodity.rst This snippet demonstrates how to create a Bitcoin commodity (XBT) using the Commodity constructor. It sets the namespace to 'CURRENCY', provides a mnemonic and fullname, and specifies the fraction, noting a GnuCash limitation of a maximum of 6 digits after the comma. The created commodity must be added to the book's session. ```python # create a bitcoin currency (warning, max 6 digits after comma, current GnuCash limitation) XBT = Commodity(namespace="CURRENCY", mnemonic="XBT", fullname="Bitcoin", fraction=1000000) book.add(XBT) # add to session XBT ``` -------------------------------- ### Create New Account in Piecash (Python) Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/new_objects/create_account.rst This snippet shows how to create a new account in a Piecash book. It includes creating a placeholder account and a detailed sub-account. It requires the 'piecash' library and assumes a book object is already created. ```python from piecash import create_book, Account book = create_book(currency="EUR") # retrieve the default currency EUR = book.commodities.get(mnemonic="EUR") # creating a placeholder account acc = Account(name="My account", type="ASSET", parent=book.root_account, commodity=EUR, placeholder=True,) # creating a detailed sub-account subacc = Account(name="My sub account", type="BANK", parent=acc, commodity=EUR, commodity_scu=1000, description="my bank account", code="FR013334...",) book.save() book.accounts ``` -------------------------------- ### Create File-Based SQLite Book Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/new_objects/create_book.rst Creates a new GnuCash book persisted to a SQLite file. The function can accept the filename directly or a connection URI. An optional `overwrite` argument can be used to replace an existing file. The default currency is EUR, but can be specified. ```python book = piecash.create_book("example_file.gnucash") ``` ```python book = piecash.create_book(sqlite_file="example_file.gnucash", overwrite=True) ``` ```python book = piecash.create_book(uri_conn="sqlite:///example_file.gnucash", overwrite=True) ``` ```python book = piecash.create_book(sqlite_file="example_file.gnucash", currency="USD", overwrite=True) ``` ```python book = piecash.create_book(sqlite_file="example_file.gnucash", overwrite=True) ``` -------------------------------- ### Access GnuCash Objects via SQLAlchemy in Piecash Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/existing_objects/open_book.rst Shows how advanced users can access GnuCash book elements through SQLAlchemy queries on the underlying session object. This allows for complex data retrieval using SQL-like syntax. ```python # retrieve underlying SQLAlchemy session object session = book.session # get all account with name >= "T" print(session.query(Account).filter(Account.name>="T").all()) # display underlying query print(str(session.query(Account).filter(Account.name>="T"))) ``` -------------------------------- ### Export GnuCash Data to CSV using Piecash CLI Source: https://context7.com/sdementen/piecash/llms.txt Demonstrates exporting various data types like prices, customers, and vendors from a GnuCash file to CSV format using the piecash command-line interface. It also shows how to direct output to stdout if the --output option is not specified. ```bash piecash export mybook.gnucash prices --output prices.csv piecash export mybook.gnucash customers --inactive --output customers.csv piecash export mybook.gnucash vendors --output vendors.csv piecash export mybook.gnucash prices > prices.csv ``` -------------------------------- ### Create Stock Account Structure with Piecash Python Factory Source: https://context7.com/sdementen/piecash/llms.txt This Python code snippet demonstrates using the `create_stock_accounts` factory function from piecash to automatically set up a complete stock tracking structure within a GnuCash file. It involves creating a stock commodity and then using the factory to generate corresponding asset and income accounts. ```python from piecash import open_book, factories from piecash.core.factories import create_stock_accounts with open_book("investment.gnucash", readonly=False, open_if_lock=True) as book: # Create stock commodity stock = factories.create_stock_from_symbol("AAPL", book=book) # Get parent accounts broker = book.accounts(fullname="Assets:Brokerage") income = book.accounts(fullname="Income") # Create complete stock account structure # Creates: Assets:Brokerage:AAPL # Income:Dividend Income:AAPL, Income:Cap Gain (Long):AAPL, etc. stock_account, income_accounts = create_stock_accounts( cdty=stock, broker_account=broker, income_account=income, income_account_types="D/CL/CS/I" # Dividend/CapGainLong/CapGainShort/Interest ) print(f"Stock account: {stock_account.fullname}") for acc in income_accounts: print(f"Income account: {acc.fullname}") book.save() ``` -------------------------------- ### Command Line Export Tools Source: https://context7.com/sdementen/piecash/llms.txt This section indicates the availability of command-line interface (CLI) tools within Piecash for exporting data. These tools allow users to perform data exports without writing Python code, offering a convenient alternative for quick data extraction. ```bash ``` -------------------------------- ### Generate API Documentation with Sphinx-APIDoc Source: https://github.com/sdementen/piecash/blob/master/DEVELOPER.rst Generates reStructuredText files for API documentation from Python modules. This command should be run from the docs/source/doc directory. ```bash sphinx-apidoc -o . ../../piecash ``` -------------------------------- ### Manage Accounts in Python Source: https://context7.com/sdementen/piecash/llms.txt Demonstrates creating, querying, and manipulating account hierarchies within a GnuCash file. This code requires the piecash library and operates on a specified book. It involves account types, parent-child relationships, and balance calculations. ```python from piecash import open_book, Account, ACCOUNT_TYPES with open_book("mybook.gnucash", readonly=False, open_if_lock=True) as book: USD = book.default_currency # Get parent account assets = book.accounts(fullname="Assets") # Create new account under parent new_account = Account( name="Investment Account", type="BANK", commodity=USD, parent=assets, description="Long-term investments", code="1050", placeholder=False ) # Query account by different attributes account_by_name = book.accounts(name="Checking") account_by_fullname = book.accounts(fullname="Assets:Checking") # Get all accounts of specific type all_accounts = list(book.accounts) expense_accounts = [acc for acc in book.accounts if acc.type == "EXPENSE"] # Calculate account balance (including children if recurse=True) balance = assets.get_balance(recurse=True, natural_sign=True) print(f"Total assets: {balance}") # Get balance at specific date from datetime import date balance_at_date = assets.get_balance(at_date=date(2024, 12, 31)) # Access account relationships print(f"Parent: {new_account.parent.name}") print(f"Children: {[child.name for child in assets.children]}") print(f"Full path: {new_account.fullname}") book.save() ``` -------------------------------- ### Retrieve All Invoices from Piecash Book (Python) Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/existing_objects/invoices.rst This snippet demonstrates how to open a Piecash book and retrieve a list of all invoices. It iterates through the 'invoices' attribute of the book object. Ensure the 'gnucash_books' path is correctly set and the specified book file exists. ```python from piecash import open_book # Assuming gnucash_books is a defined path to your GnuCash files gnucash_books = "/path/to/your/gnucash/files/" book = open_book(gnucash_books + "invoices.gnucash", open_if_lock=True) # all invoices for invoice in book.invoices: print(invoice) ``` -------------------------------- ### Release New Version with Standard Python Tools Source: https://github.com/sdementen/piecash/blob/master/DEVELOPER.rst Steps for releasing a new version of Piecash without Gitflow. Involves updating metadata, changelog, tagging the release, and uploading the distribution to PyPI using Twine. ```bash 1. update metadata.py 2. update changelog 3. tag MM.mm.pp 4. twine upload dist/* --repository piecash ``` -------------------------------- ### Accessing Commodities and Prices in Piecash Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/existing_objects/commodity.rst This snippet demonstrates how to retrieve a list of all commodities from a Piecash book and access their attributes. It also shows how to iterate through the prices associated with each commodity, displaying their date, value, and currency. ```python from piecash import open_book gnucash_books = "/path/to/your/gnucash/books/" book = open_book(gnucash_books + "book_prices.gnucash", open_if_lock=True) # all commodities print(book.commodities) cdty = book.commodities[0] # accessing attributes of a commodity print("Commodity namespace={cdty.namespace}\ mnemonic={cdty.mnemonic}\ cusip={cdty.cusip}\ fraction={cdty.fraction}".format(cdty=cdty)) # loop on the prices for cdty in book.commodities: for pr in cdty.prices: print("Price date={pr.date}" " value={pr.value} {pr.currency.mnemonic}/{pr.commodity.mnemonic}".format(pr=pr)) ``` -------------------------------- ### Access GnuCash Objects via Object Model in Piecash Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/existing_objects/open_book.rst Illustrates accessing GnuCash book elements using the object model, navigating from the book object to related accounts and commodities. This method emphasizes relationships between objects. ```python book = open_book(gnucash_books + "default_book.gnucash") # accessing the root_account print(book.root_account) # looping through the children accounts of the root_account for acc in book.root_account.children: print(acc) # accessing children accounts by name, index, and type root = book.root_account assets = root.children(name="Assets") cur_assets = assets.children[0] cash = cur_assets.children(type="CASH") print(cash) # get the commodity of an account commo = cash.commodity print(commo) # get first ten accounts linked to the commodity commo for acc in commo.accounts[:10]: print(acc) ``` -------------------------------- ### Create Custom Commodities with Piecash Source: https://github.com/sdementen/piecash/blob/master/docs/source/tutorial/new_objects/create_commodity.rst This snippet illustrates creating custom commodities using the Commodity constructor. It shows how to create a 'Reward miles' commodity without specifying the book initially, requiring manual addition to the session. It also demonstrates creating a 'Unicorn hugs' commodity by passing the book object directly to the constructor. ```python # creating commodities using the constructor # (warning, object should be manually added to session if book kwarg is not included in constructor) # create a special "reward miles" Commodity using the constructor without book kwarg miles = Commodity(namespace="LOYALTY", mnemonic="Miles", fullname="Reward miles", fraction=1000000) book.add(miles) # add to session # create a special "unicorn hugs" Commodity using the constructor with book kwarg unhugs = Commodity(namespace="KINDNESS", mnemonic="Unhugs", fullname="Unicorn hugs", fraction=1, book=book) USD, miles, unhugs ``` -------------------------------- ### Iterate Through Accounts in Piecash Source: https://github.com/sdementen/piecash/blob/master/docs/source/doc/doc.rst This Python snippet demonstrates how to iterate through all accounts in a Piecash book. It assumes the 'book' object is already initialized. The output lists each account's representation. ```python for account in book.accounts: print(account) ```