Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ledger to Beancount
#!/usr/bin/python
import ledger
import sys
import re
def account_name(post):
account = post.account.fullname().replace(" ","").replace("(","").replace(")","").replace("'","")
return re.sub(r'\:(\d)',r':X\1', account)
def get_symbol(amount):
symbol = amount.commodity.symbol.replace("-","").replace("\"","").upper()
if symbol == "$":
symbol = "USD"
return symbol
filename = sys.argv[1]
accounts = set()
for xact in ledger.read_journal(filename).xacts():
for post in xact.posts():
account = account_name(post)
if account not in accounts:
print "%s open %s" % (xact.date, account)
accounts.add(account)
print "%s * \"%s\"" % (xact.date, xact.payee)
for post in xact.posts():
account = account_name(post)
symbol = get_symbol(post.amount)
if post.amount.has_annotation():
price = post.amount.price()
if post.amount.number() != 0:
price = price / post.amount.number()
psym = get_symbol(price)
print " %-50s %s %s @ %s %s" % (account, post.amount.number(), symbol, price.number(), psym)
else:
print " %-50s %s %s" % (account, post.amount.number(), symbol)
@brunov25

This comment has been minimized.

Show comment
Hide comment
@brunov25

brunov25 Apr 30, 2016

proposal: in line 9 insert a new line with
account = account.title() # to force capitalization of the account names

proposal: in line 9 insert a new line with
account = account.title() # to force capitalization of the account names

@jan-loeffler

This comment has been minimized.

Show comment
Hide comment
@jan-loeffler

jan-loeffler Mar 22, 2017

Does somebody know how to include tags ?

Does somebody know how to include tags ?

@glasserc

This comment has been minimized.

Show comment
Hide comment
@glasserc

glasserc Aug 21, 2017

This solution drops some features of my ledger file that I find quite important -- namely, comments and balance assertions. To address this, I wrote another ledger-to-beancount converter which works syntactically.

This solution drops some features of my ledger file that I find quite important -- namely, comments and balance assertions. To address this, I wrote another ledger-to-beancount converter which works syntactically.

@zacchiro

This comment has been minimized.

Show comment
Hide comment
@zacchiro

zacchiro Apr 6, 2018

You might want to check ledger2beancount, which is feature-complete w.r.t. ledger functionalities that can be faithfully supported in beancount.

zacchiro commented Apr 6, 2018

You might want to check ledger2beancount, which is feature-complete w.r.t. ledger functionalities that can be faithfully supported in beancount.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment