How to use beancount - 10 common examples

To help you get started, we’ve selected a few beancount examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github beancount / fava / tests / test_core_file.py View on Github external
def test_insert_entry_align(tmpdir):
    file_content = dedent(
        """
        2016-02-26 * "Uncle Boons" "Eating out alone"
            Liabilities:US:Chase:Slate                       -24.84 USD
            Expenses:Food:Restaurant                          24.84 USD

    """
    )
    samplefile = tmpdir.mkdir("fava_util_file3").join("example.beancount")
    samplefile.write(file_content)

    postings = [
        data.Posting(
            "Liabilities:US:Chase:Slate",
            amount.Amount(D("-10.00"), "USD"),
            None,
            None,
            None,
            None,
        ),
        data.Posting(
            "Expenses:Food",
            amount.Amount(D("10.00"), "USD"),
            None,
            None,
            None,
            None,
        ),
    ]
github beancount / fava / tests / test_serialisation.py View on Github external
"postings": postings,
    }

    txn = Transaction(
        {},
        datetime.date(2017, 12, 12),
        "*",
        "Test3",
        "asdfasd",
        frozenset(["tag"]),
        frozenset(["link"]),
        [],
    )
    create_simple_posting(txn, "Assets:ETrade:Cash", "100", "USD")
    txn.postings.append(
        Posting("Assets:ETrade:GLD", MISSING, None, None, None, None)
    )
    assert deserialise(json_txn) == txn

    with pytest.raises(KeyError):
        deserialise({})

    with pytest.raises(FavaAPIException):
        deserialise({"type": "NoEntry"})
github beancount / fava / tests / test_core_file.py View on Github external
)
    samplefile = tmpdir.mkdir("fava_util_file3").join("example.beancount")
    samplefile.write(file_content)

    postings = [
        data.Posting(
            "Liabilities:US:Chase:Slate",
            amount.Amount(D("-10.00"), "USD"),
            None,
            None,
            None,
            None,
        ),
        data.Posting(
            "Expenses:Food",
            amount.Amount(D("10.00"), "USD"),
            None,
            None,
            None,
            None,
        ),
    ]

    transaction = data.Transaction(
        {},
        datetime.date(2016, 1, 1),
        "*",
        "new payee",
        "narr",
        None,
        None,
        postings,
github beancount / fava / tests / test_budgets.py View on Github external
def test_budgets(load_doc):
    """
    2016-01-01 custom "budget" Expenses:Groceries "weekly" 100.00 CNY
    2016-06-01 custom "budget" Expenses:Groceries "weekly"  10.00 EUR"""
    entries, _, _ = load_doc
    budget = Budgets(entries)
    budgets = budget.budget('Expenses:Groceries', date(2016, 6, 1), date(2016, 6, 8)) # noqa
    assert budgets['CNY'] == Decimal(100)
    assert budgets['EUR'] == Decimal(10)
github siddhantgoel / beancount-dkb / tests / test_common.py View on Github external
def test_fmt_number_de():
    assert fmt_number_de('1') == Decimal(1)
    assert fmt_number_de('1,50') == Decimal(1.50)
    assert fmt_number_de('150') == Decimal(150)
    assert fmt_number_de('15,0') == Decimal(15)
    assert fmt_number_de('1234,0') == Decimal(1234)
github siddhantgoel / beancount-dkb / tests / test_common.py View on Github external
def test_fmt_number_de():
    assert fmt_number_de('1') == Decimal(1)
    assert fmt_number_de('1,50') == Decimal(1.50)
    assert fmt_number_de('150') == Decimal(150)
    assert fmt_number_de('15,0') == Decimal(15)
    assert fmt_number_de('1234,0') == Decimal(1234)
github beancount / beancount / experiments / docs / intro-doc / svg.py View on Github external
p.x_timeline_end *= 0.7
    p.x_width = p.x_timeline_end + p.x_margin + p.x_balance_width + p.x_margin
    p.x_timeline_before = 100
    draw_diagram(p, [sbalances[0:len(sbalances)//3]], 'svg1.html')


    p = Params()
    random.seed(args.seed+1)
    group_dict = groupby(balances, lambda item: item[0].split(':', 1)[0])
    group_dict['Equity'].reverse()
    groups = [group_dict[x] for x in 'Assets Liabilities Equity Income Expenses'.split()]
    draw_diagram(p, groups, 'svg5.html')

    random.seed(args.seed+1)
    p.draw_clearing = True
    draw_diagram(p, groups, 'svg6.html', scale_income=D('0.3'))

    random.seed(args.seed+1)
    p.draw_opening = True
    draw_diagram(p, groups, 'svg7.html')

    random.seed(args.seed+1)
    p.draw_before = False
    draw_diagram(p, groups, 'svg8.html')

    random.seed(args.seed+1)
    p.draw_after = False
    draw_diagram(p, groups, 'svg9.html')

    random.seed(args.seed+1)
    p.draw_close = True
    draw_diagram(p, groups, 'svgA.html')
github ghislainbourgeois / beancount_portfolio_allocation / beancount_portfolio_allocation / loader.py View on Github external
def load(bean, portfolio):
    entries, errors, options_map = loader.load_file(bean)

    if _missing_operating_currency(options_map):
        logging.error("Missing operating_currency")
        exit(1)

    targets = get_allocation_directives(entries, portfolio)

    allocations = get_allocations(entries, options_map, portfolio)

    total = allocations.total_invested_for_portfolio()

    return (targets, allocations, total)
github beancount / beancount / beancount / plugins / book_conversions.py View on Github external
"""
    logging.basicConfig(level=logging.INFO, format='%(levelname)-8s: %(message)s')
    parser = argparse.ArgumentParser(description=__doc__.strip())
    parser.add_argument('filename', help='Beancount input filename')

    oparser = parser.add_argument_group('Outputs')
    oparser.add_argument('-o', '--output', action='store',
                         help="Filename to output results to (default goes to stdout)")
    oparser.add_argument('-f', '--format', default='text',
                         choices=['text', 'csv'],
                         help="Output format to render to (text, csv)")

    args = parser.parse_args()

    # Load the input file.
    entries, errors, options_map = loader.load_file(args.filename)

    # Get the list of trades.
    trades = extract_trades(entries)

    # Produce a table of all the trades.
    columns = ('units currency cost_currency '
               'buy_date buy_price sell_date sell_price pnl').split()
    header = ['Units', 'Currency', 'Cost Currency',
              'Buy Date', 'Buy Price', 'Sell Date', 'Sell Price',
              'P/L']
    body = []
    for aug, red in trades:
        units = -red.posting.units.number
        buy_price = aug.posting.price.number
        sell_price = red.posting.price.number
        pnl = (units * (sell_price - buy_price)).quantize(buy_price)
github beancount / beancount / beancount / core / realization.py View on Github external
children of, or create under.
      account_name: A string, the name of the direct or indirect child leaf
        to get or create.
    Returns:
      A RealAccount instance for the child, or the default value, if the child
      is not found.
    """
    if not isinstance(account_name, str):
        raise ValueError
    components = account.split(account_name)
    path = []
    for component in components:
        path.append(component)
        real_child = real_account.get(component, None)
        if real_child is None:
            real_child = RealAccount(account.join(*path))
            real_account[component] = real_child
        real_account = real_child
    return real_account