Economic Agents

An Agent is an autonomous economic entity. Each agent is equipped with a balance sheet and an income statement.

Agents

class sfctools.core.agent.Agent(alias=None, verbose=False, signals: Optional[list] = None, slots: Optional[list] = None)

Bases: object

This is the base class for any agent. It takes care of the bookkeeping system and other low-level operations of the agent.

Instantiation of agents is done here. Note: Each agent will be given a name and an alias name. The name will be set automatically and the alias name will be a (possibly non-unique) name, for example ‘name’ could be ‘Firm_0001’ and alias_name could be ‘MyEnergyProducer’.

Parameters
  • alias – (optional) alias or None(default)

  • verbose – boolean switch to enable console output. Default is False

  • signals – list of str or None(default), signal names connected to this node

  • slots – list of str or None(default), slot names connected to this node.

property balance_sheet

This will return the (private) BalanceSheet object of the agent.

property cash_balance: float

‘Shortcut’ property for balance of ‘Cash’ stored in ‘Assets’ of the agent

file_bankruptcy(event=None)

file agent for bankrupcy

Parameters

event – preferrably str, can be None for manual trigger but should be something like ‘negative cash’ or ‘negative equity’ (default).

NOTE This should be called by a sub-module rather than manually by the user

get_balance(key, kind) float

Gets the nominal balance of a certain entry in the balance sheet. :param key: str, which item is requested (e.g. ‘Cash’, ‘Apples’,…) :param kind: BalanceEntry

property leverage: float

leverage of own balance sheet

property net_worth: float

net worth at own balance sheet

property total_assets

sum of assets column of balance sheet

property total_liabilities

sum of liabilities column of balance sheet

trigger(event_key, *args, **kwargs)

trigger a certain default method of this agent :param event_key str: a key for the event

class sfctools.core.agent.SingletonAgent(*args, **kwargs)

Bases: sfctools.core.agent.Agent

SingletonAgent is an agent which is singleton, meaning that only one instance creation of this Agent will be allowed.

Instantiation of agents is done here. Note: Each agent will be given a name and an alias name. The name will be set automatically and the alias name will be a (possibly non-unique) name, for example ‘name’ could be ‘Firm_0001’ and alias_name could be ‘MyEnergyProducer’.

Parameters
  • alias – (optional) alias or None(default)

  • verbose – boolean switch to enable console output. Default is False

  • signals – list of str or None(default), signal names connected to this node

  • slots – list of str or None(default), slot names connected to this node.

sfctools.core.agent.block_on_bankrupt(method)

This is a decorator you can use when building an agent. It will block this action whenever the agent is bankrupt.

Usage:

from sfctools import block_on_bankrupt

class MyAgent(Agent):
    ...

@block_on_bankrupt
def my_fun(self,...):
    ...

Balance Sheet

enum sfctools.datastructs.balance.BalanceEntry(value)

Bases: enum.Enum

these are the different entry types

Valid values are as follows:

ASSETS = <BalanceEntry.ASSETS: 0>
EQUITY = <BalanceEntry.EQUITY: 1>
LIABILITIES = <BalanceEntry.LIABILITIES: 2>
TOTAL = <BalanceEntry.TOTAL: 3>
class sfctools.datastructs.balance.BalanceSheet(owner)

Bases: object

This is the balance sheet of an agent (it could be used as a standalone datastructure, too, in theory). A balance sheet is of the following form

ASSETS

LIABILITIES AND EQUITY

Liabilities

Equity, Net Worth

TOT ASSETS = TOT LIABILITIES AND EQUITY

more information can be found here https://www.investopedia.com/terms/b/balancesheet.asp for example.

Balance sheet constructor. Creates a new balance sheet

Parameters

owner – the owner agent of this balance sheet. Can be None for standalone purposes, but it is recommended to pass an Agent instance here.

class Proxy(parent)

Bases: object

Proxy class for balance sheet. It can be either engaged (consistent and ‘active’) or disengaged (inconsistent and ‘disabled’). The consistency is automatically checked inside the ‘engage()’ call when switched from disengaged to engaged.

add_changelog(agent, name, which, x)

inserts a link between a specific balance sheet item to a for example, a bank might want to record which agent its deposits belong to… Data structure: [BalanceEntry]->[ItemName]->[Agent]->[float Balance]

Parameters
  • agent – agent instance to store here

  • name – name of the item, e.g. ‘Deposits’

  • which – corresponding BalanceEntry

  • x – quantity which is inserted, can be positive, zero or negative

change_item(name, which, value, suppress_stock=False)

Chanes value of an item in the balance sheet.

Parameters
  • name – name of the asset / entry to change

  • value – value is added to entry. can also be negative

  • which – BalanceEntry: Asset, Liability, Equity

classmethod change_tolerance(tol: float, rel_tol: float)

Change the tolerance by which the balace is allowed to diverge This will set the new values globally. The tolerance is checked in a two-step process: Frist, the absolute tolerance violation is checked, i.e. if any balance sheet side sums up to more or less than the other side. If the absolute tolerance is violated, an error is thrown if also the relative tolerance is exceeded. The latter is the second step of the checking process. If the relative deviation is violated but the absolute level is not exceeded, no error wil be thrown.

Parameters
  • tol – new absolute tolerance

  • rel_tol – relative tolerance (relative devaition from total assets)

check_consistency_changelog(item, balance_entry=None, verbose=False)

checks the changelog consistency with the aggregate balance sheet

Parameters

item – name of the item

:param balance_entry a BalanceEntry identifier :param verbose: print out the values (default False)

depreciate()

(BETA) this will look up all the required depreciation rates in the settings and depreciate the balance sheet. Equity will become less, liabilities will stay.

disengage()

‘unlocks’ the balance sheet -> can be modified now without error

engage()

locks the balance sheet -> no longer can be modified performs also a cross-check if consistency is maintained

get_balance(key, kind=BalanceEntry.ASSETS) float

Gets amount of a certain entry for certain key

Parameters
  • key – name of entry (e.g. ‘Cash’ or ‘Apples’)

  • kind – preferrably BalanceEntry: Asset, Liabilities or Equity, optionally str ‘Assets’, ‘Equity’ or ‘Liabilities’

Returns

float, value in balance sheet

get_last_changelog(name, which, agent=None)

returns the internally stored links to other agents made via balance sheet transactions

Parameters
  • agent – agent instance to store here. if None, all agents’ entries will be returned

  • name – name of the item, e.g. ‘Deposits’

  • which – corresponding BalanceEntry

Returns

float, current balance or dict of balances for agents

property leverage: float

computes the financial leverage value (debt-to-assets ratio) of this balance sheet

\[Leverage = LIABILITIES / (LIABILITIES + NET WORTH)\]
Returns

float, leverage

property modify

Modification decorator. Temporarily disengages the data structure. This can be used in a with block:

with balance_sheet_1.modify:
    with balance_sheet_2.modify:
        balance_sheet_1.change_item(...)
        balance_sheet_2.change_item(...)
property net_worth: float

net worth = sum of equity

plot(show_labels=True, cols_assets=None, cols_liabs=None, cols_eq=None, show_legend=True, fname=None, ax=None, label_fmt='{0:.1f}')

creates a matplotlib plot of the balance sheet

Parameters
  • show_labels – show labels (numbers) above the bars

  • label_fmt – (default ‘{0:.1f}’), format of labels (if shown)

  • show_legend – (True) show a legend with the balance sheet entries

By default, assets are red, equity is blue and liabilites are green but custom colors can be given

Parameters
  • cols_assets – (None) list of mpl colors for assets. Default is [“salmon”, “indianred”, “rosybrown”, “orangered”, “red”, “indianred”]

  • cols_liabs – (None) list of mpl colors for liabilities. Default is [ “lightgreen”, “honeydew”,”seagreen”, “darkgreen”, “darkslategray”]

  • cols_eq – (None) list of mpl colors for equity. Default is [“lightsteelblue”, “lavender”, “powderblue”, “steelblue”, “royalblue”, “blue”]

if you want to save to file instead of showing as plot window, specify a fname :param fname: if None (default) is given, plot will be shown directly. If fname is given, plot will be saved to a file

if you want to redirect the plot to a certain axis, you can enter the axis via the parameter ax :param ax: axis to plot on. setting this parameter different from None will make ‘fname’ ineffective

classmethod plot_list(list_of_balance_sheets, dt=1, xlabel=None, ylabel=None, title=None, show_liabilities=True, show=True)

Plots a list of balance sheets (e.g. a collected temporal series)

Parameters
  • list_of_balance_sheets – a list of BalanceSheet instances

  • dt – step, (how many values to skip in between)

  • xlabel – x axis label

  • ylabel – y axis label

  • title – title of the figure

  • show_liabilities – boolean switch to show passive side of balance sheet as downward-pointing bars (default True)

  • show – show the plot in a new window? if False, only the matplotlib figure is returned

property raw_data

get the raw data of this data structure in dictionary format. This will create a copy of the original data, so the user won’t operate on the data directly (which is forbidden)

restore_after_bankrupcy(verbose=False)
to_dataframe()

Create a dataframe from this data structure. Warning: this is computationally heavy and should not be used in loops!

Returns

pandas dataframe

to_string(nice_format=True)

Coverts the whole balance sheet to a pandas dataframe and subsequently to a string

Parameters

nice_format – True (default), use a fancy formatting in three boxes vs direct dataframe to string conversion

Returns

str, balance sheet string representation

property total_assets

total assets = sum of assets column

property total_liabilities

total liabilities = sum of all liabilities in liability column

enum sfctools.datastructs.balance.BankruptcyEvent(value)

Bases: enum.Enum

bankruptcy cases

Valid values are as follows:

NEGATIVE_ASSETS = <BankruptcyEvent.NEGATIVE_ASSETS: 0>
NEGATIVE_LIABILITIES = <BankruptcyEvent.NEGATIVE_LIABILITIES: 1>
NEGATIVE_EQUITY = <BankruptcyEvent.NEGATIVE_EQUITY: 2>

Income Statement

enum sfctools.datastructs.income_statement.ICSEntry(value)

Bases: enum.Enum

Enum for income sheet entry (ICSEntry). Explanation: see IncomeStatement class

Valid values are as follows:

REVENUES = <ICSEntry.REVENUES: 0>
GAINS = <ICSEntry.GAINS: 1>
EXPENSES = <ICSEntry.EXPENSES: 2>
LOSSES = <ICSEntry.LOSSES: 3>
NONTAX_PROFITS = <ICSEntry.NONTAX_PROFITS: 4>
NONTAX_LOSSES = <ICSEntry.NONTAX_LOSSES: 5>
INTEREST = <ICSEntry.INTEREST: 6>
TAXES = <ICSEntry.TAXES: 7>
NOI = <ICSEntry.NOI: 8>
class sfctools.datastructs.income_statement.IncomeStatement(owner, data=None, tot_dict=None, total_spendings=0.0, last=None, is_empty=True)

Bases: object

Income statement data structure. Consist of the following entries:

Income Statement

Example / Description

Revenues and Gains

Money a company actually receives during a specific period

Tag | Value

interest on deposits, sales

Tag | Value

Tag | Value

Tag | Value

Expenditures and Losses

Tag | Value

wages

Tag | Value

Gross (Before-Tax)

Tag | Value

Interest Payments

Tag | Value

interst on loans

inter NOI

interest payments non-operating income

Tax paid

taxes (e.g. on income) paid

Non-Taxable

untaxed profits and losses

After- tax income

Constructs a new income statement.

Parameters
  • owner – Agent instance. The owner of this income statement.

  • data – default None, can be used to pre-initialize income sheet with data. Should not be used in most cases (two-fold dict data[kind:ICSEntry][tag:str])

  • tot_dict – default None, can be used to pre-initialize income sheet with data. Should not be used in most cases (two-fold dict tot_dict[kind:ICSEntry][tag:str]). Saves ‘total’ row of the sheet.

  • total_spendings – depreciated, to not used

property ebit

earnings before interest and tax

property ebt

earnings before tax (and after interest)

get_entry(kind, tag)

get an specific entry of the income statement

Parameters
  • kind – BalanceEntry, which entry to look up

  • tag – str, tag of the specific row

property gross_income

agi

property gross_spendings

expenses + losses

property int

interest expenditure (absolute value)

property net_income

eranings after tax (and after interest)

new_entry(kind, tag, value)

Registers a new item in the income statement

Parameters
  • kind – kind of entry: Revnue, Gain, Expense, Loss or Tax

  • tag – a name, e.g. ‘interest on deposits’

  • value – nominal value of the entry

Example:

from sfctools import Agent, ICSEntry

a = Agent()
ics = a.income_statement
# ics.new_entry(kind,tag,value)
ics.new_entry(ICSEntry.EXPENSES, "Vacation", 1000.0)
# ...
ics.reset()
property noi

non-operational income

reset()

Reset routine. Remove data and start a new, blank income statement for the next period. Saves current state in “last”.

restore()

Restore an all-zero income statement

property spendings

expenses + losses + taxes + interest

property tax

taxes

to_dataframe()

Converts the data structure of the income sheet to human-readable pandas dataframe format. :return: pandas dataframe

to_string()

String representation of the income sheet. This will first convert to pandas dataframe, then to string. :return: str

Cashflow Statement

enum sfctools.datastructs.cash_flow_statement.CashFlowEntry(value)

Bases: enum.Enum

these are the different entry types

Valid values are as follows:

OPERATING = <CashFlowEntry.OPERATING: 0>
FINANCING = <CashFlowEntry.FINANCING: 1>
INVESTING = <CashFlowEntry.INVESTING: 2>
class sfctools.datastructs.cash_flow_statement.CashFlowStatement(owner)

Bases: object

Cash flow statement data structure. See also https://www.investopedia.com/investing/what-is-a-cash-flow-statement/

Cash Flow Statement

Operating Activities

Net Income | Value

Tag | Value

Tag | Value

TOTAL

Investing Activities

Tag | Value

Tag | Value

TOTAL

Financing Activities

Tag | Value

Tag | Value

TOTAL

instaniates a new cash flow statement

Parameters

owner – owner instance this cash flow statement belongs to.

property financing_cash_flow

returns only financing part of the cash flow

get_entry(kind, tag=None)

retrieve an arbitrary entry from the cash flow statement :param kind: sfctools.CashFlowEntry.OPERATING, FINANCING or INVESTING :param tag (optional): the tag under which to search for

property investing_cash_flow

returns only investing part of the cash flow

new_entry(kind, tag, value)

registers a new item in the income statement

Parameters
  • kind – kind of entry: Financing, Operating or Investing

  • tag – a name, e.g. ‘interest on deposits’

  • value – nominal value of the entry

Example

from sfctools import Agent, CashFlowEntry
a = Agent()
cfs = a.cash_flow_statement

kind = CashFlowEntry.FINANCING
tag = "My Subject"
value = 10.0

cfs.new_entry(kind,tag,value)
print(cfs.to_dataframe())
property operating_cash_flow

returns only operating part of the cash flow

reset()

Removes data and starts a new, blank income statement for the next period

to_dataframe()

Converts the data structure to a human-readable pandas dataframe.

to_string()

Converts the cash-flow statement to dataframe and then to string.

property total_cash_flow

returns total cashflow, i.e. operating plus financing plus investing