abcEconomics package

Subpackages

Submodules

abcEconomics.agent module

The abcEconomics.Agent class is the basic class for creating your agents. It automatically handles the possession of goods of an agent. In order to produce/transforme goods you also need to subclass the abcEconomics.Firm or to create a consumer the abcEconomics.Household.

For detailed documentation on:

Trading, see Trade

Logging and data creation, see Database.

Messaging between agents, see Messenger.

class abcEconomics.agent.Agent(id, agent_parameters, simulation_parameters, name=None)[source]

Bases: abcEconomics.logger.logger.Logger, abcEconomics.agents.trader.Trader, abcEconomics.agents.messenger.Messenger, abcEconomics.agents.goods.Goods

Every agent has to inherit this class. It connects the agent to the simulation and to other agent. The abcEconomics.Trade, abcEconomics.Logger and abcEconomics.Messenger classes are included. An agent can also inheriting from abcEconomics.Firm, abcEconomics.FirmMultiTechnologies or abcEconomics.Household classes.

Every method can return parameters to the simulation.

For example:

class Household(abcEconomics.Agent, abcEconomics.Household):
    def init(self, simulation_parameters, agent_parameters):
        self.num_firms = simulation_parameters['num_firms']
        self.type = agent_parameters['type']
        ...

    def selling(self):
        for i in range(self.num_firms):
            self.sell('firm', i, 'good', quantity=1, price=1)

    ...
    def return_quantity_of_good(self):
        return['good']


...

simulation = Simulation()
households = Simulation.build_agents(household, 'household',
                                     parameters={...},
                                     agent_parameters=[{'type': 'a'},
                                                       {'type': 'b'}])
for r in range(10):
    simulation.advance_round(r)
    households.selling()
    print(households.return_quantity_of_good())
group = None

self.group returns the agents group or type READ ONLY!

id = None

self.name returns the agents name, which is the group name and the id

init()[source]

This method is called when the agents are build. It can be overwritten by the user, to initialize the agents. Parameters are the parameters given to abcEconomics.Simulation.build_agents().

Example:

class Student(abcEconomics.Agent):
    def init(self, rounds, age, lazy, school_size):
        self.rounds = rounds
        self.age = age
        self.lazy = lazy
        self.school_size = school_size

    def say(self):
        print('I am', self.age ' years old and go to a school
        that is ', self.school_size')


def main():
    sim = Simulation()
    students = sim.build_agents(Student, 'student',
                                agent_parameters=[{'age': 12, lazy: True},
                                                  {'age': 12, lazy: True},
                                                  {'age': 13, lazy: False},
                                                  {'age': 14, lazy: True}],
                                rounds=50,
                                school_size=990)
time = None

self.time, contains the time set with simulation.advance_round(time) you can set time to anything you want an integer or (12, 30, 21, 09, 1979) or ‘monday’

abcEconomics.compile module

abcEconomics.credit module

abcEconomics.logger module

abcEconomics.db module

abcEconomics.expiringgood module

class abcEconomics.expiringgood.ExpiringGood(duration)[source]

Bases: object

A good that expires after X rounds

abcEconomics.financial module

abcEconomics.group module

class abcEconomics.group.Action(scheduler, actions)[source]

Bases: object

class abcEconomics.group.Chain(iterables)[source]

Bases: object

class abcEconomics.group.Group(sim, scheduler, names, agent_arguments=None)[source]

Bases: object

A group of agents. Groups of agents inherit the actions of the agents class they are created by. When a group is called with an agent action all agents execute this actions simultaneously. e.G. banks.buy_stocks(), then all banks buy stocks simultaneously.

agents groups are created like this:

sim = Simulation()

Agents = sim.build_agents(AgentClass, 'group_name', number=100, param1=param1, param2=param2)
Agents = sim.build_agents(AgentClass, 'group_name',
                          param1=param1, param2=param2,
                          agent_parameters=[dict(ap=ap1_agentA, ap=ap2_agentA),
                                            dict(ap=ap1_agentB, ap=ap2_agentB),
                                            dict(ap=ap1_agentC, ap=ap2_agentC)])

Agent groups can be combined using the + sign:

financial_institutions = banks + hedgefunds
...
financial_institutions.buy_stocks()

or:

(banks + hedgefunds).buy_stocks()

Simultaneous execution means that all agents act on the same information set and influence each other only after this action.

individual agents in a group are addressable, you can also get subgroups (only from non combined groups):

banks[5].buy_stocks()

(banks[6,4] + hedgefunds[7,9]).buy_stocks()

agents actions can also be combined:

buying_stuff = banks.buy_stocks & hedgefunds.buy_feraries
buy_stocks()

or:

(banks.buy_stocks & hedgefunds.buy_feraries)()
agg_log(variables=[], goods=[], func={}, len=[])[source]

agg_log(.) writes a aggregate data of variables and goods of a group of agents into the database, so that it is displayed in the gui.

Args:
goods (list, optional):
a list of all goods you want to track as ‘strings’
variables (list, optional):
a list of all variables you want to track as ‘strings’
func (dict, optional):
accepts lambda functions that execute functions. e.G. func = lambda self: self.old_money - self.new_money
len (list, optional):
records the length of the list or dictionary with that name.

Example in start.py:

for round in simulation.next_round():
    firms.produce_and_sell()
    firms.agg_log(goods=['money', 'input'],
                variables=['production_target', 'gross_revenue'])
    households.buying()
by_name(name)[source]

Return a group of a single agents by its name

by_names(names)[source]

Return a callable group of agents from a list of names.group

Example:

banks.by_names(['UBS', 'RBS', "DKB"]).give_loans() 
create_agents(Agent, number=1, agent_parameters=None, **common_parameters)[source]

Create new agents to this group. Works only for non-combined groups

Args:
Agent:
The class used to initialize the agents
agent_parameters:
List of dictionaries of agent_parameters
number:
number of agents to create if agent_parameters is not set
any keyword parameter:
parameters directly passed to agent.init methood
Returns:
The id of the new agent
delete_agents(names)[source]

Remove an agents from a group, by specifying their id.

Args:
ids:
list of ids of the agent

Example:

students.delete_agents([1, 5, 15])
panel_log(variables=[], goods=[], func={}, len=[])[source]

panel_log(.) writes a panel of variables and goods of a group of agents into the database, so that it is displayed in the gui.

Args:
goods (list, optional):
a list of all goods you want to track as ‘strings’
variables (list, optional):
a list of all variables you want to track as ‘strings’
func (dict, optional):
accepts lambda functions that execute functions. e.G. func = lambda self: self.old_money - self.new_money
len (list, optional):
records the length of the list or dictionary with that name.

Example in start.py:

for round in simulation.next_round():
    firms.produce_and_sell()
    firms.panel_log(goods=['money', 'input'],
                variables=['production_target', 'gross_revenue'])
    households.buying()

abcEconomics.inventory module

class abcEconomics.inventory.Inventory(name)[source]

Bases: object

calculate_assetvalue(prices)[source]
calculate_liablityvalue(prices)[source]
calculate_netvalue(prices)[source]
calculate_valued_assets(prices)[source]
calculate_valued_liablities(prices)[source]
commit(good, committed_quantity, final_quantity)[source]
create(good, quantity)[source]

creates quantity of the good out of nothing

Use with care. As long as you use it only for labor and natural resources your model is macro-economically complete.

Args:
‘good’: is the name of the good quantity: number
create_timestructured(good, quantity)[source]

creates quantity of the time structured good out of nothing. For example:

self.creat_timestructured('capital', [10,20,30])

Creates capital. 10 units are 2 years old 20 units are 1 year old and 30 units are new.

It can also be used with a quantity instead of an array. In this case the amount is equally split on the years.:

self.creat_timestructured('capital', 60)

In this case 20 units are 2 years old 20 units are 1 year old and 20 units are new.

Args:
‘good’:
is the name of the good
quantity:
an arry or number
destroy(good, quantity=None)[source]

destroys quantity of the good. If quantity is omitted destroys all

Use with care.

Args:

'good':
    is the name of the good
quantity (optional):
    number

Raises:

NotEnoughGoods: when goods are insufficient
not_reserved(good)[source]

returns how much of good an agent possesses.

Returns:
A number.

possession does not return a dictionary for self.log(…), you can use self.possessions([…]) (plural) with self.log.

Example:

if self['money'] < 1:
    self.financial_crisis = True

if not(is_positive(self['money']):
    self.bankruptcy = True
possession(good)[source]
possessions()[source]

returns all possessions

reserve(good, quantity)[source]
reserved(good)[source]

returns how much of a good an agent has currently reseed to sell or buy.

Returns:
A number.

possession does not return a dictionary for self.log(…), you can use self.possessions([…]) (plural) with self.log.

Example:

if self['money'] < 1:
    self.financial_crisis = True

if not(is_positive(self['money']):
    self.bankruptcy = True
rewind(good, quantity)[source]
transform(ingredient, unit, product, quantity=None)[source]
abcEconomics.inventory.isclose(a, b)[source]

abcEconomics.messenger module

abcEconomics.multicurrencytrade module

abcEconomics.notenoughgoods module

This file defines the tools.NotEnoughGoods

exception abcEconomics.notenoughgoods.NotEnoughGoods(_agent_name, good, amount_missing)[source]

Bases: Exception

Methods raise this exception when the agent has less goods than needed

These functions (self.produce, self.offer, self.sell, self.buy) should be encapsulated by a try except block:

try:
   self.produce(...)
except NotEnoughGoods:
   alternative_statements()

abcEconomics.online_variance module

abcEconomics.online_variance module

abcEconomics.postbox module

abcEconomics.postprocess module

abcEconomics.processorgroup module

abcEconomics.quote module

abcEconomics.trade module

abcEconomics.trade module

abcEconomics.webtext module

Module contents

The best way to start creating a simulation is by copying the start.py file and other files from ‘abcEconomics/template’ in https://github.com/AB-CE/examples.

To see how to create a simulation, read ipython_tutorial.

This is a minimal template for a start.py:

from agent import Agent
from abcEconomics import *


simulation = Simulation(name='abcEconomics')
agents = simulation.build_agents(Agent, 'agent', 2)
for time in range(100):
    simulation.advance_round(time)
    agents.one()
    agents.two()
    agents.three()
simulation.finalize()

Note two things are important: there must be a

finalize() at the end otherwise the simulation blocks at the end. Furthermore, every round needs to be announced using simulation.advance_round(time), where time is any representation of time.

class abcEconomics.Simulation(name='abcEconomics', random_seed=None, trade_logging='off', processes=1, dbplugin=None, dbpluginargs=[], path='auto', multiprocessing_database=False)[source]

Bases: object

This is the class in which the simulation is run. Actions and agents have to be added. Databases and resource declarations can be added. Then run the simulation.

Args:
name:
name of the simulation
random_seed (optional):
a random seed that controls the random number of the simulation
trade_logging:
Whether trades are logged,trade_logging can be ‘group’ (fast) or ‘individual’ (slow) or ‘off’
processes (optional):
The number of processes that runs in parallel. Each process hosts a share of the agents. By default, if this parameter is not specified, processes is all your logical processor cores times two, using hyper-threading when available. For easy debugging, set processes to one and the simulation is executed without parallelization. Sometimes it is advisable to decrease the number of processes to the number of logical or even physical processor cores on your computer. For easy debugging set processes to 1, this way only one agent runs at a time and only one error message is displayed
check_unchecked_msgs:
check every round that all messages have been received with get_massages or get_offers.
path:
path for database use None to omit directory creation.
dbplugin, dbpluginargs:
database plugin, see Database Plugins

Example:

simulation = Simulation(name='abcEconomics',
                        trade_logging='individual',
                        processes=None)

Example for a simulation:

num_firms = 5
num_households = 2000

w = Simulation(name='abcEconomics',
               trade_logging='individual',
               processes=None)

w.panel('firm', command='after_sales_before_consumption')

firms = w.build_agents(Firm, 'firm', num_firms)
households = w.build_agents(Household, 'household', num_households)

all = firms + households

for time in range(100):
    self.time = time
    endowment.refresh_services('labor', derived_from='labor_endowment', units=5)
    households.recieve_connections()
    households.offer_capital()
    firms.buy_capital()
    firms.production()
    if time == 250:
        centralbank.intervention()
    households.buy_product()
    all.after_sales_before_consumption()
    households.consume()

w.finalize()
advance_round(time)[source]
build_agents(AgentClass, group_name, number=None, agent_parameters=None, **parameters)[source]

This method creates agents.

Args:

AgentClass:
is the name of the AgentClass that you imported
group_name:
the name of the group, as it will be used in the action list and transactions. Should generally be lowercase of the AgentClass.
number:
number of agents to be created.
agent_parameters:
a list of dictionaries, where each agent gets one dictionary. The number of agents is the length of the list
any other parameters:
are directly passed to the agent

Example:

firms = simulation.build_agents(Firm, 'firm',
    number=simulation_parameters['num_firms'])
banks = simulation.build_agents(Bank, 'bank',
                                agent_parameters=[{'name': 'UBS'},
                                {'name': 'amex'},{'name': 'chase'}
                                **simulation_parameters,
                                loanable=True)

centralbanks = simulation.build_agents(CentralBank, 'centralbank',
                                       number=1,
                                       rounds=num_rounds)
create_agent(AgentClass, group_name, simulation_parameters=None, agent_parameters=None)[source]
create_agents(AgentClass, group_name, simulation_parameters=None, agent_parameters=None, number=1)[source]
delete_agent(*ang)[source]
delete_agents(group, ids)[source]

This deletes a group of agents. The model has to make sure that other agents are notified of the death of agents in order to stop them from corresponding with this agent. Note that if you create new agents after deleting agents the ID’s of the deleted agents are reused.

Args:
group:
group of the agent
ids:
a list of ids of the agents to be deleted in that group
finalize()[source]

simulation.finalize() must be run after each simulation. It will write all data to disk

Example:

simulation = Simulation(...)
...
for r in range(100):
    simulation.advance_round(r)
    agents.do_something()
    ...

simulation.finalize()
time

Set and get time for simulation and all agents