Ejemplo n.º 1
0
def main():
    args = parse_args()

    env = Environment(
        loader=FileSystemLoader(os.path.dirname(sys.argv[0])),
        autoescape=True)
    template = env.get_template('expenses.html.j2')

    journal = ledger.read_journal(args.file)

    balances_by_month = dict()  # {month: {account: balance}}
    accounts = set()
    for post in journal.query(args.query):
        if (args.commodity
                and post.amount.commodity.symbol != args.commodity):
            continue
        account = post.account.fullname()
        month = '%04d-%02d' % (
            post.xact.date.year, post.xact.date.month)
        payee = post.xact.payee
        amount = post.amount.to_double()
        accounts.add(account)
        if month not in balances_by_month:
            balances_by_month[month] = dict()
        if account not in balances_by_month[month]:
            balances_by_month[month][account] = 0
        balances_by_month[month][account] += amount

    with file_or_std(args.output, sys.stdout) as f:
        print(template.render(
                balances=sorted(list(balances_by_month.items())),
                keys=sorted(list(accounts))),
            file=f)
Ejemplo n.º 2
0
def read_ledger(filename, authors):
    journal = ledger.read_journal(filename)

    result = []

    for xact in journal.xacts():
        date = xact.date
        if hasattr(xact, 'note'):
            comment = xact.note
        else:
            comment = None

        for post in xact.posts():
            amount = post.amount

            if amount <= 0:
                continue

            author = None
            for test_author in authors:
                if post.has_tag(test_author):
                    author = test_author

            if author is None:
                continue
                # raise Exception('line '+str(post.pos.beg_line)+': post without author found')

            account = post.account

            # conversion to str for date: it's datetime.date otherwise
            result.append(
                LedgerEntry(int(amount), author, str(date), account, comment))
    return result
Ejemplo n.º 3
0
def run():
    journal = ledger.read_journal("./secret/ledger.dat")
    last_post = None
    amount = 0

    for post in journal.query(""):
        if last_post == None or post.date == last_post.date:
            if str(post.amount.commodity) != "£":
                continue
            amount = amount + post.amount
        else:
            print post.date, ",", amount
            amount = 0
        last_post = post

    df = pd.read_csv('./testing.csv')
    df['y'] = np.multiply(100, df['y'])

    m = Prophet()
    m.fit(df);

    forecast = m.predict(future)
    forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()

    m.plot(forecast);
    m.plot_components(forecast);
Ejemplo n.º 4
0
def run():
    journal = ledger.read_journal("./secret/ledger.dat")
    last_post = None
    amount = 0

    for post in journal.query(""):
        if last_post == None or post.date == last_post.date:
            if str(post.amount.commodity) != "£":
                continue
            amount = amount + post.amount
        else:
            print post.date, ",", amount
            amount = 0
        last_post = post

    df = pd.read_csv('./testing.csv')
    df['y'] = np.multiply(100, df['y'])

    m = Prophet()
    m.fit(df)

    forecast = m.predict(future)
    forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()

    m.plot(forecast)
    m.plot_components(forecast)
Ejemplo n.º 5
0
 def __init__(self, ledger_file=None, string_read=True):
     # sanity check for ledger python interface
     try:
         import ledger
     except ImportError:
         raise Exception("Ledger python interface not found!")
     if ledger_file is None:
         # TODO - better loading
         raise Exception
     else:
         if string_read:
             self.session = ledger.Session()
             self.journal = self.session.read_journal_from_string(open(ledger_file).read())
         else:
             self.journal = ledger.read_journal(ledger_file)
Ejemplo n.º 6
0
def main():
    args = parse_args()

    env = Environment(
        loader=FileSystemLoader(os.path.dirname(sys.argv[0])),
        autoescape=True)
    template = env.get_template('assets.html.j2')

    journal = ledger.read_journal(args.file)

    balances_by_date = {}  # type: Dict[date, Dict[AccountName, Dict[CommodityName, float]]]
    last_date = None
    balances = {}  # type: Dict[AccountName, Dict[CommodityName, float]]
    for post in sorted(journal.query(args.query),
                       key=lambda p: p.xact.date):
        date = post.xact.date
        account = post.account.fullname()
        commodity = post.amount.commodity.symbol.strip('"')
        amount = post.amount.to_double()

        if date != last_date:
            if last_date is not None:
                balances_by_date[last_date] = deepcopy(balances)
            last_date = date
        if account not in balances:
            balances[account] = {}  # type: Dict[CommodityName, float]
        if commodity not in balances[account]:
            balances[account][commodity] = 0
        balances[account][commodity] += amount
    balances_by_date[last_date] = deepcopy(balances)

    base_commodity = ledger.commodities.find(args.commodity)
    worth_by_date = {
        date: {
            account: amount_sum(date, base_commodity,
                (ledger.Amount('{:f}'.format(amount))
                       .with_commodity(ledger.commodities.find(commodity))
                 for commodity, amount in commodity_balances.items()))
            for account, commodity_balances in balances.items()}
        for date, balances in balances_by_date.items()}

    with file_or_std(args.output, sys.stdout) as f:
        print(template.render(
                balances=sorted(list(worth_by_date.items())),
                keys=sorted(list(balances.keys()))),
            file=f)
Ejemplo n.º 7
0
    def __init__(self, ledger_file=None, string_read=True):
        # sanity check for ledger python interface
        try:
            import ledger
        except ImportError:
            raise Exception("Ledger python interface not found!")
        if ledger_file is None:
            # TODO - better loading
            raise Exception
        else:
            if string_read:
                self.session = ledger.Session()
                self.journal = self.session.read_journal_from_string(
                    open(ledger_file).read())
            else:
                self.journal = ledger.read_journal(ledger_file)

        super(LedgerPython, self).__init__()
Ejemplo n.º 8
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    journal_file = settings['ledger_file']
    journal = ledger.read_journal(journal_file)

    config = Configurator(settings=settings)

    config.add_request_method(lambda _: journal,
                              'journal',
                              reify=True)

    config.include('pyramid_chameleon')
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('home', '/')
    config.add_route('transactions', '/api/transactions')
    config.add_route('transaction',  '/api/transactions/:id')
    config.scan()
    return config.make_wsgi_app()
Ejemplo n.º 9
0
def main():
    args = argparse.ArgumentParser(description=(
        'Ein Programm zur Berechnung und Anzeige der Abschreibung '
        'für Abnutzung (AfA) auf Grundlage eines ledger Journals.'))
    args.add_argument('file', help='ledger Journal')
    args.add_argument('-j',
                      '--jahr',
                      type=int,
                      default=date.today().year,
                      help='Jahr der Berechnung')
    args.add_argument('-k', '--konto', default='AfA', help='Konto für AfA')

    args = args.parse_args()

    try:
        journal = ledger.read_journal(args.file)
        posts = get_afa_posts(journal, args.konto, args.jahr)
        inventory = [
            InventoryItem(a, x, args.jahr) for a, x in get_inventory(posts)
        ]
        table = create_table(inventory, args.jahr)
        print(tabulate.tabulate(table, tablefmt='plain'))
    except ValueError as e:
        print(e.message)
Ejemplo n.º 10
0
### ### ###

# get year from 1st parameter or set last year as default
try:
    year = int(sys.argv[1])
except Exception, e:
    year = int(datetime.date.today().year - 1)

# get my ledger file, stored in the ENVIRONMENT_VARIABLE "LEDGER_FILE"
ledger_file = os.environ.get('LEDGER_FILE')
if not ledger_file:
    print 'LEDGER_FILE not set.'
    exit()

# make python ledger object from file
LED = ledger.read_journal(ledger_file)

# get the (german) afa table
if os.path.isfile(path_to_project + '/afa.txt'):

    # load the afa.txt file
    f = open(path_to_project + '/afa.txt')
    afa_file = f.read().splitlines()
    f.close()

    # get the variables from the file
    afa_table = {}
    for line in afa_file:
        if not '#' in line and line != '':
            try:
                tmp_key = line.split('=')[0].strip()
Ejemplo n.º 11
0
import ledger

eur = ledger.commodities.find_or_create('EUR')

total_eur = ledger.Amount("0.00 EUR")
total_gbp = ledger.Amount("0.00 GBP")
total = ledger.Amount("0.00 EUR")

for post in ledger.read_journal("test/regress/78AB4B87.dat").query("^income:"):
    print post.amount
    print post.amount.commodity
    if post.amount.commodity == "EUR":
        total_eur += post.amount
    elif post.amount.commodity == "GBP":
        total_gbp += post.amount

    a = post.amount.value(eur)
    if a:
        print "Total is presently: (%s)" % total
        print "Converted to EUR:   (%s)" % a
        total += a
        print "Total is now:       (%s)" % total
    else:
        print "Cannot convert '%s'" % post.amount
    print

print total
Ejemplo n.º 12
0
#!/usr/bin/python

from __future__ import print_function

import sys

try:
    import ledger
except:
    sys.exit('ledger extension missing, try installing python-ledger')


def dumpattrs(obj):
    for field in dir(obj):
        print('%s' % field, end='')
        try:
            print(': %s' % getattr(obj, field))
        except Exception as e:
            # a bunch of those fail, ignore
            print(': could not extract field! (%s)' % e)


for post in ledger.read_journal("ledger.lgr").query(""):
    print("Transferring %s to/from %s" % (post.amount, post.account))
    print('transaction fields:')
    dumpattrs(post)
    for func in ('xdata', ):
        print('%s: attrs:' % func, end='')
        xdata = getattr(post, func)()
        dumpattrs(xdata)
Ejemplo n.º 13
0
from __future__ import print_function

import ledger

eur = ledger.commodities.find_or_create('EUR')

total_eur = ledger.Amount("0.00 EUR")
total_gbp = ledger.Amount("0.00 GBP")
total = ledger.Amount("0.00 EUR")

for post in ledger.read_journal("test/regress/78AB4B87.dat").query("^income:"):
    print(post.amount)
    print(post.amount.commodity)
    if post.amount.commodity == "EUR":
        total_eur += post.amount
    elif post.amount.commodity == "GBP":
        total_gbp += post.amount

    a = post.amount.value(eur)
    if a:
        print("Total is presently: (%s)" % total)
        print("Converted to EUR:   (%s)" % a)
        total += a
        print("Total is now:       (%s)" % total)
    else:
        print("Cannot convert '%s'" % post.amount)
    print()

print(total)
Ejemplo n.º 14
0
def check_file(f):
    try:
        j = ledger.read_journal(f)
    except RuntimeError:
        raise abort(400)
Ejemplo n.º 15
0
import ledger

for post in ledger.read_journal("test/regress/4D9288AE.dat").query(
        "^expenses:"):
    print post.cost
Ejemplo n.º 16
0
 def __init__(self, project, ledger_filename):
     self.project = project
     self.founding_date = "2006/01/01"
     self.session = ledger.read_journal(ledger_filename)
Ejemplo n.º 17
0
import ledger, json, sys, re

prefix = ""
if len(sys.argv) == 2:
	prefix = sys.argv[1] + ":"
regex = re.compile(prefix)

bal = {}
journal = ledger.read_journal( "drewr.dat" )
for x in journal.xacts():
	for p in x.posts():
		name = p.account.fullname()
		if regex.match( name ):
			name = prefix + name[len(prefix):].split(":")[0]
			bal[name] = bal.get(name, 0) + p.amount

bal_list = bal.items()

out={}
out["nodes"] = [ { "name": n, "value": abs(v.to_long()), "group": 1 } for (n,v) in bal_list ]
print json.dumps( out )

Ejemplo n.º 18
0
    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(),
Ejemplo n.º 19
0

print "comment"
print "\nQuerying %r via the ledger bridge.\n" % filename

# Use's the ledger python bridge to read from a ledger journal file.
# NOTE: ledger file must be sorted by date, via "ledger print --sort date"
#
# Each posting is broken into a list of strings, s.
# s[0] is date, s[1] is amount, s[2] unit, s[3] price, s[4] account
# "lots" is a list of s strings.
#

lots = []

for post in ledger.read_journal(filename).query(query):
    s = "%s %s, %s" % (post.date, post.amount, post.account)
    s = s.split(' ')
    if len(s) == 9:
        s[3] = "%s %s" % (s[3], s[4])
        del s[4:8]
    if len(s) == 7:
        s[3] = "%s %s" % (s[3], s[4])
        del s[4]
        del s[4]
    elif len(s) == 4:
        s.insert(3, "{1.00000000 BTC}")
    lots.append(s)

# Creates lists for cryptocurrency holdings, a list "stack" to hold
# whichever cryptocurrency is actively being reduced, and a "reduce_stack"
Ejemplo n.º 20
0
import ledger
journal = ledger.read_journal(" LEDGER FILE PATH HERE  ")
print """<html>
<head>
	<title>Rental Ledger</title>
	<link rel="stylesheet" href="javascript/jquery.tablesorter/themes/blue/style.css" type="text/css" id="" media="print, projection, screen" />
	<script type="text/javascript" src="javascript/jquery.js"></script> 
	<script type="text/javascript" src="javascript/jquery.tablesorter/jquery.tablesorter.js"></script>
	<script type="text/javascript" id="js">
		$(document).ready(function() {
			// call the tablesorter plugin
			$("table").tablesorter();
			$('#bill').hide();
			
		}); 
	</script>
	<style type="text/css">
		.date {
			width: 75px;
		}
		.house {
			width: 75px;
		}
		.reconciled {
			width: 20px;
		}
		.checknum {
			width: 50px;
		}
		.payee {
			width: 280px;
Ejemplo n.º 21
0
import ledger

for post in ledger.read_journal('test/regress/xact_code.dat').query(
        'expenses'):
    print post.xact.code
Ejemplo n.º 22
0
def query_journal(q):
    journal = ledger.read_journal(journal_file())
    return journal.query(q)
Ejemplo n.º 23
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import print_function, unicode_literals

import ledger

for post in ledger.read_journal(__file__.replace(".py", "_py.test")).query("income"):
  print(unicode(post.tag("Reference")))
Ejemplo n.º 24
0
def journal():
    return ledger.read_journal('tests/data/single_transaction.journal')
Ejemplo n.º 25
0
import re
import string
import datetime
import copy
import pprint
import inspect
import traceback

if len(sys.argv) < 4:
    print "must be run via `ledger python ledgercalc.py <journalfile> start_year end_year <commandfile>...`"
    sys.exit(1)

##### ledger prep #####

# read in the journal file
journal = ledger.read_journal(sys.argv[1])

# create a USD commodity
comms = ledger.commodities
usd = comms.find_or_create('$')

# create dates for start/endpoint
start = datetime.date(int(sys.argv[2]), 1, 1)
end = datetime.date(int(sys.argv[3]), 1, 1)

##### ledger functions #####


# find the balance for an account
def balance_acct(acct_name, start_d=None, end_d=None):
    total = ledger.Balance()
Ejemplo n.º 26
0
 def __init__(self, filename, effective_date=True):
     self.ledger = ledger
     self.journal = ledger.read_journal(filename)
     self.effective_date = effective_date
Ejemplo n.º 27
0
import re
import string
import datetime
import copy
import pprint
import inspect
import traceback

if len(sys.argv) < 4:
    print "must be run via `ledger python ledgercalc.py <journalfile> start_year end_year <commandfile>...`"
    sys.exit(1)

##### ledger prep #####

# read in the journal file
journal = ledger.read_journal(sys.argv[1])

# create a USD commodity
comms = ledger.commodities
usd = comms.find_or_create('$')

# create dates for start/endpoint
start = datetime.date(int(sys.argv[2]),1,1)
end = datetime.date(int(sys.argv[3]),1,1)

##### ledger functions #####

# find the balance for an account
def balance_acct(acct_name, start_d=None, end_d=None):
    total = ledger.Balance()
    if re.match(r"^[A-Za-z:_\-\ ]*$",acct_name):  # if the account name lacks re's
Ejemplo n.º 28
0
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)
Ejemplo n.º 29
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import print_function, unicode_literals

import sys
import ledger

for post in ledger.read_journal(__file__.replace(".py", "_py.test")).query("income"):
  reference = post.tag("Reference")
  if sys.version_info.major == 2:
      reference = unicode(reference)
  print(reference)
Ejemplo n.º 30
0
import ledger

for post in ledger.read_journal('test/regress/xact_code.dat').query('expenses'):
  print post.xact.code
Ejemplo n.º 31
0
#!/usr/bin/python

from __future__ import print_function

import sys

try:
    import ledger
except:
    sys.exit('ledger extension missing, try installing python-ledger')

def dumpattrs(obj):
    for field in dir(obj):
        print('%s' % field, end='')
        try:
            print(': %s' % getattr(obj, field))
        except Exception as e:
            # a bunch of those fail, ignore
            print(': could not extract field! (%s)' % e)
        
    
for post in ledger.read_journal("ledger.lgr").query(""):
        print("Transferring %s to/from %s" % (post.amount, post.account))
        print('transaction fields:')
        dumpattrs(post)
        for func in ('xdata',):
            print('%s: attrs:' % func, end='')
            xdata = getattr(post, func)()
            dumpattrs(xdata)
Ejemplo n.º 32
0
import ledger
import json
import sys

filename = sys.argv[1]
query = sys.argv[2]

transactions = []
last_xact = None
for match in ledger.read_journal(filename).query(query):
    if match.xact != last_xact:
        transaction = {}
        transaction['payee'] = match.xact.payee
        transaction['date'] = match.xact.date.strftime('%Y/%m/%d')

        if match.xact.code != None:
            transaction['code'] = match.xact.code

        if match.xact.note != None:
            transaction['note'] = match.xact.note.strip()

        if match.xact.aux_date != None:
            transaction['effective_date'] = match.xact.aux_date.strftime('%Y/%m/%d')

        if str(match.xact.state) == 'Cleared':
            transaction['cleared'] = True
            transaction['pending'] = False
        elif str(match.xact.state) == 'Pending':
            transaction['cleared'] = False
            transaction['pending'] = True
        else: