How to use the beancount.core.data.Transaction function in beancount

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 siddhantgoel / beancount-dkb / beancount_dkb / ec.py View on Github external
)
                        )
                else:
                    description = '{} {}'.format(
                        line['Buchungstext'],
                        line['Verwendungszweck'] or line['Kontonummer'],
                    )

                    postings = [
                        data.Posting(
                            self.account, amount, None, None, None, None
                        )
                    ]

                    entries.append(
                        data.Transaction(
                            meta,
                            date,
                            self.FLAG,
                            line['Auftraggeber / Begünstigter'],
                            description,
                            data.EMPTY_SET,
                            data.EMPTY_SET,
                            postings,
                        )
                    )

                line_index += 1

            # Closing Balance
            meta = data.new_metadata(file_.name, closing_balance_index)
            entries.append(
github beancount / beancount / experiments / sharing / extract_sheets.py View on Github external
if not number_str:
        logging.warning("Zero amount: %s", row)

    account = default_account
    if coltypes.get(csv.Col.ACCOUNT):
        account = row[coltypes.get(csv.Col.ACCOUNT)] or account

    payee = None
    if coltypes.get(csv.Col.PAYEE):
        payee = row[coltypes.get(csv.Col.PAYEE)]
    narration = None
    if coltypes.get(csv.Col.NARRATION):
        narration = row[coltypes.get(csv.Col.NARRATION)]

    postings = []
    txn = data.Transaction(data.new_metadata(docid, index),
                           date,
                           flags.FLAG_OKAY,
                           payee,
                           narration,
                           data.EMPTY_SET,
                           data.EMPTY_SET,
                           postings)
    units = amount.Amount(number, 'USD')
    postings.append(data.Posting(account, units, None, None, None, None))
    postings.append(data.Posting(inflows_account, -units, None, None, None, None))
    return txn
github beancount / beancount / src / python / beancount / sources / thinkorswimforex.py View on Github external
##print('RUNNING_BALANCE', running_balance, balance)
        assert(abs(running_balance - balance) <= Decimal('0.01'))

        amount = balance - prev_balance
        assert(abs(row_amount - amount) <= Decimal('0.01'))

        # Check some invariants.
        assert row.commissions == '--'

        if row.type not in ('BAL',):

            # Create a new transaction.
            narration = re.sub('[ ]+', ' ', "({0.type}) {0.description}".format(row).replace('\n', ' ')).strip()
            fileloc = data.FileLocation(filename, index)
            links = set([row.ref] if row.ref != '--' else [])
            entry = Transaction(fileloc, date, flags.FLAG_IMPORT, None, narration, None, links, [])

            if row.type in ('FND', 'WDR'):
                create_simple_posting(entry, config['transfer'], amount, cash_currency)
                create_simple_posting(entry, config['asset_cash'], -amount, cash_currency)

            elif row.type == 'TRD':
                create_simple_posting(entry, config['asset_cash'], amount, cash_currency)
                create_simple_posting(entry, config['pnl'], -amount, cash_currency)

            elif row.type == 'ROLL':
                if amount != ZERO:
                    create_simple_posting(entry, config['asset_cash'], amount, cash_currency)
                    create_simple_posting(entry, config['pnl'], -amount, cash_currency)

            if entry.postings:
                new_entries.append(entry)
github beancount / beancount / beancount / parser / grammar.py View on Github external
# with a non-zero balance, it'll get caught below in the booking code.
        #
        # # Detect when a transaction does not have at least two legs.
        # if postings is None or len(postings) < 2:
        #     self.errors.append(
        #         ParserError(meta,
        #                     "Transaction with only one posting: {}".format(postings),
        #                     None))
        #     return None

        # If there are no postings, make sure we insert a list object.
        if postings is None:
            postings = []

        # Create the transaction.
        return Transaction(meta, date, chr(flag),
                           payee, narration, tags, links, postings)
github jbms / beancount-import / beancount_import / matching.py View on Github external
def fix_meta_in(obj):
        if isinstance(obj, Transaction):
            return obj._replace(
                meta=fix_meta(obj.meta),
                postings=[fix_meta_in(p) for p in obj.postings])
        else:
            return obj._replace(meta=fix_meta(obj.meta))
github zsxsoft / my-beancount-scripts / modules / imports / yuebao.py View on Github external
def parse(self):
        table = self.table
        rows = table.nrows
        for i in range(5, rows - 4):
            row = table.row_values(i)
            time = datetime.datetime(
                *xlrd.xldate_as_tuple(table.cell_value(rowx=i, colx=0), self.book.datemode))
            print("Importing {} price = {} balance = {}".format(
                time, row[2], row[3]))
            meta = {}
            amount = float(row[1])

            entry = Transaction(
                meta,
                date(time.year, time.month, time.day),
                '*',
                '余额宝',
                '余额宝',
                data.EMPTY_SET,
                data.EMPTY_SET, []
            )

            if not row[2] in incomes:
                amount = -amount

            if self.deduplicate.find_duplicate(entry, amount, None, Account余额宝):
                print(
                    "Unknown transaction for {}, check if Alipay transaction exists.".format(time))
github jbms / beancount-import / beancount_import / source / mint.py View on Github external
def _make_import_result(mint_entry: MintEntry) -> ImportResult:
    transaction = Transaction(
        meta=None,
        date=mint_entry.date,
        flag=FLAG_OKAY,
        payee=None,
        narration=mint_entry.source_desc,
        tags=EMPTY_SET,
        links=EMPTY_SET,
        postings=[
            Posting(
                account=mint_entry.account,
                units=mint_entry.amount,
                cost=None,
                price=None,
                flag=None,
                meta=collections.OrderedDict(
                    source_desc=mint_entry.source_desc,
github beancount / beancount / src / python / beancount / sources / oanda.new.py View on Github external
#     # raise SystemExit

        # Save the balance to compute the next one.
        prev_balance = balance

        # Create the transaction.
        fileloc = data.FileLocation(filename, lineno)
        narration = '{} - {}'.format(txntype, obj['currency_pair'], obj['ticket'])

        # Create links.
        links = set([LINK_FORMAT.format(obj['ticket'].strip())])
        link = obj['transaction_link'].strip()
        if link:
            links.add(LINK_FORMAT.format(link))

        entry = Transaction(fileloc, date, flags.FLAG_IMPORT, None, narration, None, links, [])

        # FIXME: Add the rates for transfers
        oanda_add_posting(entry, config['asset'], change, currency)
        if pnl != ZERO:
            oanda_add_posting(entry, config['pnl'], -pnl, currency)
        if interest != ZERO:
            oanda_add_posting(entry, config['interest'], -interest, currency)
        if other is not None:
            oanda_add_posting(entry, other_account, -other, currency)

        if len(entry.postings) < 2:
            continue

        new_entries.append(entry)

        diff = balance - computed_balance
github zsxsoft / my-beancount-scripts / modules / imports / wechat.py View on Github external
# flag = "*"
            amount_string = row['金额(元)'].replace('¥', '')
            amount = float(amount_string)

            if row['商户单号'] != '/':
                meta['shop_trade_no'] = row['商户单号']

            if row['备注'] != '/':
                meta['note'] = row['备注']

            meta = data.new_metadata(
                'beancount/core/testing.beancount',
                12345,
                meta
            )
            entry = Transaction(
                meta,
                date(time.year, time.month, time.day),
                '*',
                row['交易对方'],
                row['商品'],
                data.EMPTY_SET,
                data.EMPTY_SET, []
            )

            status = row['当前状态']

            if status == '支付成功' or status == '朋友已收钱' or status == '已全额退款' or '已退款' in status:
                if '转入零钱通' in row['交易类型']:
                    entry = entry._replace(payee='')
                    entry = entry._replace(narration='转入零钱通')
                    data.create_simple_posting(
github beancount / beancount / beancount / ops / summarize.py View on Github external
conversion_cost_balance = conversion_balance.reduce(convert.get_cost)
    if conversion_cost_balance.is_empty():
        return entries

    # Calculate the index and the date for the new entry. We want to store it as
    # the last transaction of the day before.
    if date is not None:
        index = bisect_key.bisect_left_with_key(entries, date, key=lambda entry: entry.date)
        last_date = date - datetime.timedelta(days=1)
    else:
        index = len(entries)
        last_date = entries[-1].date

    meta = data.new_metadata('', -1)
    narration = 'Conversion for {}'.format(conversion_balance)
    conversion_entry = Transaction(meta, last_date, flags.FLAG_CONVERSIONS,
                                   None, narration, data.EMPTY_SET, data.EMPTY_SET, [])
    for position in conversion_cost_balance.get_positions():
        # Important note: Set the cost to zero here to maintain the balance
        # invariant. (This is the only single place we cheat on the balance rule
        # in the entire system and this is necessary; see documentation on
        # Conversions.)
        price = amount.Amount(ZERO, conversion_currency)
        neg_pos = -position
        conversion_entry.postings.append(
            data.Posting(conversion_account, neg_pos.units, neg_pos.cost,
                         price, None, None))

    # Make a copy of the list of entries and insert the new transaction into it.
    new_entries = list(entries)
    new_entries.insert(index, conversion_entry)