Modify postings in transactions and update the input beancount file

141 views
Skip to first unread message

Saglara S

unread,
Mar 15, 2024, 6:47:56 PM3/15/24
to Beancount
I want to add and modify postings in transactions based on a lookup table (search string : account). The script here does the job and will print out the modified transactions. 

But how on earth to modify / update the transactions in the input file accordingly?

import json
import re
from beancount import loader
from beancount.core import data
from beancount.parser import printer

# Define the filename and load the Beancount file
filename = "comdirect-mitko.beancount"
entries, errors, options = loader.load_file(filename)

# Define the JSON lookup table
lookup_table = {
    "AGIP": "Assets:Test",
    "PayPal Europe": "Assets:Transfer:Paypal",
    # Add more entries as needed
}

# Loop over each key-value pair in the lookup table
for search_string, posting_account in lookup_table.items():
    for entry in entries:
        if isinstance(entry, data.Transaction):
            if re.search(search_string, (entry.payee or entry.narration)):
                posting = data.Posting(
                    posting_account,
                    None,
                    None,
                    None,
                    None,
                    None,
                )
                if len(entry.postings) == 1:
                    entry.postings.append(posting)
                elif len(entry.postings) == 2:
                    entry.postings[1] = posting
                printer.print_entry(entry)  # Print the modified entry

Martin Blais

unread,
Mar 15, 2024, 7:58:57 PM3/15/24
to bean...@googlegroups.com
There's a far fetched idea for the next version to augment the parser such that it is possible to completely reverse the process and regenerate the input file with modifications, but it's just a fanciful idea at this point.


--
You received this message because you are subscribed to the Google Groups "Beancount" group.
To unsubscribe from this group and stop receiving emails from it, send an email to beancount+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/beancount/11a9fd9a-f6b4-42d6-9851-8c9ef21c71acn%40googlegroups.com.
Message has been deleted

Red S

unread,
Mar 16, 2024, 2:43:55 AM3/16/24
to Beancount

You can do this with autobean-refactor.

Note that if you did it with Beancount as it currently us, like with the code you posted, it would be writing out processed entries. I.e., entries that have been through interpolation, plugins, and such. In most cases, that is not what you want.

Chary Chary

unread,
Mar 16, 2024, 6:30:33 AM3/16/24
to Beancount
I think I probably misunderstand the question.

Why is it not possible just to print entries in the new file?

printer.print_entries(entries, file=open("new_file.bean", "w", encoding="utf-8"))
Reply all
Reply to author
Forward
0 new messages