Skip to content

API reference

abacus.core

Core elements of a minimal double-entry accounting system.

Using this module you can:

  • create a chart of accounts using Chart class,
  • create Ledger from Chart,
  • post entries to Ledger,
  • generate trial balance, balance sheet and income statement.

Implemented in this module:

  • contra accounts — there can be a refunds account that offsets income:sales and depreciation account that offsets asset:ppe,
  • multiple entries — debit and credit several accounts in one transaction,
  • closing entries — proper closing of accounts at the accounting period end.

Assumptions and simplifications:

  1. no sub-accounts — there is only one level of account hierarchy in chart
  2. account names must be globally unique
  3. no cashflow statement
  4. one currency
  5. no checks for account non-negativity

Defining a chart

abacus.Chart dataclass

Chart of accounts.

Example:

chart = Chart(assets=["cash"], capital=["equity"])
Source code in abacus/core.py
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
@dataclass
class Chart:
    """Chart of accounts.

    Example:

    ```python
    chart = Chart(assets=["cash"], capital=["equity"])
    ```
    """

    income_summary_account: str = "_isa"
    retained_earnings_account: str = "retained_earnings"
    null_account: str = "_null"
    assets: list[str | Account] = field(default_factory=list)
    capital: list[str | Account] = field(default_factory=list)
    liabilities: list[str | Account] = field(default_factory=list)
    income: list[str | Account] = field(default_factory=list)
    expenses: list[str | Account] = field(default_factory=list)

    def __post_init__(self):
        self.validate()

    def validate(self) -> "Chart":
        a = list(self.to_dict().keys())
        b = [x[0] for x in self.dict_items()]
        if len(a) != len(b):
            raise AbacusError(
                [
                    "Chart should not contain duplicate account names.",
                    len(a),
                    len(b),
                    set(b) - set(a),
                ]
            )
        return self

    def to_dict(self) -> dict[str, Holder]:
        """Return a dictionary of account names and account types.
        Will purge duplicate names if found in chart.
        """
        return dict(self.dict_items())

    def dict_items(self):
        """Assign account types to account names."""
        yield from self.stream(self.assets, T.Asset)
        yield from self.stream(self.capital, T.Capital)
        yield self.retained_earnings_account, Regular(T.Capital)
        yield from self.stream(self.liabilities, T.Liability)
        yield from self.stream(self.income, T.Income)
        yield from self.stream(self.expenses, T.Expense)
        yield self.income_summary_account, Wrap(IncomeSummaryAccount)
        yield self.null_account, Wrap(NullAccount)

    def pure_accounts(self, xs: list[str | Account]) -> list[Account]:
        return [Account.from_string(x) for x in xs]

    def stream(self, items, t: T):
        for account in self.pure_accounts(items):
            yield account.name, Regular(t)
            for contra_name in account.contra_accounts:
                yield contra_name, Contra(t)

    def ledger(self, starting_balances: dict | None = None):
        return Ledger.new(self, AccountBalances(starting_balances))

abacus.core.Account dataclass

Source code in abacus/core.py
134
135
136
137
138
139
140
141
142
143
144
145
146
@dataclass
class Account:
    name: str
    contra_accounts: list[str] = field(default_factory=list)

    @staticmethod
    def from_string(s) -> "Account":
        if isinstance(s, str):
            return Account(s, [])
        return s

    def __str__(self):
        return self.name

Entries

abacus.core.Entry dataclass

Double entry with account name to be debited, account name to be credited and transaction amount.

Example:

entry = Entry(debit="cash", credit="equity", amount=20000)
Source code in abacus/core.py
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
@dataclass
class Entry:
    """Double entry with account name to be debited,
       account name to be credited and transaction amount.

    Example:

    ```python
    entry = Entry(debit="cash", credit="equity", amount=20000)
    ```
    """

    debit: str
    credit: str
    amount: Amount

    def to_json(self):
        return json.dumps(self.__dict__)

    @classmethod
    def from_string(cls, line: str):
        return cls(**json.loads(line))

abacus.core.CompoundEntry dataclass

An entry that affects several accounts at once.

Source code in abacus/core.py
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
@dataclass
class CompoundEntry:
    """An entry that affects several accounts at once."""

    debits: list[tuple[str, Amount]]
    credits: list[tuple[str, Amount]]

    def __post_init__(self):
        self.validate()

    def validate(self):
        """Assert sum of debit entries equals sum of credit entries."""
        if sum_second(self.debits) == sum_second(self.credits):
            return self
        else:
            raise AbacusError(["Invalid multiple entry", self])

    def to_entries(self, null_account_name: str) -> list[Entry]:
        """Return list of double entries that make up multiple entry.
        The double entries will correspond to null account.
        """
        a = [
            Entry(account_name, null_account_name, amount)
            for (account_name, amount) in self.debits
        ]
        b = [
            Entry(null_account_name, account_name, amount)
            for (account_name, amount) in self.credits
        ]
        return a + b

    @classmethod
    def from_balances(cls, chart: Chart, balances: AccountBalances) -> "CompoundEntry":
        ledger = chart.ledger()

        def is_debit(name):
            return isinstance(ledger.data[name], DebitAccount)

        def is_credit(name):
            return isinstance(ledger.data[name], CreditAccount)

        return cls(
            debits=[(name, b) for name, b in balances.items() if is_debit(name)],
            credits=[(name, b) for name, b in balances.items() if is_credit(name)],
        )

to_entries(null_account_name)

Return list of double entries that make up multiple entry. The double entries will correspond to null account.

Source code in abacus/core.py
683
684
685
686
687
688
689
690
691
692
693
694
695
def to_entries(self, null_account_name: str) -> list[Entry]:
    """Return list of double entries that make up multiple entry.
    The double entries will correspond to null account.
    """
    a = [
        Entry(account_name, null_account_name, amount)
        for (account_name, amount) in self.debits
    ]
    b = [
        Entry(null_account_name, account_name, amount)
        for (account_name, amount) in self.credits
    ]
    return a + b

validate()

Assert sum of debit entries equals sum of credit entries.

Source code in abacus/core.py
676
677
678
679
680
681
def validate(self):
    """Assert sum of debit entries equals sum of credit entries."""
    if sum_second(self.debits) == sum_second(self.credits):
        return self
    else:
        raise AbacusError(["Invalid multiple entry", self])

Processing entries

abacus.core.TAccount dataclass

Bases: ABC

T-account will hold amounts on debits and credit side.

Source code in abacus/core.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
@dataclass
class TAccount(ABC):
    """T-account will hold amounts on debits and credit side."""

    debits: list[Amount] = field(default_factory=list)
    credits: list[Amount] = field(default_factory=list)

    def debit(self, amount: Amount):
        """Add debit amount to account."""
        self.debits.append(amount)

    def credit(self, amount: Amount):
        """Add credit amount to account."""
        self.credits.append(amount)

    @abstractmethod
    def balance(self) -> Amount:
        """Return account balance."""

    @abstractmethod
    def transfer_balance(self, my_name: str, dest_name: str) -> "Entry":
        """Create an entry that transfers account balance from this account
        to destination account.

        This account name is `my_name` and destination account name is `dest_name`.
        """

    def condense(self):
        """Create a new account of the same type with only one value as account balance."""
        return self.empty().topup(self.balance())

    def empty(self):
        """Create a new empty account of the same type."""
        return self.__class__()

    def topup(self, balance):
        """Add starting balance to a proper side of account."""
        match self:
            case DebitAccount(_, _):
                self.debit(balance)
            case CreditAccount(_, _):
                self.credit(balance)
        return self

balance() abstractmethod

Return account balance.

Source code in abacus/core.py
164
165
166
@abstractmethod
def balance(self) -> Amount:
    """Return account balance."""

condense()

Create a new account of the same type with only one value as account balance.

Source code in abacus/core.py
176
177
178
def condense(self):
    """Create a new account of the same type with only one value as account balance."""
    return self.empty().topup(self.balance())

credit(amount)

Add credit amount to account.

Source code in abacus/core.py
160
161
162
def credit(self, amount: Amount):
    """Add credit amount to account."""
    self.credits.append(amount)

debit(amount)

Add debit amount to account.

Source code in abacus/core.py
156
157
158
def debit(self, amount: Amount):
    """Add debit amount to account."""
    self.debits.append(amount)

empty()

Create a new empty account of the same type.

Source code in abacus/core.py
180
181
182
def empty(self):
    """Create a new empty account of the same type."""
    return self.__class__()

topup(balance)

Add starting balance to a proper side of account.

Source code in abacus/core.py
184
185
186
187
188
189
190
191
def topup(self, balance):
    """Add starting balance to a proper side of account."""
    match self:
        case DebitAccount(_, _):
            self.debit(balance)
        case CreditAccount(_, _):
            self.credit(balance)
    return self

transfer_balance(my_name, dest_name) abstractmethod

Create an entry that transfers account balance from this account to destination account.

This account name is my_name and destination account name is dest_name.

Source code in abacus/core.py
168
169
170
171
172
173
174
@abstractmethod
def transfer_balance(self, my_name: str, dest_name: str) -> "Entry":
    """Create an entry that transfers account balance from this account
    to destination account.

    This account name is `my_name` and destination account name is `dest_name`.
    """

abacus.core.Ledger

Bases: UserDict[str, TAccount]

Source code in abacus/core.py
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
class Ledger(UserDict[str, TAccount]):
    @classmethod
    def new(cls, chart: Chart, balances: AccountBalances | None):
        """Create a new ledger from chart, possibly using starting balances."""
        ledger = cls({name: h.t_account() for name, h in chart.dict_items()})  # type: ignore
        if balances:
            entries = starting_entries(chart, balances)
            ledger.post_many(entries)
        return ledger

    def post(self, debit: str, credit: str, amount: Amount, title: str = ""):
        """Post to ledger using debit and credit account names and amount."""
        # FIXME: title is discarded
        return self.post_one(Entry(debit, credit, amount))

    def post_one(self, entry: Entry):
        """Post one double entry to ledger."""
        return self.post_many(entries=[entry])

    def post_many(self, entries: Iterable[Entry]):
        """Post several double entries to ledger."""
        failed = []
        for entry in entries:
            try:
                self.data[entry.debit].debit(amount=entry.amount)
                self.data[entry.credit].credit(amount=entry.amount)
            except KeyError:
                failed.append(entry)
        if failed:
            raise AbacusError(failed)
        return self

    @property
    def balances(self):
        """Return account balances."""
        return AccountBalances(
            {name: account.balance() for name, account in self.items()}
        )

    def subset(self, cls: Type[TAccount]):
        """Filter ledger by account type."""
        return self.__class__(
            {
                account_name: t_account
                for account_name, t_account in self.data.items()
                if isinstance(t_account, cls)
            }
        )

    def condense(self):
        """Return a new ledger with condensed accounts that hold just one value.
        Used to avoid copying of ledger data where only account balances are needed."""
        return self.__class__(
            {name: account.condense() for name, account in self.items()}
        )

balances property

Return account balances.

condense()

Return a new ledger with condensed accounts that hold just one value. Used to avoid copying of ledger data where only account balances are needed.

Source code in abacus/core.py
445
446
447
448
449
450
def condense(self):
    """Return a new ledger with condensed accounts that hold just one value.
    Used to avoid copying of ledger data where only account balances are needed."""
    return self.__class__(
        {name: account.condense() for name, account in self.items()}
    )

new(chart, balances) classmethod

Create a new ledger from chart, possibly using starting balances.

Source code in abacus/core.py
397
398
399
400
401
402
403
404
@classmethod
def new(cls, chart: Chart, balances: AccountBalances | None):
    """Create a new ledger from chart, possibly using starting balances."""
    ledger = cls({name: h.t_account() for name, h in chart.dict_items()})  # type: ignore
    if balances:
        entries = starting_entries(chart, balances)
        ledger.post_many(entries)
    return ledger

post(debit, credit, amount, title='')

Post to ledger using debit and credit account names and amount.

Source code in abacus/core.py
406
407
408
409
def post(self, debit: str, credit: str, amount: Amount, title: str = ""):
    """Post to ledger using debit and credit account names and amount."""
    # FIXME: title is discarded
    return self.post_one(Entry(debit, credit, amount))

post_many(entries)

Post several double entries to ledger.

Source code in abacus/core.py
415
416
417
418
419
420
421
422
423
424
425
426
def post_many(self, entries: Iterable[Entry]):
    """Post several double entries to ledger."""
    failed = []
    for entry in entries:
        try:
            self.data[entry.debit].debit(amount=entry.amount)
            self.data[entry.credit].credit(amount=entry.amount)
        except KeyError:
            failed.append(entry)
    if failed:
        raise AbacusError(failed)
    return self

post_one(entry)

Post one double entry to ledger.

Source code in abacus/core.py
411
412
413
def post_one(self, entry: Entry):
    """Post one double entry to ledger."""
    return self.post_many(entries=[entry])

subset(cls)

Filter ledger by account type.

Source code in abacus/core.py
435
436
437
438
439
440
441
442
443
def subset(self, cls: Type[TAccount]):
    """Filter ledger by account type."""
    return self.__class__(
        {
            account_name: t_account
            for account_name, t_account in self.data.items()
            if isinstance(t_account, cls)
        }
    )

abacus.core.Pipeline

A pipeline to accumulate ledger transformations.

Source code in abacus/core.py
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
class Pipeline:
    """A pipeline to accumulate ledger transformations."""

    def __init__(self, chart: Chart, ledger: Ledger):
        self.chart = chart
        self.ledger = deepcopy(ledger)
        self.closing_entries: list[Entry] = []

    def append_and_post(self, entry: Entry):
        self.ledger.post_one(entry)
        self.closing_entries.append(entry)

    def close_contra(self, t: Type[ContraAccount]):
        """Close contra accounts of type `t`."""
        for account, contra_account in contra_pairs(self.chart, t):
            entry = self.ledger.data[contra_account].transfer_balance(
                contra_account, account
            )
            self.append_and_post(entry)
        return self

    def close_to_isa(self):
        """Close income or expense accounts to income summary account."""
        for name, account in self.ledger.data.items():
            if isinstance(account, Income) or isinstance(account, Expense):
                entry = account.transfer_balance(
                    name, self.chart.income_summary_account
                )
                self.append_and_post(entry)
        return self

    def close_isa_to_re(self):
        """Close income summary account to retained earnings account."""
        entry = Entry(
            debit=self.chart.income_summary_account,
            credit=self.chart.retained_earnings_account,
            amount=self.ledger.data[self.chart.income_summary_account].balance(),
        )
        self.append_and_post(entry)
        return self

    def close_first(self):
        """Close contra income and contra expense accounts."""
        self.close_contra(ContraIncome)
        self.close_contra(ContraExpense)
        return self

    def close_second(self):
        """Close income and expense accounts to income summary account,
        then close income summary account to retained earnings."""
        self.close_to_isa()
        self.close_isa_to_re()
        return self

    def close_last(self):
        """Close permanent contra accounts."""
        self.close_contra(ContraAsset)
        self.close_contra(ContraLiability)
        self.close_contra(ContraCapital)
        return self

    def close(self):
        self.close_first()
        self.close_second()
        self.close_last()
        return self

close_contra(t)

Close contra accounts of type t.

Source code in abacus/core.py
482
483
484
485
486
487
488
489
def close_contra(self, t: Type[ContraAccount]):
    """Close contra accounts of type `t`."""
    for account, contra_account in contra_pairs(self.chart, t):
        entry = self.ledger.data[contra_account].transfer_balance(
            contra_account, account
        )
        self.append_and_post(entry)
    return self

close_first()

Close contra income and contra expense accounts.

Source code in abacus/core.py
511
512
513
514
515
def close_first(self):
    """Close contra income and contra expense accounts."""
    self.close_contra(ContraIncome)
    self.close_contra(ContraExpense)
    return self

close_isa_to_re()

Close income summary account to retained earnings account.

Source code in abacus/core.py
501
502
503
504
505
506
507
508
509
def close_isa_to_re(self):
    """Close income summary account to retained earnings account."""
    entry = Entry(
        debit=self.chart.income_summary_account,
        credit=self.chart.retained_earnings_account,
        amount=self.ledger.data[self.chart.income_summary_account].balance(),
    )
    self.append_and_post(entry)
    return self

close_last()

Close permanent contra accounts.

Source code in abacus/core.py
524
525
526
527
528
529
def close_last(self):
    """Close permanent contra accounts."""
    self.close_contra(ContraAsset)
    self.close_contra(ContraLiability)
    self.close_contra(ContraCapital)
    return self

close_second()

Close income and expense accounts to income summary account, then close income summary account to retained earnings.

Source code in abacus/core.py
517
518
519
520
521
522
def close_second(self):
    """Close income and expense accounts to income summary account,
    then close income summary account to retained earnings."""
    self.close_to_isa()
    self.close_isa_to_re()
    return self

close_to_isa()

Close income or expense accounts to income summary account.

Source code in abacus/core.py
491
492
493
494
495
496
497
498
499
def close_to_isa(self):
    """Close income or expense accounts to income summary account."""
    for name, account in self.ledger.data.items():
        if isinstance(account, Income) or isinstance(account, Expense):
            entry = account.transfer_balance(
                name, self.chart.income_summary_account
            )
            self.append_and_post(entry)
    return self

Reports

abacus.core.BalanceSheet dataclass

Bases: Statement

Source code in abacus/core.py
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
@dataclass
class BalanceSheet(Statement):
    assets: AccountBalances
    capital: AccountBalances
    liabilities: AccountBalances

    @property
    def viewer(self):
        from abacus.viewers import BalanceSheetViewer

        return BalanceSheetViewer(self)

    @classmethod
    def new(cls, ledger: Ledger):
        return cls(
            assets=ledger.subset(Asset).balances,
            capital=ledger.subset(Capital).balances,
            liabilities=ledger.subset(Liability).balances,
        )

abacus.core.IncomeStatement dataclass

Bases: Statement

Source code in abacus/core.py
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
@dataclass
class IncomeStatement(Statement):
    income: AccountBalances
    expenses: AccountBalances
    default_header: ClassVar[str] = "Income statement"

    @property
    def viewer(self):
        from abacus.viewers import IncomeStatementViewer

        return IncomeStatementViewer(self)

    @classmethod
    def new(cls, ledger: Ledger):
        return cls(
            income=ledger.subset(Income).balances,
            expenses=ledger.subset(Expense).balances,
        )

    def current_profit(self):
        return sum(self.income.values()) - sum(self.expenses.values())

abacus.core.TrialBalance

Bases: UserDict[str, tuple[Amount, Amount]], Statement

Trial balance is a dictionary of account names and their debit-side and credit-side balances.

Source code in abacus/core.py
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
class TrialBalance(UserDict[str, tuple[Amount, Amount]], Statement):
    """Trial balance is a dictionary of account names and
    their debit-side and credit-side balances."""

    @classmethod
    def new(cls, ledger: Ledger):
        _ledger = ledger.condense()
        tb = cls()
        for name, balance in _ledger.subset(DebitAccount).balances.items():
            tb[name] = (balance, 0)
        for name, balance in _ledger.subset(CreditAccount).balances.items():
            tb[name] = (0, balance)
        return cls(tb)

    @property
    def viewer(self):
        from abacus.viewers import TrialBalanceViewer

        return TrialBalanceViewer(self.data)

abacus.core.AccountBalances

Bases: UserDict[str, Amount]

Source code in abacus/core.py
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
class AccountBalances(UserDict[str, Amount]):
    def nonzero(self):
        return self.__class__(
            {name: balance for name, balance in self.items() if balance}
        )

    def total(self):
        return sum(self.values())

    def json(self):
        return json.dumps(self.data, indent=4, ensure_ascii=False)

    def save(self, path: Path | str):
        Path(path).write_text(self.json(), encoding="utf-8")

    @classmethod
    def load(cls, path: Path | str):
        return cls(json.loads(Path(path).read_text(encoding="utf-8")))

abacus.Report dataclass

Source code in abacus/core.py
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
@dataclass
class Report:
    chart: Chart
    ledger: Ledger
    rename_dict: dict[str, str] = field(default_factory=dict)

    # FIXME: may condense chart after init

    def rename(self, key, value):
        self.rename_dict[key] = value
        return self

    @property
    def pipeline(self):
        return Pipeline(self.chart, self.ledger)

    @property
    def balance_sheet(self):
        p = self.pipeline.close_first().close_second().close_last()
        return BalanceSheet.new(p.ledger)

    @property
    def balance_sheet_before_closing(self):
        return BalanceSheet.new(self.ledger)

    @property
    def income_statement(self):
        p = self.pipeline.close_first()
        return IncomeStatement.new(p.ledger)

    @property
    def trial_balance(self):
        return TrialBalance.new(self.ledger)

    @property
    def account_balances(self):
        return self.ledger.balances

    def print_all(self):
        from abacus.viewers import print_viewers

        tv = self.trial_balance.viewer
        bv = self.balance_sheet.viewer
        iv = self.income_statement.viewer
        print_viewers(self.rename_dict, tv, bv, iv)