Creating accounts and transactions and postings programatically

86 views
Skip to first unread message

Morpheous

unread,
Mar 30, 2023, 1:53:20 PM3/30/23
to Beancount

I am using beancount 2.3.5 and I am trying to write a proof of concept file that does the following:

  1. Creates a simple chart of accounts
  2. Posts sample transactions into ledgers using double entry

This is my code:

from datetime import datetime
from decimal import Decimal as
import beancount.core.data as data 
line_number = 42 

metadata = data.new_metadata(filename='./myfile.beancount', lineno=line_number) 

# define accounts 
accounts = ["Assets:Bank", "Expenses:Groceries"

# create postings 
posting1 = data.Posting(accounts[0], data.Amount(D('1000'), 'USD'), None, None, None, meta=metadata) 
posting2 = data.Posting(accounts[1], data.Amount(D('200'), 'USD'), None, None, None, meta=metadata) 

# create transactions 
transaction1 = data.Transaction( meta = metadata, date = datetime.strptime("2022-03-29", '%Y-%m-%d'), flag = "*", payee = "Bob's Grocery Store", narration = "Groceries for the week", tags = set(), links = set(), postings = [posting1, posting2] )


After I run the code, I expect to see a newly created file myfile.beancount with the above transactions in it. However, no file is generated.

I suspect that I might have to mark the accounts as open first, but I can't see anywhere in the documentation (or a function/method in the source code) that provides a clean entrypoint to do that.

How do I modify this code so that it creates the file and correctly posts the transactions to the file?

Red S

unread,
Mar 30, 2023, 7:56:19 PM3/30/23
to Beancount
Beancount is primarily designed to read+process input files, which is different from what you're attempting (create+write). May I ask what your end goal is?

You can create and write, which is what the importers do. Look at extract.py, which will show you how to do this. The main problem above is, nowhere are you actually printing output to a file.

David Avraamides

unread,
Apr 4, 2023, 6:45:52 PM4/4/23
to Beancount
Just add these lines to your script (the last one at the end):
from beancount.parser import printer
printer.print_entry(transaction1)

And the script will output:
2022-03-29 00:00:00 * "Bob's Grocery Store" "Groceries for the week"
  Assets:Bank         1000 USD
  Expenses:Groceries   200 USD

Just a note - I use the helpers in the data module to create the postings like this:
    data.create_simple_posting(entry, main_account, number.D(f"{tx.amount:.2f}"), "USD")

This adds the posting to the entry (transaction1 in your script) and also returns the posting as a convenience, if you need it.

I learned a LOT by digging through Red S's excellent code!
Reply all
Reply to author
Forward
0 new messages