Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python and GnuCash: Extract data from GnuCash files

I'm looking for information on how to read GnuCash files using python. I have read about this python-gnucash which provides Python bindings to the GnuCash library, but it takes a lot of work at the moment (e.g. dependencies, headers, etc.). The instructions are tailored for the Linux environment, and a rather old GnuCash version (2.0.x). I am running GnuCash 2.2.9. Though I can operate the Linux command line, I am running GnuCash on Windows XP.

My main objective is to read (no plans to write yet) my GnuCash files so that I can create my own visual dynamic reports using matplotlib and wxpython. I'm not yet in the mood to learn Scheme.

I hope someone can point me to a good start on this. As far as I know about GnuCash and Python, I think someone probably knows solutions of the following types:

  1. More recently updated documentation aside from this one from the GnuCash wiki
  2. Some workaround, like exporting to a certain file format for which there is a more mature Python library that can read it.

You guys might have better suggestions in addition to those mentioned.

like image 629
Kit Avatar asked Dec 01 '22 05:12

Kit


1 Answers

I published piecash, a python interface to SQL saved GnuCash books that uses SQLAlchemy as basis (https://github.com/sdementen/piecash).

With it you can easily access all the information contained in a book.

For instance, to iterate over all accounts in the book:

from piecash import open_book

# open a book
with open_book("some_book.gnucash", open_if_lock=True) as mybook:
    # iterate over all accounts of the book
    for account in mybook.accounts:
        print(account)

or to iterate over all the splits in the "Asset" account:

# open the book
with open_book("some_book.gnucash", open_if_lock=True) as mybook:
    # retrieve the account by its fullname
    asset = mybook.accounts(fullname="Asset")
    # iterate over all its splits
    for split in asset.splits:
        print(split)

Recent versions also allows to extract the split information directly to pandas DataFrames for easy plotting/analysis with

from piecash import open_book

# open a book
with open_book("some_book.gnucash", open_if_lock=True) as mybook:
    # extract all split information to a pandas DataFrame
    df = mybook.splits_df()

    # print for account "Asset" some information on the splits
    print(df.loc[df["account.fullname"] == "Asset",
                 ["transaction.post_date", "value"]])
like image 160
sdementen Avatar answered Dec 05 '22 17:12

sdementen