Macroeconomic ABM with Banking Instability and Macroprudential Rules

Macroeconomic ABM with Banking Instability and Macroprudential Rules preview image

This model is seeking new collaborators — would you please help?

1 collaborator

Yo Rubén Osuna (Author)

Tags

crisis 

Tagged by Rubén Osuna over 6 years ago

cycles 

Tagged by Rubén Osuna over 6 years ago

macroeconomic 

Tagged by Rubén Osuna over 6 years ago

Parent of 1 model: Version 2
Visible to everyone | Changeable by everyone
Model was written in NetLogo 6.0.1 • Viewed 563 times • Downloaded 40 times • Run 0 times
Download the 'Macroeconomic ABM with Banking Instability and Macroprudential Rules' modelDownload this modelEmbed this model

Do you have questions or comments about this model? Ask them here! (You'll first need to log in.)


Comments and Questions

This model is a beta version!

The model has undetected problems and it does not run yet.

Posted about 6 years ago

Version 2 now runs

The version 2 runs, but the behaviour of the model is not the expected yet.

Posted about 6 years ago

Click to Run Model

; Macro Agent Base Model (MABM)
; code written by Rubén Osuna, from the model of Assenza, Gatti, Grazzini et al. (2015) macro ABM (as coded by Elder Silva)


extensions [ matrix r stats ]                               ; calling the R extension and the matrix extension

globals [
  taylor-interest-rate                                      ; the interest rate. Conservative type: only inflation considered. Dual mandate: inflation and output gap. Three mandate: inflation, output gap and credit
  eta1                                                      ; undifferentiated interest rate applied to loans of firms with the retail banks
  eta2                                                      ; interest rate applied to loans of retail banks with the Central Bank
  eta3                                                      ; interest rate applied to deposits of firms in the accounts of the retail banks
  eta4                                                      ; interest rate applied to deposits of retail banks in the accounts of the Central Bank
  GDP                                                       ; sum of consumption, total-investment and public expenditures
  GDP_1                                                     ; GDP of the last period (tick)
  P_GDP                                                     ; potential GDP
  Growth-Rate                                               ; growth rate of the GDP
  Recession-lenght                                          ; how many periods the GDP is decreasing
  Unemployment-Rate                                         ; rate of unemployment
  Total-Consumption                                         ; sum of goods sold by the consumptions firms
  Total-Investment                                          ; sum of total capital sold by the capital production firms
  Goods-Price-Level                                         ; sum (price * qt) / Qt sold
  Goods-Price-Level_1                                       ; the same, for the previous period
  Capital-Price-Level                                       ; sum (price * qt) / Qt sold
  Capital-Price-Level_1                                     ; the same, for the previous period
  Total-Loans-Firms                                         ; sum of loans of retail banks with firms of any kind
  Total-Loans-C-Firms                                       ; sum of loans with the C-Firms
  Total-Loans-K-Firms                                       ; sum of loans with the K-Firms
  Total-Central-Bank-Loans                                  ; sum of loans of the retail banks with the Central Bank
  Total-Loans                                               ; sum of loans in this economy (adding up the previous cathegories)
  Total-Loans_1                                             ; sum of loans in this economy for the previous period
  Total-Client-Loans                                        ; this variable should be equal to Total-Loans, but calculated from banks' variables
  Total-Deposits                                            ; sum of all deposits of the retail banks
  Total-Clients-Accounts                                     ; this variable should be equal to Total-Deposits, but calculated from banks' variables
  Total-Deposits_1                                          ; sum of all deposits of the retail banks, previous period
  Total-Reserves                                            ; sum of all reserves of the retail banks
  Total-Deposits-Workers                                    ; sum of deposit at the bank of the households
  Total-Deposits-Capitalists                                ; sum of deposit at the bank of the capitalists
  Total-Deposits-C-Firms                                    ; sum of deposit at the bank of the C-Firms
  Total-Deposits-K-Firms                                    ; sum of deposit at the bank of the K-Firms
  Total-Interest-Payments                                   ; sum of all interest payments from loaners to retail banks
  Total-Installment-Payments                                ; sum of all installment payments from loaners to retail banks
  C-Firms                                                   ; group of firms producing consumption goods
  K-Firms                                                   ; group of firms producing capital goods
  Workers                                                   ; group of households that offer work time
  Capitalists                                               ; group of households that are owners of firms and banks and do not work for others
  Employed                                                  ; group of workers with an employment
  Unemployed                                                ; group of workers without an employment
  C-Broke                                                   ; number of consumption firms that went broken last period
  K-Broke                                                   ; number of capital production firms that went broken last period
  B-Broke                                                   ; number of banks that went broken last period
  Matrix-C-Firms-Bankruptcy                                 ; input with information that will be used in calculation into R (eq 23)
  Matrix-K-Firms-Bankruptcy                                 ; input with information that will be used in calculation into R (eq 23)
  Matrix-Basel-Buffer                                       ; input with information that will be used in calculation into R (eq 23)
  cpi                                                       ; consumer price index of this period
  cpi_1                                                     ; consumer price index of the previous period
  inflation                                                 ; inflation of this period
  inflation_1                                               ; inflation of the previous period
  Wage-on-GDP                                               ; total salaries as a percentage of the GDP, then wage = Wage-on-GDP * GDP / Number-of-Employees is the wage that keeps that proportion constant
  Wage-on-GDP_1                                             ; total salaries as a percentage of the GDP, then wage = Wage-on-GDP * GDP / Number-of-Employees is the wage that keeps that proportion constant
  Credit-on-GDP                                             ; this is the basic ratio used in the Counter-Cyclical-Capital-Buffer defined in Basel III rules
  Credit-on-GDP_1                                           ; the same from the previous period
  Credit-on-GDP-Gap                                         ; difference between current Credit-on-GDP and the long run trend
  State-budget                                              ; how much money the Government owns at this stick
  State-budget_1                                            ; how much money the Government had the previous period. It is related to the cycle
  Leverage-Banks                                            ; mean leverage of the Banks, the Central Bank has their numbers
  Central-Bank-Own-Capital                                  ; the own capital of the central bank, a liability in its balance
  Account-of-State-at-Central-Bank                          ; Account of the State at the Central Bank
  Monetary-Base                                             ; currency plus total reserves or public debt plus credits o the central bank to retail bank less Account-of-State-at-Central-Bank and the capital of the CB
  Currency                                                  ; bills and coins, the monetary base less total reserves
  Money-Supply                                              ; menetary base multiplied by the money multiplier, which is the inverse of RR, the reserve ratio
  Capital-Buffer                                            ; a % of the new loans acting like reserves
  QEasing?                                                  ; it is automatically set true if three periods of recession are observed
  PublicDebt                                                ; public debt titles sold to the central bank
  PublicDebt_1                                              ; public debt titles sold to the central bank the previous period
  Wage                                                      ; uniform wage paid to the workers by C-Firms and K-Firms
  Wage_1                                                    ; wage of the previous period
  Helped-Households                                         ; how many households are being helped
  Beta_1-C-Firms                                            ; parameter utilized by the banks to calculate the interest rate for the firms (eq 26)
  Beta_2-C-Firms                                            ; parameter utilized by the banks to calculate the interest rate for the firms (eq 26)
  Beta_1-K-Firms                                            ; parameter utilized by the banks to calculate the interest rate for the firms (eq 26)
  Beta_2-K-Firms                                            ; parameter utilized by the banks to calculate the interest rate for the firms (eq 26)
  Mjc                                                       ; parameter utilized in the process "SubF-Call-Matrix-formation", related to C-Firms
  Mjk                                                       ; parameter utilized in the process "SubF-Call-Matrix-formation", related to K-Firms
  Mjb                                                       ; parameter utilized in the process related to the calculation of the Capital Buffer set in Basel III rules
  Current-Number-of-C-Firms                                 ; current number of C-Firms, after losses and entries
  Current-Number-of-K-Firms                                 ; current number of K-Firms, after losses and entries
  Current-Number-of-Workers                                 ; current number of Workers, after losses and entries
  ]

breed                 [ Banks        Bank         ]         ; agent class
breed                 [ Households   Household    ]         ; agent class
breed                 [ Firms        Firm         ]         ; agent class
directed-link-breed   [ Hireds       Hired        ]         ; link used to link firms to the worker
directed-link-breed   [ Owners       Owner        ]         ; link used to link firms and banks to their owner/capitalist
directed-link-breed   [ Bankers      Banker       ]         ; link used for connecting the clients with its bank


Banks-own [
  Clients-Accounts-C-Firms                                  ; the total accounts (deposits) of C-Firms in this bank
  Clients-Accounts-K-Firms                                  ; the total accounts (deposits) of K-Firms in this bank
  Clients-Accounts-Firms                                    ; the sum of the former two variables
  Clients-Accounts-Workers                                  ; the total accounts (deposits) of Workers in this bank
  Clients-Accounts-Capitalists                              ; the total accounts (deposits) of Capitalists in this bank
  Clients-Accounts-Households                               ; the total accounts (deposits) of Households (Workers and Capitalists) in this bank
  Clients-Accounts-at-the-Bank_1                            ; the sum of all previous variables (sum of Firms and Households accounts), previous period
  Clients-Accounts-at-the-Bank                              ; the sum of all previous variables (sum of Firms and Households accounts)
  Clients-Loans-C-Firms                                     ; the total loans of C-Firms in this bank
  Clients-Loans-K-Firms                                     ; the total loans of K-Firms in this bank
  Clients-Loans-with-the-Bank_1                             ; the total loans Firms in this bank, previous period
  Clients-Loans-with-the-Bank                               ; the total loans Firms in this bank
  Available-Credit-Basel2                                   ; maximum available credit under Basel II rules
  Available-Credit-Basel31                                  ; maximum available credit under Basel III rules, Global Capital Framework
  Available-Credit-Basel32                                  ; maximum available credit under Basel III rules, Global Liquidity Requirement
  Available-Credit-Basel                                    ; maximum available credit under Basel rule
  Number-of-Firm-Clients
  Number-of-Household-Clients
  Number-of-Clients
  Own-Reserves                                              ; the reserves of retail banks are deposited in the Central Bank, and they are rewarded with the eta4
  Own-Bank-Capital                                          ; bank own capital
  Need-Cash                                                 ; need of money after production, because the bank has losses and it does not have enough assets for paying it
  Bank-Equity                                               ; Equity is the net worth, the difference between assets and liabilities
  Central-Bank-Loans                                        ; loans from the Central Bank to the Retail Banks
  Profit                                                    ; sum of interest received less the bank losses with their loans
  PBT                                                       ; profits before taxes
  I-Received                                                ; total interest payments of Firms to the Banks
  D-Received                                                ; total installment pays of Firms to the Banks
  Assets                                                    ; total assets of retail banks
  Liabilities                                               ; total liabilities of retail banks
  Overdraft                                                 ; losses of the bank so large than it cannot compensate it with own capital
  Shares                                                    ; the own-bank-capital divided by the total number of capitalists in this economy
  PBT                                                       ; profits before taxes
  ]

Households-own [
  Worker?                                                   ; property of the household, true if it is a worker, false if it is a capitalist
  Employed?                                                 ; property of the household, true if it is employed, false if it is unemployed
  Bankrupt?                                                 ; property of the household, true if the capitalist is broken and become a worker
  Human-Wealth                                              ; variable used in determining how much of the entire wealth will be used for consumption
  Current-Income                                            ; the salary if it is a worker, the profit if it is a capitalist
  Bank-Account-Household                                    ; the total of wealth of the households held with the bank
  Desired-Consumption                                       ; theorical value the household want to consume this period
  Consumption                                               ; real value the household did consumption
  C-Firm-List                                               ; list with the firms the household visited last period
  My-Nearest-Bank                                           ; the nearest bank to the household
  ]

Firms-own [
  C-Firm?                                                   ; property of the firms, yes if it is a consumption production firm, not if is a capital production firm
  Owner?                                                    ; any firm may lose its owner, so this parameter sets the existence of not of an owner at a particular moment
  Price                                                     ; last price practiced by the firm
  Demand                                                    ; last quantity demanded
  Production                                                ; actual production of the firm
  Stock                                                     ; amount available for sales (inventories)
  Delta                                                     ; parameter used to calculate new price
  Number-of-Employees                                       ; actual number of employees of this firm
  Need-of-Employees                                         ; ideal number of employees for this firm
  Vacancy                                                   ; number of opened places at this firm for new workers
  Revenue                                                   ; sum of quantity sold times the price
  Sales                                                     ; sum of quantity sold last period
  Profit                                                    ; revenue less the expenditures, considering taxes
  PBT                                                       ; profits before taxes
  Dividend                                                  ; part of the profit given to the owner, from firms and banks
  Overdraft                                                 ; difference between losses and firm's own resources
  Need-Cash                                                 ; need of money before production starts
  Bank-Account-Firm                                         ; money available at the bank owned by the firms
  Leverage                                                  ; debts of the firm divided by their assets, including the debt, ranging between 0 and 1 (0 is zero debt, and 1, all assets are debt)
  Assets                                                    ; sum deposit at bank and stock available for sales
  Liabilities                                               ; total liabilities of firms
  Equity-C-Firms                                            ; assets minus liabilities, or net worth
  Equity-K-Firms                                            ; assets minus liabilities, or net worth
  eta0                                                      ; taylor-made interest rata calculated for every firm
  Current-Retail-Loans                                      ; loans with the retail banks
  Cases-of-Bankruptcy                                       ; the total number of bankruptcies by this firm
  Probability-of-Bankruptcy                                 ; the probability of dying of the firm
  Available-Credit-Assenza                                  ; maximum available credit under internal risk calculations of the bank
  Interest-Pay                                              ; sum of interest rate payed last period
  Installment-Pay                                           ; sum of the installment payed last period
  T-expected                                                ; the expected life span for this firm
  Capital                                                   ; property of the C-firms, indicate the capital available to be used at the production process
  Desired-Investment                                        ; property of the C-Firms, ideal investment needed
  K-Firm-List                                               ; property of the C-Firms, list with the K-Firms the C-Firms visited last period trying to buy capital goods
  Investment                                                ; property of the C-Firms, capital goods bough last period
  Investment-Memory                                         ; property of the C-firms, parameter utilized to calculate te Desired-Investment
  Util-Capacity                                             ; property of the C-Firms, indicates how much of the Capital had been used
  Stock_t-1                                                 ; Stock available in t-1
  My-Nearest-Bank                                           ; the nearest bank to the firm
  ]


; TO SETUP

to Setup
  clear-all
  ;Setup-Globals
  Short-Setup-Globals
  if Do_We_Have_Banks?                [ Setup-Banks         ]             ; call the setup for banks
  if Do_We_Have_C-Firms?              [ Setup-C-Firms       ]             ; call the setup for C-Firms
  if Do_We_Have_K-Firms?              [ Setup-K-Firms       ]             ; call the setup for K-Firms
  if Do_We_Have_Workers?              [ Setup-Workers       ]             ; call the setup for workers
  if Do_We_Have_Capitalists?          [ Setup-Capitalists   ]             ; call the setup for Capitalists
  reset-ticks                                                             ; netlogo need this
end 

; The setup-globals is not being called. but if it is included into the setup it is not working, because some variable is not a defined global.

to Short-Setup-Globals
  set C-Firms                        Firms      with [     C-Firm? ]                   ; building the group with all C-Firms
  set K-Firms                        Firms      with [ not C-Firm? ]                   ; building the group with all K-firms
  set Capitalists                    Households with [ not Worker?  ]                   ; building the group with all Capitalist
  set Workers                        Households with [    Worker?   ]                   ; building the group with all workers
  if not Random-Seed?               [ random-seed 12345 ]                               ; random seed may or not be used
end 

to Setup-Globals                                                                      ; call the setup for globals
  set taylor-interest-rate              natural-interest-rate                         ; the interest rate set by the central bank
  set GDP                               0                                             ; initial GDP
  set GDP_1                             0                                             ; GDP of the previous period
  set Recession-lenght                  0                                             ; number of periods with GDP falls
  set Unemployment-rate                 0                                             ; initial Unemployment rate
  set Total-Consumption                 0                                             ; initial value of consumption
  set Total-Investment                  0                                             ; initial value of total investment
  set Goods-Price-Level                 1                                             ; initial goods price level, necessary minimum for taking logarithms later
  set Capital-Price-Level               1                                             ; initial capital goods price level, necessary minimum for taking logarithms later
  set Goods-Price-Level_1               0.5                                           ; initial goods price level of the previous period, necessary minimum for taking logarithms later
  set Capital-Price-Level_1             0.5                                           ; initial capital goods price level of the previous period, necessary minimum for taking logarithms later
  set Wage                              Minimum-Wage                                  ; initial value for the wage
  set Wage_1                            0                                             ; initial value for the wage of the previous period
  set cpi                               0                                             ; consumer price index of this period
  set cpi_1                             0                                             ; consumer price index of the previous period
  set inflation                         0                                             ; inflation of this period
  set inflation_1                       0                                             ; inflation of the previous period
  set Wage-on-GDP                       0                                             ; total salaries as a percentage of the GDP, then wage = Wage-on-GDP * GDP / Number-of-Employees is the wage that keeps that proportion constant
  set Wage-on-GDP_1                     0                                             ; total salaries as a percentage of the GDP, then wage = Wage-on-GDP * GDP / Number-of-Employees is the wage that keeps that proportion constant
  set Credit-on-GDP                     0                                             ; this is the basic ratio used in the Counter-Cyclical-Capital-Buffer defined in Basel III rules
  set Credit-on-GDP_1                   0                                             ; this is the basic ratio used in the Counter-Cyclical-Capital-Buffer defined in Basel III rules
  set Total-Loans-Firms                 0                                             ; initial value for total loans of retail banks and firms
  set Total-Loans-C-Firms               0                                             ; initial value for C-loans
  set Total-Loans-K-Firms               0                                             ; initial value for K-loans
  set Total-Central-Bank-Loans          0                                             ; initial value for the total loans of retail banks and central bank
  set Total-Loans                       0                                             ; initial value for the total loans in this economy
  set Total-Loans_1                     0                                             ; sum of loans in this economy for the previous period
  set Total-Deposits-Workers            0                                             ; sum of deposit at the bank of the households
  set Total-Deposits-Capitalists        0                                             ; sum of deposit at the bank of the capitalists
  set Total-Deposits-C-Firms            0                                             ; sum of deposit at the bank of the C-Firms
  set Total-Deposits-K-Firms            0                                             ; sum of deposit at the bank of the K-Firms
  set Total-Deposits                    0                                             ; sum of all deposits of retail banks
  set Total-Deposits_1                  0                                             ; sum of all deposits of retail banks, previous period
  set Total-Reserves                    0                                             ; the reserves of retail banks are deposited in the Central Bank, and they are rewarded with the eta4
  set Total-Interest-Payments           0                                             ; total interest payments of firms to reatail banks for loans received
  set Total-Installment-Payments        0                                             ; total installment payments firms to reatail banks for loans received
  ; the Available-Credit-Basel is a bank propertie, not a global. Need to be relocated to bank setup
  ;set Available-Credit-Basel            0                                             ; this is the credit limit to retail banks from Basel macroprudential rules
  ;set Available-Credit-Basel2           0                                             ; maximum available credit under Basel II rules
  ;set Available-Credit-Basel31          0                                             ; maximum available credit under Basel III rules, Global Capital Framework
  ;set Available-Credit-Basel32          0                                             ; maximum available credit under Basel III rules, Global Liquidity Requirement
  ; ^^^^^^^^ to be relocated
  set State-Budget                      0                                             ; initial value for State-Budget
  set C-Firms                           Firms      with [ C-Firm?        ]            ; building the group with all C-Firms
  set K-Firms                           Firms      with [ not C-Firm?    ]            ; building the group with all K-firms
  set Capitalists                       Households with [ not Worker?    ]            ; building the group with all Capitalist
  set Workers                           Households with [ Worker?        ]            ; building the group with all workers
  set Employed                          Workers    with [ Employed?      ]            ; building the group with all employed workers
  set Unemployed                        Workers    with [ not Employed?  ]            ; building the group with all unemployed workers
  set Helped-Households                 0                                             ; number of households helped by the State
  set Central-Bank-Own-Capital          sum [Initial-equity-of-the-bank ] of Banks    ; the own capital of the central bank, a liability in its balance
  set Account-of-State-at-Central-Bank  0                                             ; Account of the State at the Central Bank
  set Matrix-C-Firms-Bankruptcy         matrix:make-constant  2 Time-Window1 0        ; building the initial matrix which will be used by R-Netlogo later, it is a constant matrix of zeroes with 2 rows and "T-W1" columns
  set Matrix-K-Firms-Bankruptcy         matrix:make-constant  2 Time-Window1 0        ; building the initial matrix which will be used by R-Netlogo later, it is a constant matrix of zeroes with 2 rows and "T-W1" columns
  set Matrix-Basel-Buffer               matrix:make-constant  2 Time-Window2 0        ; building the initial matrix which will be used by R-Netlogo later, it is a constant matrix of zeroes with 2 rows and "T-W2" columns
  set Mjc                               0                                             ; helper with the matrix above
  set Mjk                               0                                             ; helper with the matrix above
  set Mjb                               0                                             ; helper with the matrix above
  set Probability-of-Bankruptcy         0                                             ; probability of a firm of dying, explained by the leverage of that firm
  set PublicDebt                        0                                             ; public debt titles sold to the central bank
  set PublicDebt_1                      0                                             ; public debt titles sold to the central bank the previous period
  if not Random-Seed?                 [ random-seed 12345 ]                           ; random seed may or not be used
end 

to Setup-Banks
    create-Banks Number-of-Banks [                                                 ; create n banks, determined in a global variable
    setxy                                random-xcor random-ycor                   ; place them randomly
    move-to                              one-of patches with [not any? Firms-here] ; if a C-Firm or K-Firm is at the same patch, move the Bank to another empty patch in the setup process
    set shape                           "house"                                    ; just for fun, not necessary for the model, used only for display in HUD netlogo
    set size                             2                                         ; just for fun, not necessary for the model, used only for display in HUD netlogo
    set color                            turquoise                                 ; just for fun, not necessary for the model, used only for display in HUD netlogo
    set Own-Bank-Capital                 Initial-equity-of-the-bank                ; explicit
    set Bank-Equity                      Own-Bank-Capital                          ; this is the initial equity of the bank
    set Clients-Accounts-C-Firms         0                                         ; the total accounts (deposits) of C-Firms in this bank
    set Clients-Accounts-K-Firms         0                                         ; the total accounts (deposits) of K-Firms in this bank
    set Clients-Accounts-Firms           0                                         ; the sum of the former two variables
    set Clients-Accounts-Workers         0                                         ; the total accounts (deposits) of Workers in this bank
    set Clients-Accounts-Capitalists     0                                         ; the total accounts (deposits) of Capitalists in this bank
    set Clients-Accounts-Households      0                                         ; the total accounts (deposits) of Households (Workers and Capitalists) in this bank
    set Clients-Accounts-at-the-Bank_1   0                                         ; the sum of all previous variables (sum of Firms and Households accounts), previous period
    set Clients-Accounts-at-the-Bank     0                                         ; the sum of all previous variables (sum of Firms and Households accounts)
    set Clients-Loans-C-Firms            0                                         ; the total loans of C-Firms in this bank
    set Clients-Loans-K-Firms            0                                         ; the total loans of K-Firms in this bank
    set Clients-Loans-with-the-Bank_1    0                                         ; the total loans Firms in this bank, previous period
    set Clients-Loans-with-the-Bank      0                                         ; the total loans Firms in this bank
    set Number-of-Firm-Clients           0
    set Number-of-Household-Clients      0
    set Number-of-Clients                0
    set Available-Credit-Basel2          0                                         ; maximum available credit under Basel II rules
    set Available-Credit-Basel31         0                                         ; maximum available credit under Basel III rules, Global Capital Framework
    set Available-Credit-Basel32         0                                         ; maximum available credit under Basel III rules, Global Liquidity Requirement
    set Available-Credit-Basel           0                                         ; maximum available credit under Basel rules
    set Own-Reserves                     0                                         ; reserves of the bank, deposits multiplied by the reserve requirement
    set Need-Cash                        0                                         ; initial value for cash needed after production, because heavy losses
    set Profit                           0                                         ; revenue less the expenditures, considering taxes
    set PBT                              0                                         ; profits before taxes
    set I-Received                       0                                         ; local variable
    set D-Received                       0                                         ; local variable
    set Overdraft                        0                                         ; this is the difference betwween own liquid assets and losses
    ; properties relocated from the setup-globals
    set Available-Credit-Basel            0                                             ; this is the credit limit to retail banks from Basel macroprudential rules
    set Available-Credit-Basel2           0                                             ; maximum available credit under Basel II rules
    set Available-Credit-Basel31          0                                             ; maximum available credit under Basel III rules, Global Capital Framework
    set Available-Credit-Basel32          0                                             ; maximum available credit under Basel III rules, Global Liquidity Requirement
    ]
end 

to Setup-C-Firms
   ask n-of Number-of-C-Firms patches [                                       ; this command asks a number of patches controlled by a slider with random coordinates
    sprout-Firms 1 [                                                          ; ask to create one firm at these patches
      move-to one-of patches with [not any? Firms-here]                       ; if a C-Firm and K-Firm are at the same patch, move the K-Firm in the setup process
      set shape                      "factory"                                ; just for fun, not necessary for the model, used only for display in HUD netlogo
      set size                       2                                        ; just for fun, not necessary for the model, used only for display in HUD netlogo
      set color                      orange                                   ; just for fun, not necessary for the model, used only for display in HUD netlogo
      set C-Firm?                    true                                     ; proper of the Firms, true means it is a consumption producer firm
      set Owner?                     true                                     ; this firm will have an owner
      set Price                      2                                        ; initial value for price
      set Capital                    Initial-capital                          ; initial value for capital
      set Stock                      Initial-production-C-firms               ; initial value for stock
      set Production                 Initial-production-C-firms               ; initial value for production
      set Revenue                    0                                        ; initial value for revenue
      set Sales                      0                                        ; initial value for sales
      set Profit                     0                                        ; revenue less the expenditures, considering taxes
      set PBT                        0                                        ; profits before taxes
      set Need-Cash                  0                                        ; initial value for cash needed before production, because lack of liquidity for starting it
      set Cases-of-Bankruptcy        0                                        ; the total number of bankruptcies by this firm
      set Available-Credit-Assenza   0                                        ; maximum available credit under internal risk calculations of the bank
      set Desired-Investment         0                                        ; initial value for desire investment
      set Investment                 0                                        ; initial value for investment
      set Number-of-Employees        0                                        ; initial value for number of employees
      set Need-of-Employees          0                                        ; initial value for desire employees
      set K-Firm-List               [ ]                                       ; setup for the list which will be used to colect the K-Firms visited
      set Vacancy                    0                                        ; initial value for vacancy
      set Bank-Account-Firm          Initial-liquidity-of-Firms               ; initial money deposited at the bank by the firms
      set Investment-Memory          Initial-Capital                          ; initial value for Investment-Memory, parameter utilized to calculate the desire investment
      set Util-Capacity              0                                        ; initial value for util-capacity
      create-banker-from             min-one-of banks [distance myself] [set hidden? true]      ; this create a link between the bank and the capitalist
      set My-Nearest-Bank            min-one-of banks [distance myself]       ; this bank is the same to which the C-Firms is now linked with a "banker" relationship
      ]
    ]
end 

to Setup-K-Firms
   ask n-of Number-of-K-Firms patches  [                                   ; this command asks a number of patches controlled by a slider randomly selected
      sprout-Firms 1 [                                                     ; ask to create one firm in each of those patches
      move-to one-of patches with [not any? Firms-here]                    ; if a C-Firm and K-Firm are at the same patch, move the K-Firm in the setup process
      set shape                      "factory"                             ; just for fun, not necessary for the model, used only for display in HUD netlogo
      set size                       2                                     ; just for fun, not necessary for the model, used only for display in HUD netlogo
      set color                      green                                 ; just for fun, not necessary for the model, used only for display in HUD netlogo
      set C-Firm?                    false                                 ; proper of Firms, false mean it is a capital producer firm
      set Owner?                     true                                  ; this firm will have an owner
      set Price                      2                                     ; initial value for price
      set Stock                      Initial-production-K-firms            ; initial value for stock
      set Production                 Initial-production-K-firms            ; initial value for production
      set Revenue                    0                                     ; initial value for revenue
      set Sales                      0                                     ; initial value for sales
      set Profit                     0                                     ; revenue less the expenditures, considering taxes
      set PBT                        0                                     ; profits before taxes
      set Need-Cash                  0                                     ; initial value for cash needed before production, because lack of liquidity for starting it
      set Cases-of-Bankruptcy        0                                     ; the total number of bankruptcies by this firm
      set Available-Credit-Assenza   0                                     ; maximum available credit under internal risk calculations of the bank
      set Desired-Investment         ""                                    ; not applied to K-Firms
      set Investment                 ""                                    ; not applied to K-Firms
      set Number-of-Employees        0                                     ; initial number for employees
      set Need-of-Employees          0                                     ; initial value for desired employees
      set Vacancy                    0                                     ; initial value for vacancy
      set Bank-Account-Firm          Initial-liquidity-of-Firms            ; initial money deposited at the banks by the firms
      set Investment-Memory          ""                                    ; not applied to K-Firms
      set Util-Capacity              ""                                    ; not applied to K-Firms
      create-banker-from             min-one-of banks [distance myself] [set hidden? true]   ; this create a link between the bank and the capitalist
      set My-Nearest-Bank            min-one-of banks [distance myself]    ; this bank is the same to which the K-Firms is now linked with a "banker" relationship
      ]
    ]
end 

to Setup-Workers
   create-Households Number-of-Workers [
    setxy                            random-xcor random-ycor                   ; the initial position of the worker is random
    set shape                       "person"                                   ; just for fun, not necessary for the model, used only for display in HUD netlogo
    set size                         1.25                                      ; just for fun, not necessary for the model, used only for display in HUD netlogo
    set color                        yellow                                    ; just for fun, not necessary for the model, used only for display in HUD netlogo
    set Worker?                      true                                      ; property of the household, "true" indicates it is a worker
    set Employed?                    false                                     ; all workers are unemployed at the start
    set Human-Wealth                 1                                         ; initial value for Human Wealth, utilized to calculate the consumption process
    set Current-Income               0                                         ; intitial income
    set Bank-Account-Household       Initial-households-personal-assets        ; initial value of deposits at the banks
    set Desired-Consumption          0                                         ; initial value for desired Consumption
    set Consumption                  0                                         ; initial value for Consumption
    set C-Firm-List                 [ ]                                        ; setup for the list which will be used to record the C-Firms visited
    create-banker-from               min-one-of banks [distance myself] [set hidden? true]       ; this create a link between the bank and the capitalist
    set My-Nearest-Bank              min-one-of banks [distance myself]        ; this bank is the same to which the Worker is now linked with a "banker" relationship
   ]
end 

to Setup-Capitalists
   create-Households (Number-of-C-Firms + Number-of-K-Firms) [                ; one capitalist for each firm distributed ramdomly in space
    setxy                           random-xcor random-ycor                   ; the initial position of the worker is random
    set shape                      "person"                                   ; just for fun, not necessary for the model, used only for display in HUD netlogo
    set size                        1.25                                      ; just for fun, not necessary for the model, used only for display in HUD netlogo
    set color                       white                                     ; just for fun, not necessary for the model, used only for display in HUD netlogo
    set Worker?                     false                                     ; proper of the household, false means it is a capitalist
    set Bankrupt?                   false
    set Human-Wealth                1                                         ; initial value for human wealth
    set Current-Income              0                                         ; initial value for current income
    set Bank-Account-Household      Initial-households-personal-assets        ; initial value for deposit at bank
    set Desired-Consumption         0                                         ; initial value for Desired-Consumption, D-C is the budget allocated to consumption
    set Consumption                 0                                         ; initial value of Consumption
    set C-Firm-List                [ ]                                        ; setup for the list which will be used to collect the price of the C-Firms visited
    create-owner-from               one-of Firms with [not any? out-link-neighbors] [set hidden? true] ; this create a link between the firm and the capitalist
    create-banker-from              min-one-of banks [distance myself] [set hidden? true]              ; this create a link between the bank and the capitalist
    set My-Nearest-Bank             min-one-of banks [distance myself]        ; this bank is the same to which the Capitalist is now linked with a "banker" relationship
   ]
end 


; TO GO

to Go
   Function-Job-Market                                            ; this function plays the job market process
   Function-Consumption-Market                                    ; this function plays the consumption market process
   Function-Capital-Market                                        ; this function plays the capital market process
   Function-UpDate-Production                                     ; this function plays the production process

   Function-UpDate-Globals                                        ; this function update the globals
   Function-Cash-Flows-Dividends                                  ; this function update the cash flow and set the dividends

   Function-Credit-Market                                         ; this function update the credit market

   Function-Central-Bank                                          ; this function give loans to the banking system and set macropudential rules and monetary policy
   Function-State-Manage-Budget                                   ; the government appears getting taxes and giving subsidies to families, helping banks and during a crisis period and selling public debt

   Function-Update-System

   tick                                                           ; netlogo needs this because it controlates time
end 



; FUNCTIONS


; TO FUNCTION-JOB-MARKET


To Function-Job-Market                              ; here will be called the subfunctions
  ask Firms [                                       ; reset the firms need for cash and update the desire workers number
      SubF-UpDate-Desired-Workers
      set Need-Cash                    0
  ]

  ask Workers with [Current-Income = 0] [           ; ask workers which do not have a job to look for one
      SubF-Find-a-Job
  ]
  ask Workers  [ set Bank-Account-Household    Bank-Account-Household + Current-Income         ] ; ask workers to update their income
  ask Firms    [ set Bank-Account-Firm         Bank-Account-Firm - Number-of-Employees * wage  ] ; ask firms to update their bank account
end 

to SubF-UpDate-Desired-Workers                                                                                        ; this subfunction update the desired workers
   if C-Firm?  [                                                                                                      ; only C-Firms run this
     set Need-of-Employees   min list Need-of-Employees ((Capital * Productivity-of-capital) / Productivity-of-labor) ; set desire employee considering the capital production restriction (Assenza, Gatti, Grazzini et al. 2015, eq. 5.9)
     if Hiring-Rationality? [                                                                                         ; if this switch is on, the firm will hire employees limited to the Bank-Account-Firm resources
         if Need-of-Employees * Wage > Bank-Account-Firm [                                                            ; if Need-of-Employees multiplied by wage is larger than the Bank-Account, the Need-of-Employees is updated
            set Need-of-Employees      max list 0 (int (Bank-Account-Firm / Wage) + 1)                                ; update the desired employees considering the money available
         ]
     ]
   ]
   set Vacancy                         Need-of-Employees   -   Number-of-Employees     ; opening new vacancies to contract more employees
   while [Vacancy < 0 and Number-of-Employees > 0] [                                   ; if vacancy < 0 the firm needs to fire someone
    ask one-of my-out-hireds [                                                         ; choose one employee
        ask other-end [                                                                ; ask this employee to set...
            set Current-Income         0                                               ; their income as 0, it was fired (die)
            set Employed?              false                                           ; the worker is now unemployed
        ]
    die                                                                                ; "die" means this worker is fired (the link disappears)
    ]
    set Vacancy                        Vacancy               + 1                       ; record the fired worker
    set Number-of-Employees            Number-of-Employees   - 1                       ; update the number of employees after the firing process
   ]
end 

to SubF-Find-a-Job                                                                                    ; this subfunction is used by the worker trying to find a job position
   let extension                             0
   repeat 3 [                                                                                         ; the worker will repeteat the process two times
      if Employed? = true [ stop ]                                                                    ; if the worker finds a job the seach process stops
      let aFirm one-of Firms in-radius (radius-for-employment-search + extension) with [Vacancy > 0 ] ; the worker looks for a firm around him with vacancies
      if aFirm != nobody [
         create-hired-from                   one-of Firms-here [set hidden? true]                     ; this link means the worker has a job in a firm, and the two know about eachother
         set Current-Income                  Wage * (1 - tax1)                                        ; update the current-income of the worker
         set State-Budget                    State-Budget + wage * tax1                               ; the tax on income goes to the State
         set Employed?                       true                                                     ; the worker is employed now
         ask aFirm [
             set Number-of-Employees      Number-of-Employees + 1                             ; update the number of employees
             set Vacancy                  Vacancy             - 1                             ; update the vacancies
         ]
      ]
      if aFirm = nobody [
         set Current-Income                 0
         set extension                      extension + 10                    ; a new search starts widening the radius
      ]
  ]
  if Do_We_Have_State? = true and Employed? = false [
     SubF-Get-Unemployment-Benefits                                ; get unemployment benefits if the worker is unemployed
  ]
end 

to SubF-Get-Unemployment-Benefits
   let Unemployment-Benefit                 Wage * Unemployment-Cover                   ; the unemployment benefits is a fraction (= u-cover) of the wage
   ifelse Do_We_Have_Central-Bank? = true and QEasing? = true [                         ; if there is a Central Bank and Quantitative Easing policy, this authority will buy any amount of Public Debt, so there are no constraints
          set Current-Income                Unemployment-Benefit                        ; if the worker is unemployed and his/her Current income is zero the State pays unemployment benefits
          set State-Budget                  State-Budget - Unemployment-Benefit         ; the tax on income goes to the State
          set Helped-Households             Helped-Households + 1                       ; the total number of households helped is increased
   ] [
          if State-Budget >= Unemployment-Benefit [                                     ; if there is enough budget available the State pays the benefits, and the Central Bank help is unnecessary
             set Current-Income             Unemployment-Benefit                        ; if the worker is unemployed and its Current income is zero the State pays unemployment benefits, a tax free subsidy
             set State-Budget               State-Budget - Unemployment-Benefit         ; the tax on income goes to the State
             set Helped-Households          Helped-Households + 1                       ; the total number of households helped is increased
          ]
   ]
end 



; FUNCTION-CONSUMPTION-MARKET

to Function-Consumption-Market                                           ; here will be called the subfunctions of the consumption market
   ask C-Firms [
       set Demand                      0
       set Sales                       0
       set Revenue                     0
   ]                                                                     ; updating properties of the C-Firms
   ask Households [                                                      ; explicit
       SubF-UpDate-Desired-Consumption                                   ; call subfunction for households update their desired consumption
       SubF-Visit-C-Firms                                                ; call subfunction for households visit firm trying to consume
       if Desired-Consumption > 0 [ SubF-Try-Consume ]                   ; if the household wish to consume something, it tries to buy it
   ]
end 

to SubF-UpDate-Desired-Consumption
   set Human-Wealth                   (Memory-parameter-human-wealth * Human-Wealth) + (1 - Memory-parameter-human-wealth) * Current-Income                          ; update human wealth (eq 2)
   set Desired-Consumption             min list  Bank-Account-Household  ((Fraction-of-wealth-devoted-to-consumption * Bank-Account-Household) + Human-Wealth)       ; update desired consumption, it can not be higher than the money the household has
   set Desired-Consumption             max list  0 Desired-Consumption                                                                                               ; this ensures the desired consumption is not negative
end 

to SubF-Visit-C-Firms                                                                                         ; this subfunction rules the shopping process, visiting the firms
  set C-Firm-List sort-by [ [?1 ?2] -> [Price] of ?1 < [Price] of ?2] C-Firms in-radius 30 with [Stock > 0]   ; we build a list with the C-Firms in the neighborhood ordered by price, assuming the household doesn't have the prices of all C-Firms because of time constraints
end 

to SubF-Try-Consume                                                                              ; the household doesn't take the lowest price...
  let listposition floor random-gamma 1.2 0.66                                                   ; ... but applies a distribution to the ordered list, because information is not perfect, scale = 1/lambda, shape/lamda 1.2/0.66 CDF: 0 (0) 1 (0.39) 2 (0.66) 3 (0.81) 4 (0.90)
  if listposition >= (length C-Firm-List) [set listposition 0]                                   ; in this way we increase the probability of the lowest price, by adding up those cases in which the gamma give us a number larger than the length of the list
  print listposition
  let Selected-C-Firm                          (item listposition C-Firm-List)                   ; auxiliar variable
  let Qtt                                       Desired-Consumption / [Price] of Selected-C-Firm ; total number of consumption goods desired
  let expenses                                  0                                                ; auxiliar variable to update the deposit at bank later
  let new-cons                                  0                                                ; auxiliar variable to record the quantity consumed
  while [Qtt > 0 and empty? C-Firm-List = false] [                                               ; if there is desired-consumption not satisfied and the list of firms is not empty...
        ask Selected-C-Firm [
        ifelse [Stock] of Selected-C-Firm > Qtt [                                                ; if there are enough available goods at the first firm ...
            set Demand                          Demand + Qtt                                     ; update the demand of Selected-Firm
            set Stock                           Stock  - Qtt                                     ; updated the stock of the firm
            set Sales                           Sales  + Qtt                                     ; update the sales
            set Revenue                         Revenue + Price * Qtt                            ; update the revenue
            set Expenses                        Expenses + Price * Qtt * (1 + tax3)              ; update the auxiliar variable, used later to update the household bank account
            set State-Budget                    State-Budget + Price * Qtt * tax3                ; update State's budget considering consumption taxes (tax3)
            set new-cons                        new-cons + Qtt                                   ; update the auxiliar variable to register the qtt consumed
            set Qtt                             0                                                ; means no need to bought anymore
        ] [                                                                                      ; second situation, buying only part at the first firm
            set Sales                           Sales  +  Stock                                  ; update sales
            set Revenue                         Price  *  Stock + Revenue                        ; update revenue
            set expenses                        Price  *  Stock * (1 + tax3) + expenses          ; update auxiliar variable, later used to update the bank account of the household
            set State-Budget                    State-Budget + Price * Stock * tax3              ; update State income
            set new-cons                        new-cons  +  Stock                               ; update stock
            set Qtt                             Qtt  -  Stock                                    ; update auxiliar variable to register the Qtt consumed, Qtt = Qtt - S
            set Stock                           0                                                ; update stock
        ]
        ]
        set C-Firm-List remove-item listposition C-Firm-List                                     ; we remove the Firm with depleted Stock
        set listposition floor random-gamma 1.2 0.66                                             ; the firm don't take the lowest price, but applies a distribution to the list, because information is not perfect, scale = 1/lambda, shape/lamda 1.2/0.66 CDF: 0 (0) 1 (0.39) 2 (0.66) 3 (0.81) 4 (0.90)
        if listposition >= (length C-Firm-List) [set listposition 0]                             ; in this way we increase the probability of the lowest price, by adding up those cases in which the gamma give us a number larger than the length of the list, the maximum length of the list
        set Selected-C-Firm                    (item listposition C-Firm-List)                   ; auxiliar variable, record the quantity that can be bought, DC/Pa
  ]
  set Consumption                               new-cons                                         ; update the Consume of the households, the real value that the household did consume
  set Bank-Account-Household                    Bank-Account-Household - expenses                ; update the bank account of the households with the remaining money after the purchasing process
end 



; FUNCTION-CAPITAL-MARKET

to Function-Capital-Market                                                           ; this function set the rules for the capital goods market
  ask K-Firms [                                                                      ; update K-Firms properties
    set Demand                     0
    set Revenue                    0
    set Sales                      0
  ]
  ask C-Firms [                                                                      ; updating the C-Firms properties
    set Investment                 0
    SubF-UpDate-Investment-Desire                                                    ; call sub-function to update investment
    if Desired-Investment > 0    [ SubF-UpDate-Investment ]                          ; if there is need for investment call the sub-function for investment
  ]
end 

to SubF-UpDate-Investment-Desire                                                                                                                                                   ; sub-function with procedure to update the investment need of a C-Firm
  set Desired-Investment           0                                                                                                                                               ; reset variable
  let rand                         random-float 1                                                                                                                                  ; auxiliar sub-function variable
  if  rand < Probability-of-investing [                                                                                                                                            ; check if it is time to invest, because only a fraction of C-Firms (= probability) can invest
      if ticks > 1 [                                                                                                                                                               ; assure that there is no investment in time equal zero
         set Investment-Memory    (Memory-parameter-investment * Investment-Memory) + (1 - Memory-parameter-investment) * Util-Capacity * Capital                                  ; begin of equation of capital motion (eq 10 & Assenza, Gatti, Grazzini et al. 2015, p. 12)
         set Desired-Investment    max list 0 (( (1 / Desired-capacity-utilization-rate) + (Depreciation-of-capital-C / Probability-of-investing) ) * Investment-Memory - Capital) ; end of equation of capital motion (eq 12 & Assenza, Gatti, Grazzini et al. 2015 eq. 5.7)
      ]
  ]
end 

to SubF-UpDate-Investment                                       ; this subfunction is called when there is need for investment (asking C-Firms)
  if Desired-Investment > 0 [                                   ; just trying to find product in two diferents K-Firms
     SubF-Visit-K-Firms                                         ; make a list with all K-Firms, take note of their prices
     SubF-Buy-Capital                                           ; sub-function used to bought capital
  ]
end 

to SubF-Visit-K-Firms                                                                              ; this subfunction rules the shopping process, visiting the firms
   set K-Firm-List sort-by [ [?1 ?2] -> [Price] of ?1 < [Price] of ?2] K-Firms with [Stock > 0]    ; we build a list with the all the K-Firms ordered by price. We have the prices of all K-Firms because they are few and capital is expensive
end                                                                                                 ; C-Firms have no constraits and they have a complete list and make no mistakes in ordering the prices

to SubF-Buy-Capital                                                                                ; asking C-Firms
  let Selected-K-Firm                           first K-Firm-List                                  ; auxiliar variable
  let Qtt                                       Desired-Consumption / [Price] of Selected-K-Firm   ; total number of consumption goods desired
  let expenses                                  0                                                  ; auxiliar variable to update the deposit at bank later
  let new-inv                                   0                                                  ; auxiliar variable to record the quantity of capital adquired by the C-Firm
  while [Qtt > 0 and empty? K-Firm-List = false] [
        ask Selected-K-Firm [
        ifelse [Stock] of Selected-K-Firm > Qtt [                                           ; if there is not available goods at the first firm ...
            set Demand                          Demand + Qtt                                ; update the demand of Selected-Firm
            set Stock                           Stock  - Qtt                                ; updated the stock of the firm
            set Sales                           Sales  + Qtt                                ; update the sales
            set Revenue                         Revenue + Price * Qtt                       ; update the revenue
            set Expenses                        Expenses + Price * Qtt                      ; update the auxiliar variable, used later to update the household bank account
            set new-inv                         new-inv + Qtt                               ; update the auxiliar variable to register the qtt consumed
            set Qtt                             0                                           ; means no need to bought anymore
        ] [                                                                                 ; second situation, buying only part at the first firm
           set Sales                            Sales  +  Stock                             ; update sales
           set Revenue                          Price  *  Stock + Revenue                   ; update revenue
           set expenses                         Price  *  Stock + Expenses                  ; update auxiliar variable, later used to update the bank account of the household
           set new-inv                          new-inv  +  Stock                           ; update stock
           set Qtt                              Qtt  -  Stock                               ; update auxiliar variable to register the Qtt consumed, Qtt = Qtt - S
           set Stock                            0                                           ; update stock
        ]
        ]
        set K-Firm-List                         remove-item 0 K-Firm-List                   ; we remove the Firm with depleted Stock
        set Selected-K-Firm                     first K-Firm-List                           ; auxiliar variable
  ]
  set Investment                                new-inv                                     ; update the Consumption of the households, the real value that the household did consume
  set Bank-Account-Firm                         Bank-Account-Firm - Expenses                ; update the bank account of the households with the remaining money after the purchasing process
end 



; FUNCTION-UPDATE-PRODUCTION

to Function-UpDate-Production                                                                           ; this function update the production of Firms
    ask K-Firms [                                                                                       ; updating the production of K-Firms (eqs 15, 17 & 18)
        set Production                  Number-of-Employees * Productivity-of-labor                     ; updating actual production
        set Stock                       Stock * (1 - Depreciation-of-capital-K) + Production            ; updating stock, depreciation-of-capital is currently set at 2%, but K firms do not use capital so this is deterioration of unused stocks
        set Bank-Account-Firm           Bank-Account-Firm + Revenue                                     ; update bank account
        set Delta                       Production - Demand                                             ; variable used to decide new production
        ifelse K-Qtt-Function?        [ set Need-of-Employees  Report-K-Update-Need-of-Employees ]      ; if the switcher at HUD is turned on, you have a complex function below
                                      [ set Need-of-Employees  Demand / Productivity-of-labor    ]      ; ... if the switcher at HUD is turned off, you have the easy way, and the demand determines the number of employees
        ifelse K-UpDate-Price?        [ set Price              Report-K-Update-Price             ]      ; if the switcher at HUD is turned on, you have a complex function below
                                      [ set Price              Wage / Productivity-of-labor      ]      ; ... the switcher at HUD is turned off, you have the easy way
    ]
    ask C-Firms [                                                                                                                   ; updating the production of C-Firms
        set Capital                     Capital - Capital * Util-Capacity * Depreciation-of-capital-C + Investment                  ; update the capital avalible for production process (eq 5.5 of Assenza, Gatti, Grazzini et al. 2015)
        set Production                  min list (Number-of-Employees * Productivity-of-labor) (Capital * Productivity-of-capital)  ; update actual production limited by the available capital
        set Stock                       Production                                                                                  ; the C-Goods are perishable, so the actual stock are equal the production
        set Util-Capacity               Production / (Capital * Productivity-of-capital)                                            ; utilized capacity (eq 5.4 of Assenza, Gatti, Grazzini et al. 2015)
        set Bank-Account-Firm           Bank-Account-Firm + Revenue                                                                 ; update bank account
        set Delta                       Production - Demand                                                                         ; variable used to decide new production level
        ifelse C-Qtt-Function?        [ set Need-of-Employees  Report-C-Update-Need-of-Employees ]                                  ; if the switcher at HUD is turned on, you have a complex function below
                                      [ set Need-of-Employees  Demand / Productivity-of-labor    ]                                  ; ... if the switcher at HUD is turned off, you have the easy way
        ifelse C-UpDate-Price?        [ set Price              Report-C-Update-Price             ]                                  ; if the switcher at HUD is turned on, you have a complex function below
                                      [ set Price              Wage / Productivity-of-labor      ]                                  ; ... if the switcher at HUD is turned off, you have the easy way
    ]
end 

to-report Report-C-Update-Price                                                                                                     ; reporting the new price for C-Firms ...
  let N-P                     Price                                                                                                 ; local auxiliar variable
  if  (delta <= 0) and       (Price <  Goods-Price-Level)  [ set N-P  Price * (1 + random-float 1 * Price-adjust-parameter)  ]      ; rule to increase price, approaching it to that of the competitors... the jump is stochastic (eq 5.2 and fig.2 of Assenza, Gatti, Grazzini et al. 2015)
  if  (delta >  0) and       (Price >  Goods-Price-Level)  [ set N-P  Price * (1 - random-float 1 * Price-adjust-parameter)  ]      ; rule to reduce price, approaching it to that of the competitors... the jump is stochastic (eq 5.2 and fig.2 of of Assenza, Gatti, Grazzini et al. 2015)
  report                      N-P                                                                                                   ; report new price
end 

to-report Report-K-Update-Price                                                                                                     ; reporting the new price for K-firms
  let N-P                     Price                                                                                                 ; local auxiliar variable
  if (delta <= 0) and        (Price < Capital-Price-Level) [ set N-P Price * (1 + random-float 1 * Price-adjust-parameter )  ]      ; rule to increase price, approaching it to that of the competitors... the jump is stochastic (eq 6.5 of Assenza, Gatti, Grazzini et al. 2015)
  if (delta >  0) and        (Price > Capital-Price-Level) [ set N-P Price * (1 - random-float 1 * Price-adjust-parameter )  ]      ; rule to reduce price, approaching it to that of the competitors... the jump is stochastic (eq 6.5 of Assenza, Gatti, Grazzini et al. 2015)
  report                      N-P                                                                                                   ; report new price
end 

to-report Report-C-Update-Need-of-Employees                                                                                                         ; reporting new C-Firm needs for employees (eq 14)
  let N-E                     Number-of-Employees                                                                                                   ; local auxiliar variable
  if (delta <= 0) and        (Price >= Goods-Price-Level)  [ set N-E ((Production - Quantity-adjust-parameter * delta) / productivity-of-labor) ]   ; possible condition to increase actual number of employees and production (eq 5.1 and fig.2 of of Assenza, Gatti, Grazzini et al. 2015)
  if (delta >  0) and        (Price <  Goods-Price-Level)  [ set N-E ((Production - Quantity-adjust-parameter * delta) / productivity-of-labor) ]   ; other possible condition reduce actual number of employees and production (eq 5.1 and fig.2 of of Assenza, Gatti, Grazzini et al. 2015)
  report                      N-E                                                                                                                   ; report new desired employees
end                                                                                                                                                  ; if (delta <= 0) and (Price < Goods-Price-Level) or the contrary the production does not change and the prices adjust

to-report Report-K-Update-Need-of-Employees                                                                                                                  ; reporting new need for a C-firm employees
  let N-E                     Number-of-Employees                                                                                                            ; local auxiliar variable
  if (delta <= 0) and        (Price >=  Capital-Price-Level) [ set N-E ((Production - Quantity-adjust-parameter * delta - Stock) / productivity-of-labor) ]  ; possible condition to change actual number of employees and production, but we substract the stock (eq 6.6 of of Assenza, Gatti, Grazzini et al. 2015)
  if (delta >  0) and        (Price <   Capital-Price-Level) [ set N-E ((Production - Quantity-adjust-parameter * delta - Stock) / productivity-of-labor) ]  ; other possible condition to change actual number of employees (eq 6.6 of of Assenza, Gatti, Grazzini et al. 2015)
  report                      N-E                                                                                                                            ; report new need for employees
end 



; UPDATE GLOBALS

to Function-UpDate-Globals                                                                                              ; this function update the globals
  set Unemployment-Rate               1 - ((sum [Number-of-Employees] of Firms) / Number-of-Workers)                    ; update the unemployemnt rate
  set GDP_1                           GDP                                                                               ; store the previous value for the next period
  set GDP                             sum [Production] of Firms - sum [Stock] of K-Firms                                ; update the GDP, sum production - stocks
  if GDP < 0                         [set GDP 1]
  ifelse GDP_1 > GDP [
         set Recession-lenght         Recession-lenght + 1                                                              ; we define here a counter for recessions, to be used later
  ] [
         set Recession-lenght         0                                                                                 ; if there is no recession, the counter is set to zero
  ]
  if ticks > 1 [
     set Growth-Rate                 (GDP - GDP_1) / GDP_1
  ]
  if GDP_1 > GDP and Recession-lenght > 2 [
     set QEasing?   true                                                                                                ; QEasing means Quantitative Easing,and this is a policy that opens unlimited buying of Public Debt
  ]
  if GDP > GDP_1 or Recession-lenght = 0 [
     set QEasing?   false                                                                                               ; QEasing means Quantitative Easing,and this is a policy that opens unlimited buying of Public Debt
  ]
  set Total-Investment                sum [Investment] of C-Firms                                                       ; update investment realized by the C-Firms
  set Total-Consumption               sum [Consumption] of Households                                                   ; update the consumption
  set Total-Loans-Firms               sum [Current-Retail-Loans] of Firms                                               ; update the sum of retail loans, all firms
  set Total-Loans-C-Firms             sum [Current-Retail-Loans] of C-Firms                                             ; update the sum of retail loans for C-Firms
  set Total-Loans-K-Firms             sum [Current-Retail-Loans] of K-Firms                                             ; update the sum of retail loans for K-Firms
  set Total-Deposits-Workers          sum [ Bank-Account-Household ] of Workers                                         ; explicit
  set Total-Deposits-Capitalists      sum [ Bank-Account-Household ] of Capitalists                                     ; explicit
  set Total-Deposits-C-Firms          sum [ Bank-Account-Firm ] of C-firms                                              ; explicit
  set Total-Deposits-K-Firms          sum [ Bank-Account-Firm ] of K-firms                                              ; explicit
  set Total-Deposits_1                Total-Deposits                                                                    ; explicit
  set Total-Deposits                  Total-Deposits-Workers + Total-Deposits-Capitalists + Total-Deposits-C-Firms + Total-Deposits-K-Firms     ; explicit
  set Total-Interest-Payments         sum [ Interest-Pay    ] of Firms                                                  ; explicit
  set Total-Installment-Payments      sum [ Installment-Pay ] of Firms                                                  ; explicit
  set Total-Reserves                  RR * Total-Deposits                                                               ; reserves of the banks deposited at the central bank
  set Goods-Price-Level_1             Goods-Price-Level                                                                 ; store the Goods-Price-Level value for use with adaptative functions
  set Capital-Price-Level_1           Capital-Price-Level                                                               ; store the Capital-Price-Level value for use with adaptative functions
  if sum [Sales] of C-Firms != 0    [ set Goods-Price-Level   sum [ Revenue ] of C-Firms / sum [Sales] of C-Firms ]     ; update the goods price level
  if sum [Sales] of K-Firms != 0    [ set Capital-Price-Level sum [ Revenue ] of K-Firms / sum [Sales] of K-Firms ]     ; update the capital price level
  set Current-Number-of-C-Firms       count C-Firms                                                                     ; current number of C-Firms
  set Current-Number-of-K-Firms       count K-Firms                                                                     ; current number of K-Firms
  set Current-Number-of-Workers       count Workers                                                                     ; current number of Workers
end 



; FUNCTION-CASH-FLOWS AND DIVIDENDS

to Function-Cash-Flows-Dividends                                                                 ; this function sets the payment of dividends and cash-flows adjustments
  ask C-Firms [                                                                                  ; Cash flow of C-Firms
      set PBT     Revenue + Bank-Account-Firm * eta3 - Number-of-Employees * Wage - Desired-Investment * Capital-Price-Level - (annuity-rate + eta0) * Current-Retail-Loans  ; PBT is profits before taxes
      let div     0                                                                              ; auxiliar variable
      if Dividends-Payments? [                                                                            ; HUD control for activating dividends payments
         if PBT > 0 [                                                                            ; if the PBT is positive, the firm pay dividends and taxes
            set Profit                              PBT * (1 - tax2)                             ; the profit is reduced by a tax
            set State-Budget                        State-Budget + PBT * tax2                    ; the State collects the taxes
            set Dividend                            Dividend-payout-ratio * Profit               ; if there was a positive profit, setup dividend, the income of capitalists
            set Bank-Account-Firm                   Bank-Account-Firm - Dividend                 ; reduce the bank account the dividend which will be payed to the capitalist
            set Div                                 Dividend                                     ; auxiliar variable bring the div to the capitalist later
            ask one-of my-out-owners [                                                           ; calling the owner of this firm, where my-out- calls "all links you can use to travel from this node"
                ask other-end [                                                                  ; at other end of the link is the capitalist
                    set Current-Income              div * (1 - tax1)                             ; update the current income, substracting the income taxes
                    set Bank-Account-Household      Bank-Account-Household + Current-Income      ; update the household bank account of the capitalist
                    set State-Budget                State-Budget + div * tax1                    ; the State collects the income taxes on this dividend
               ]                                                                                 ; end asking capitalist
           ]                                                                                     ; end asking link
       ]                                                                                         ; end PBT > 0
       if PBT <=  0 [                                                                            ; if the profit is negative (losses) the problems appear
          set Profit                                PBT                                          ; if the profit was zero or negative, the tax is zero
          ifelse Bank-Account-Firm >= abs Profit [
                 set Bank-Account-Firm              Bank-Account-Firm - abs Profit               ; the losses reduce the bank-account of the firm
          ] [                                                                                    ; if the losses are larger than the bank-account of the firm a bakruptcy process starts
             set Overdraft                          abs Profit - Bank-Account-Firm               ; overdraft are losses not covered by the money available at the bank account
             set Bank-Account-Firm                  0                                            ; the losses deplete the bank account of the firm
             ask one-of my-out-owners [                                                          ; calling the owner of this firm, where my-out- calls "all links you can use to travel from this node"
                 ask other-end [                                                                 ; at other end of the link is the capitalist
                     ifelse Bank-Account-Household >=   Overdraft [
                            set Current-Income             0                                     ; update the current income of the capitalist
                            set Bank-Account-Household     Bank-Account-Household - Overdraft    ; the capitalist of the firm has to recapitalize it using his own bank-account
                 ] [

                     set Bankrupt?                          true
                     SubF-Capitalist-Damnation
            ]                                                                                     ; end the overdraft and liquidation process
                 ]                                                                                         ; end the negative profit process
            ]                                                                                         ; end the dividends distribution process
        ]
      ]
    ]
    ]                                                                                              ; end asking C-Firms

  ask K-Firms [                                                                                  ; Cash flow of K-Firms
    set PBT     Revenue + Bank-Account-Firm * eta3 - Number-of-Employees * Wage - (annuity-rate + eta0) * Current-Retail-Loans     ; PBT is profits before taxes
    let div     0                                                                                ; auxiliar variable
    if Dividends-Payments? [                                                                              ; HUD control for activating dividends payments
       if PBT > 0 [                                                                              ; if the profit is positive, the firm pay dividends and taxes
          set Profit                             PBT * (1 - tax2)                                ; the profit is reduced by a tax
          set State-Budget                       State-Budget + PBT * tax2                       ; the State collects the taxes
          set Dividend                           Dividend-payout-ratio * Profit                  ; if there was a positive profit, setup dividend, the income of capitalists
          set Bank-Account-Firm                  Bank-Account-Firm - Dividend                    ; reduce the bank account by the dividend which will be payed to the capitalist
          set div                                Dividend                                        ; auxiliar variable bring the div to the capitalist later
          ask one-of my-out-owners [                                                             ; calling the owner of this firm, where my-out- calls "all links you can use to travel from this node".
               ask other-end [                                                                   ; at other end of the link is the capitalist
                   set Current-Income            div * (1 - tax1)                                ; update the current income, substracting the income taxes
                   set Bank-Account-Household    Bank-Account-Household + Current-Income         ; update the household bank account
                   set State-Budget              State-Budget + div * tax1                       ; the State collects the taxes
               ]
          ]
       ]
       if PBT <=  0 [                                                                            ; if the profit before taxes is negative (losses) the problems appear
          set Profit                             PBT                                             ; if the profit was zero or negative, the tax is zero
           ifelse Bank-Account-Firm >= abs Profit [
                  set Bank-Account-Firm          Bank-Account-Firm - abs Profit                  ; the losses reduce the bank-account of the firms
           ] [                                                                                   ; if the losses are larger than the bank-account of the firm
           set Overdraft                         abs Profit - Bank-Account-Firm                  ; overdraft are losses not covered by the money available at the Bank Accounts
             set Bank-Account-Firm               0                                               ; the losses deplete the bank-account of the firms
             ask one-of my-out-owners [                                                          ; calling the owner of this firm, where my-out- calls "all links you can use to travel from this node".
                 ask other-end [                                                                 ; at other end of the link is the capitalist
                     let Unassumed-Losses                  Overdraft - Bank-Account-Household    ; the losses not covered by the capitalist's money lead to the dismantlement of the firm
                     if Unassumed-Losses <= 0 [
                        set Current-Income                 0                                     ; update the current income of the capitalist
                        set Bank-Account-Household         Bank-Account-Household - Overdraft    ; the capitalist of the firm has to recapitalize it using his own bank-account
                     ]                                                                           ; end of the procedure of heavy losses in which the capitalist is called for sustaining the firm
                     if Unassumed-Losses > 0 [
                        set Bankrupt?                  true
                        SubF-Capitalist-Damnation
                      ]                                                                          ; end procedure previous to bankruptcy
                ]                                                                                ; end ask capitalist
             ]                                                                                   ; end ask one-of my-out-owners
           ]                                                                                     ; end the overdraft and liquidation process
       ]                                                                                         ; end the negative profit process
       ]                                                                                         ; end the dividends distribution process
  ]                                                                                              ; end asking K-Firms


  ask Banks [                                                                                                          ; Now lets see the cash flow of Banks
    let div                             0                                                                              ; auxiliar variable
    set Clients-Accounts-C-Firms        sum [ Bank-Account-Firm ] of out-banker-neighbors with [C-Firm? = true ]       ; bank accounts of the C-Firms at a particular bank
    set Clients-Accounts-K-Firms        sum [ Bank-Account-Firm ] of out-banker-neighbors with [C-Firm? = false]       ; bank accounts of the K-Firms at a particular bank
    set Clients-Accounts-Firms          Clients-Accounts-C-Firms  + Clients-Accounts-K-Firms                           ; bank accounts of Firms at a particular bank
    set Clients-Accounts-Workers        sum [ Bank-Account-Household ] of out-banker-neighbors with [Worker? = true ]  ; bank accounts of the Workers at a particular bank
    set Clients-Accounts-Capitalists    sum [ Bank-Account-Household ] of out-banker-neighbors with [Worker? = false]  ; bank accounts of the Capitalists at a particular bank
    set Clients-Accounts-Households     Clients-Accounts-Capitalists + Clients-Accounts-Workers                        ; bank accounts of the Households at a particular bank
    set Clients-Accounts-at-the-Bank_1  Clients-Accounts-at-the-Bank
    set Clients-Accounts-at-the-Bank    Clients-Accounts-Firms + Clients-Accounts-Households                           ; total bank accounts of firms and households at a particular bank
    set Clients-Loans-C-Firms           sum [ Current-Retail-Loans ] of out-banker-neighbors with [C-Firm? = true]     ; loans to C-Firms of a particular bank
    set Clients-Loans-K-Firms           sum [ Current-Retail-Loans ] of out-banker-neighbors with [C-Firm? = false]    ; loans to K-Firms of a particular bank
    set Clients-Loans-with-the-Bank_1   Clients-Loans-with-the-Bank
    set Clients-Loans-with-the-Bank     Clients-Loans-K-Firms + Clients-Loans-C-Firms                                  ; total loans to Firms of a particular bank
    set Number-of-Firm-Clients          count out-banker-neighbors with [shape = "factory"]                            ; total number of firm clients (with accounts or loans) with this bank
    set Number-of-Household-Clients     count out-banker-neighbors with [shape = "person"]                             ; total number of household clients (with accounts) with this bank
    set Number-of-Clients               Number-of-Firm-Clients + Number-of-Household-Clients                           ; total number of clients (any kind) with this bank
    set Shares                          Own-Bank-Capital / (Current-Number-of-C-Firms + Current-Number-of-K-Firms)     ; the shares of the bank, one for every capitalist
    set I-Received                      sum [ Interest-Pay         ] of out-banker-neighbors with [shape = "factory"]  ; total interest payments of firms to a particular bank
    set D-Received                      sum [ Installment-Pay      ] of out-banker-neighbors with [shape = "factory"]  ; total installment payments of firms to a particular bank
    set Own-Reserves                    RR * Clients-Accounts-at-the-Bank                                              ; reserves of the banks deposited at the central bank
    set PBT                             I-Received + Own-Reserves * eta4 - Central-Bank-Loans * (eta2 + annuity-rate)  ; the profit income minus expenditures
    if Dividends-Payments? [                                                                                                    ; HUD control for activating dividends payments
       ifelse Profit > 0 [                                                                                             ; if the profit is positive, the firm pay dividends and taxes
           set Profit                                 PBT * (1 - tax2)                                                 ; the profit is reduced by a tax
           set State-budget                           State-budget + Profit * tax2                                     ; the State collects the taxes
           set Dividend                               Dividend-payout-ratio * Profit                                   ; if there was a positive profit, setup dividend, the income of capitalists
           set Own-Bank-Capital                       Own-Bank-Capital + Profit * (1 - tax2) - Dividend                ; reduce the bank account the dividend which will be paid to the capitalist
           set Div                                    Dividend / (Current-Number-of-C-Firms + Current-Number-of-K-Firms) ; calculate dividend as part of the total profit divided by capitalists (everyone have a share)
           ask Capitalists [                                                                                           ; call each of one of the capitalist
               let Number-of-Capitalists              Current-Number-of-C-Firms + Current-Number-of-K-Firms            ; total number of Capitalists
               set Current-Income                     Current-Income + div * (1 - tax1)                                ; increase the income of the capitalist with this new dividend
               set Bank-Account-Household             Bank-Account-Household + div * (1 - tax1)                        ; update the bank account of the capitalist
               set State-Budget                       State-Budget + tax1 * div                                        ; the State gets the income taxes
           ]
           ]  [                                                                                                        ; if the profit is negative (losses) the problems start to show up
           ifelse Own-Bank-Capital >= abs Profit [                                                                     ; the bank has liquidity for compensating the loss
                  set Own-Bank-Capital                Own-Bank-Capital - abs Profit                                    ; the losses reduce the Own-Bank-Capital of the bank
                  ask Capitalists [
                      set Current-Income              Current-Income + 0                                               ; update the current income of the capitalist, but we have to consider this is a secondary source of income for them
                  ]
           ] [                                                                                                         ; if the losses are larger than the Own-Bank-Capital
                  set Overdraft                       abs Profit - Own-Bank-Capital                                    ; overdraft are the losses not covered by the Own-Bank-Capital
                  set Own-Bank-Capital                0                                                                ; the losses deplete the Own-Bank-Capital and then...
                  ifelse Do_We_Have_State? [                                                                           ; untenable losses... if there exist a government and taxes... (we are asking banks)
                         SubF-Call-Rescue-From-State                                                                   ; ...the State goes to rescue the retail bank
                  ] [
                         SubF-Go-Bankruptcy-Banks                                                                      ; but if the State does not exist, the retail bank starts a bankruptcy process
                  ]
           ]                                                                                                           ; end procedure previous to bankruptcy
           ]                                                                                                           ; end of the managing losses process
     ]                                                                                                                 ; end of dividends procedure for banks
   ]                                                                                                                   ; end of ask banks
end 

to SubF-Capitalist-Damnation
   ask Capitalists with [Bankrupt? = true] [
       set Current-Income               0                                     ; update the current income of the capitalist/owner
       set Bank-Account-Household       Initial-households-personal-assets    ; update the bank account of the capitalist/owner
       set Worker?                      true                                  ; the capitalist becomes a worker... life is unfair
       set Employed?                    false                                 ; this worker is unemployed at the start
       set color                        yellow                                ; now you are a worker and look like one
       set size                         1.25
       set Human-Wealth                 1
       set Desired-Consumption          0
       set Consumption                  0
       set C-Firm-List                  [ ]
       ask in-owner-neighbors           [ die ]                                ; and the former firm he/she owned vanishes
       set Current-Number-of-C-Firms    Current-Number-of-C-Firms - 1          ; we correct the number of C-Firms in this economy
   ]                                                                           ; end procedure previous to bankruptcy
end 

to SubF-Call-Rescue-From-State
   if Do_We_Have_Central-Bank? = true and QEasing? = true [                                                                      ; if the Central Bank exists and it buys public debt without limits, all the deficit is converted to government bonds sold to the CB
      set State-Budget                            State-Budget -  Initial-equity-of-the-bank - Overdraft                         ; in this case the government pays the recapitalization of the bank and the unpaid overdraft
      set Own-Bank-Capital                        Initial-equity-of-the-bank
      set Profit                                  0
   ]
   if State-Budget >= (Initial-equity-of-the-bank + Overdraft) and Do_We_Have_Central-Bank? = false [                            ; if the Central Bank does not exist, the State helps the bank only if the budget has enough resources
      set State-Budget                            State-Budget -  Initial-equity-of-the-bank - Overdraft                         ; in this case the government pays the recapitalization of the bank and the unpaid overdraft
      set Own-Bank-Capital                        Initial-equity-of-the-bank
      set Profit                                  0
   ]
   if State-Budget >= (Initial-equity-of-the-bank + Overdraft) and Do_We_Have_Central-Bank? = true and QEasing? = false [        ; if the Central Bank exists but the Quantitative Easing policy is not activated, the State helps the bank only if the budget has enough resources
      set State-Budget                            State-Budget -  Initial-equity-of-the-bank - Overdraft                         ; in this case the government pays the recapitalization of the bank and the unpaid overdraft
      set Own-Bank-Capital                        Initial-equity-of-the-bank
      set Profit                                  0
   ]
   if State-Budget <= (Initial-equity-of-the-bank + Overdraft) and Do_We_Have_Central-Bank? = false [                            ; if the Central Bank does not exist and the State budget has not enough resources...
      SubF-Go-Bankruptcy-Banks                                                                                                   ; ... the bankruptcy process is started
   ]
   if State-Budget <= (Initial-equity-of-the-bank + Overdraft) and Do_We_Have_Central-Bank? = true and QEasing? = false [        ; if the Central Bank exists but the Quantitative Easing policy is not activated and the State budget hasn't enough resources...
      SubF-Go-Bankruptcy-Banks                                                                                                   ; ... the bankruptcy process is started
   ]
end 

to SubF-Go-Bankruptcy-Banks                                                                                               ; this subfunction rules the process for the Bank bankruptcy and rebuilding using capitalits' resources. We ask banks here.
   set B-Broke                                    B-Broke + 1                                                             ; increase the global parameter that counts the broke status
   let Original-Shares                            Initial-equity-of-the-bank / (Current-Number-of-C-Firms + Current-Number-of-K-Firms)    ; the original price of a share, before any serious problem appears
   let Bank-Owners                                Capitalists with [Bank-Account-Household >= Original-Shares]            ; this implies a bail-in, because the capitalits will be forced to buy again one share
   let Broken-Capitalists                         Capitalists with [Bank-Account-Household <  Original-Shares]            ; excluded capitalists are those unable to restitute their share in the banking sector, and their number is adjusted below
   let New-Shares                                 Original-Shares                                                         ; we prepare this instrumental variable for repeated use later
   let New-Shares_1                               0                                                                       ; we prepare this instrumental variable for repeated use later
   while [New-Shares > New-Shares_1] [
         set New-Shares_1                         New-Shares
         set New-Shares                           Initial-equity-of-the-bank / (count Bank-Owners)                        ; the capitalists unable to afford a new share are excluded, but as a consecuence, the price per share increases
         set Bank-Owners                          Capitalists with [Bank-Account-Household >= New-Shares]                 ; this implies a bail-in
         set Broken-Capitalists                   Capitalists with [Bank-Account-Household <  New-Shares]                 ; broken capitalists are unable to restitute their share in the banking sector, and they will lose their "capitalist" status
   ]
   ask  Bank-Owners [
        set Bank-Account-Household                Bank-Account-Household - New-Shares                                     ; update the bank account of the capitalist, reducing the account due to the money used to rebuild the bank
   ]
   ask  Broken-Capitalists [                                                                                              ; the capitalists unable to pay for the bail-in will be broken
        set Bank-Account-Household                0                                                                       ; the capitalist unable to pay for the new shares get broken
        set Worker?                               true                                                                    ; the capitalist is broken, and he/she becomes a poor worker
        set Number-of-Workers                     Number-of-Workers + 1
        set color                                 yellow                                                                  ; just for fun, not necessary for the model, used only for display in HUD netlogo
        set Human-Wealth                          1                                                                       ; initial value for Human Wealth, utilized to calculate the consumption process
        set Current-Income                        0                                                                       ; intitial income
        set Bank-Account-Household                Initial-households-personal-assets                                      ; initial value of deposits at the banks, a vital minimum
        set Desired-Consumption                   0                                                                       ; initial value for desire Consumption
        set Consumption                           0                                                                       ; initial value for Consumption
        set C-Firm-List                          [ ]                                                                      ; setup for the list which will be used to colect the C-Firms visited
        set Employed?                             false                                                                   ; the ex-capitalist is now an unemployed worker and he has to look for an employment... life is hard...
        ask one-of my-in-owners [                                                                                         ; we identify the firm (K or C) previously owned by the broken capitalist... my-in-breed means "all links that you can use to travel to this node".
            ask end1                            [ set Owner? false ]                                                      ; ...the firm at the other end of the link now is deprived of a proper owner
            die                                                                                                           ; the link representing ownership dies, the problem now is looking for a new owner for that orphan firm...
        ]
   ]
   let Newcapitalist                              n-of 1 Workers with-max [ Bank-Account-Household ]                      ; ...the orphan C-Firm or K-Firm needs one new owner, so we ask the worker with the highest savings to buy the Firm and become a capitalist
   ask Newcapitalist [                                                                                                    ; before we proceed to transform a worker into a capitalist, we broke his/her current labor contract with a (different) firm
       ask one-of my-in-hireds [                                                                                          ; the only link of this worker, future capitalist, is the labor contract
           ask other-end [                                                                                                ; we contact with the firm for which this worker is employed
               set Vacancy                        Vacancy + 1                                                             ; the worker leaves, so the firm adjust the vacancies adding an open job to the record
               set Number-of-Employees            Number-of-Employees - 1                                                 ; the firm losses one worker, which now is a capitalist unwilling to work
           ]
           die                                                                                                            ; the link, the labor contract, dies or disappear
       ]
       set shape                                 "person"                                                                 ; the metamorphosis of this person is compplete now... he comes to a new (better) life...
       set size                                   1.25                                                                    ; just for fun, not necessary for the model, used only for display in HUD Netlogo
       set color                                  white                                                                   ; he becomes white as well, the color of wealthy capitalists
       set Worker?                                false                                                                   ; false only means he/she is now a happy capitalist
       set Number-of-Workers                      Number-of-Workers - 1
       create-owner-from                          one-of Firms with [Owner? = false] [set hidden? true]                   ; this command creates a link between the orphan firm and the new capitalist and in this way one will know each other for all the purposes
       ask out-owner-neighbors                  [ set Owner? true ]                                                       ; we identify the (C or K) firm previously owned by the broken capitalist and now owned by the lucky new capitalist...
   ]
end 


; FUNCTION-CREDIT-MARKET: CREDIT AND BANKRUPTCY PROCEDURES

to Function-Credit-Market                                                  ; this function rules the credit market system

   SubF-Call-Matrix-Formation                                              ; function to set the matrix used in R to calculate the life spam of firms

   set C-Broke                         0                                   ; global variable for counting the total number of C-firms that went broke this period
   set K-Broke                         0                                   ; global variable for counting the total number of K-firms that went broke this period

   set Total-Clients-Accounts           sum [ Clients-Accounts-at-the-Bank   ] of Banks                           ; this should be equal to Total-Deposits
   set Total-Client-Loans              sum [ Clients-Loans-with-the-Bank    ] of Banks                           ; this should be equal to Total-Loans-Firms

   ask Firms [                                                             ; firms update their status with the retail bank
       SubF-Update-Installment                                             ; to update the installment
       SubF-Update-Cash-Need                                               ; to update firm cash need
       SubF-Update-Assets                                                  ; to update assets value
       SubF-Update-Leverage                                                ; to update the leverage, all this is used to rule interest rate practiced later
   ]

   ask C-Firms [
       SubF-Ask-for-C-Credit                                               ; checks if this C-firm needs credit, it will be asked in this subfunction
   ]

   ask K-firms [
       SubF-Ask-for-K-Credit                                               ; checks if this K-Firm needs credit, it will be asked in this subfunction
   ]

   ask Banks [                                                             ; the retail bank update the balance after the new was created
       if Do_We_Have_Central-Bank? [
          SubF-Ask-for-Credit-to-Central-Bank                              ; the retail bank asks for credits to the Central Bank if reserves fall bellow the prescribed level
       ]
       set Assets                      max list 0 (Own-Reserves + Clients-Loans-C-Firms + Clients-Loans-K-Firms + Own-Bank-Capital)
       set Liabilities                 max list 0 (Clients-Accounts-Workers + Clients-Accounts-Capitalists + Clients-Accounts-C-Firms + Clients-Accounts-K-Firms + Central-Bank-Loans)
       set Bank-Equity                 Assets - Liabilities
   ]

   set Total-Central-Bank-Loans    sum [Central-Bank-Loans] of Banks       ; global variable that calculates the sum of all Central-Bank-Loans to retail banks

   if C-Broke-Procedure? [                                                 ; switch check if the user want the broke procedure
      ask C-Firms [                                                        ; this rules is for C-firm broke
          if (Cases-of-Bankruptcy > T-Ban) [                               ; check if this firm did not pay their debts with a bank, where T-Ban (= 1, 2 o 4) are the Firm's number of periods unable to make payments before going to bankrupcy
              SubF-Go-Bankruptcy-C-Firms                                   ; subfunction containing the bankruptcy process
          ]
      ]
   ]

   if K-Broke-Procedure? [                                                 ; the same as the C-firm, check above for details
      ask K-Firms [
          if (Cases-of-Bankruptcy > T-Ban) [                               ; check if this firm did not pay their debts with a bank, where T-Ban (= 1, 2 o 4) are the Firm's number of periods unable to make payments before going to bankrupcy
              SubF-Go-Bankruptcy-K-Firms                                   ; subfunction containing the bankruptcy process
          ]
      ]
   ]
end 

to SubF-Call-Matrix-formation                                                                     ; subfunction that manage the R routines
  ask C-Firms [
    set Matrix-C-Firms-Bankruptcy matrix:set-and-report Matrix-C-Firms-Bankruptcy 1 Mjc Leverage  ; update the second row of the matrix with information about C-Firms: every (1, Mjc) element is replaced by Leverage
    ifelse (Cases-of-Bankruptcy < T-Ban)                                                          ; update a position with 0 if the firm is alive, and 1 if the firm went bankrupt
    [ set Matrix-C-Firms-Bankruptcy matrix:set-and-report Matrix-C-Firms-Bankruptcy 0 Mjc 0 ]     ; 0 is the first row, 1 the second row, etc. Mjc is the columns
    [ set Matrix-C-Firms-Bankruptcy matrix:set-and-report Matrix-C-Firms-Bankruptcy 0 Mjc 1 ]     ; 0 is the first row, 1 the second row, etc. Mjc is the columns
    set Mjc Mjc + 1 if Mjc > (Time-Window1 - 1) [ set Mjc 0 ]                                     ; move the matrix element to the next position, so the replacements in the matrix are sequential, and the time-window controls how many observations we'll have
  ]

  ask K-Firms [
    set Matrix-K-Firms-Bankruptcy matrix:set-and-report Matrix-K-Firms-Bankruptcy 1 Mjk Leverage  ; update the matrix with information about the K-firms
    ifelse (Cases-of-Bankruptcy < T-Ban)                                                          ; update a position with 0 if the firm is alive, and 1 if the firm went bankruptcy
    [ set Matrix-K-Firms-Bankruptcy matrix:set-and-report Matrix-K-Firms-Bankruptcy 0 Mjk 0 ]
    [ set Matrix-K-Firms-Bankruptcy matrix:set-and-report Matrix-K-Firms-Bankruptcy 0 Mjk 1 ]
    set Mjk Mjk + 1 if Mjk > (Time-Window1 - 1) [ set Mjk 0 ]                                     ; move the matrix the next position, and the time-window controls how many observations we'll have
  ]

  let A matrix:get-row Matrix-C-Firms-Bankruptcy 0                                                ; create an object with the first row of the matrix, which contains 0s and 1s, if barkrupt or not
  let B matrix:get-row Matrix-C-Firms-Bankruptcy 1                                                ; create an object with the second row of the matrix, which contains the Leverage for every C-Firm

  r:put   "a" A                                                                                   ; call the R and put there the object A
  r:put   "b" B                                                                                   ; call the R and put there the object B
  r:eval  "c <- glm(a ~ b, family = binomial)"                                                    ; call R and ask to solve the logistic function with the inputs A and B, gls stands for "generalized linear model", and binomial implies logit link between "a" and "b"

  let C  r:get "c$coefficients"                                                                   ; call R and the coefficients into object C
  set Beta_1-C-Firms  first C                                                                     ; save the beta-1 for C-firms
  if  Beta_1-C-Firms < (- 25)      [set Beta_1-C-Firms (- 25)]                                    ; assure value into a meaninful range, because the first period there is not enough information
  set Beta_2-C-Firms  last  C                                                                     ; save the beta-2 for C-firms
  if (Beta_2-C-Firms > 0) = false  [ set Beta_2-C-Firms    0 ]                                    ; assure value into a meaninful range, because the first period there is not enough information
  if  Beta_2-C-Firms > 25          [ set Beta_2-C-Firms   25 ]                                    ; assure value into a meaninful range, because the first period there is not enough information

  set A matrix:get-row Matrix-K-Firms-Bankruptcy 0                                                ; create an object with the first row of the matrix, which contains 0s and 1s, if barkrupt or not
  set B matrix:get-row Matrix-K-Firms-Bankruptcy 1                                                ; create an object with the seccond row of the matrix, which contains the Leverage for every K-Firm

  r:put   "a" A                                                                                   ; call the R and put there the object A
  r:put   "b" B                                                                                   ; call the R and put there the object B
  r:eval  "c <- glm(a ~ b, family = binomial)"                                                    ; call R and ask to solve the logistic function with the inputs A and B, gls stands for "generalized linear model", and binomial implies logit link between "a" and "b"

  set C  r:get "c$coefficients"                                                                   ; the same as for the C-Firms, look above for details
  set Beta_1-K-Firms  first C
  if  Beta_1-K-Firms < (- 25)     [ set Beta_1-K-Firms  (- 25) ]
  set Beta_2-K-Firms  last  C
  if (Beta_2-K-Firms > 0) = false [ set Beta_2-K-Firms       0 ]
  if  Beta_2-K-firms > 25         [ set Beta_2-K-Firms      25 ]
end 


; SUBFUNCTIONS FOR UPDATING THE SYSTEM STATE

to SubF-Update-Installment                                                           ; this subfunction update the installment debt with retail banks (we are asking Firms)
  set  Interest-Pay                     0                                            ; reset parameter
  set  Installment-Pay                  0                                            ; reset parameter, the repayment schedule
  if Current-Retail-Loans > 0 [                                                      ; check if exist loan
     ifelse Bank-Account-Firm >= ((annuity-rate + eta0) * Current-Retail-Loans) [    ; check if there is money enough to pay the debts
           set Interest-Pay             eta0 * Current-Retail-Loans                  ; update the parameter with the value will be payed
           set Bank-Account-Firm        Bank-Account-Firm  - interest-pay            ; update parameter
           set Installment-Pay          annuity-rate * Current-Retail-Loans          ; update parameter
           set Bank-Account-Firm        Bank-Account-Firm  - Installment-Pay         ; update parameter
           set Current-Retail-Loans     Current-Retail-Loans - Installment-Pay       ; update parameter
           set Cases-of-Bankruptcy      0                                            ; as the firm pay debts this period, reset the parameter for bankruptcy
           ] [
           set Cases-of-Bankruptcy      Cases-of-Bankruptcy  +  1                    ; if the firm did not had money she will be closer and closer to bankruptcy
           ]                                                                         ; bankruptcy happens when the firm is unable to pay its debt to the bank
  ]
end 

to SubF-Update-Cash-Need                                                             ; subfuntion used for updating the need for cash (loans) before production takes place (need for liquidity)... (we are asking Firms)
  ifelse C-Firm? [
         set Need-Cash         max list 0 (Need-Cash + Number-of-Employees * Wage + Desired-Investment * Capital-Price-Level + (annuity-rate + eta0) * Current-Retail-Loans - Bank-Account-Firm)
  ] [
         set Need-Cash         max list 0 (Need-Cash + Number-of-Employees * Wage + (annuity-rate + eta0) * Current-Retail-Loans - Bank-Account-Firm)
  ]
end 

to SubF-Update-Assets                                                                 ; subfunction to update the assets, which differ from C-Firm to K-Firm type (we are asking Firms)
       ifelse C-Firm? [
              set Assets            max list 0 (Stock * Price  +  Bank-Account-Firm  + Capital * Capital-Price-Level)
              set Liabilities       max list 0 (Current-Retail-Loans)
              set Equity-C-Firms    Assets - Liabilities
       ] [
              set Assets            max list 0 (Stock * Price  +  Bank-Account-Firm)
              set Liabilities       max list 0 (Current-Retail-Loans)
              set Equity-K-Firms    Assets - Liabilities
       ]
end 

to SubF-Update-Leverage                                                               ; updating the leverage of a firm (we are asking Firms)
   if Need-Cash > 0                  [ set Leverage   (Current-Retail-Loans + Need-Cash) / (Assets + Current-Retail-Loans + Need-Cash) ]
   if (Current-Retail-Loans = 0)     [ set Leverage 0 ]
end 



; CREDIT PROCESS

to SubF-Ask-for-C-Credit                                                                                                           ; this subfunction is called when there is need for a loan, we ask C-Firms

   ; how much money the nearest bank may offer as a loan, see eq. 8.11 in Assenza, Gatti, Grazzini et al. 2015
   let Available-Credit-Assenza1  (Bank-loss-parameter * ([Bank-Equity] of My-Nearest-Bank - Probability-of-Bankruptcy * [Clients-Loans-with-the-Bank] of My-Nearest-Bank)) / Probability-of-Bankruptcy
   ; how much money the nearest bank may offer as a loan, see eq. 27 of Elder Silva's document
   let Available-Credit-Assenza2   Bank-loss-parameter * ([Bank-Equity] of My-Nearest-Bank * B-Lev * Risk - [Clients-Loans-with-the-Bank] of My-Nearest-Bank)
   set Available-Credit-Assenza    min (list Available-Credit-Assenza1 Available-Credit-Assenza2)
   let Available-Credit            Available-Credit-Assenza

   if (Need-Cash > 0) and ([Available-Credit-Basel] of My-Nearest-Bank > 0) and (Available-Credit >= Need-Cash) and (Cases-of-Bankruptcy < T-Ban) [                                      ; check if the need of a firm is lower then the available credit
      set Current-Retail-Loans           Current-Retail-Loans  +  Need-Cash                                                        ; updating the loans parameter
      set Bank-Account-Firm              Bank-Account-Firm +  Need-Cash                                                            ; updating the bank account with the money received
      ask My-Nearest-Bank [
          set Available-Credit-Basel     Available-Credit-Basel - Need-Cash
      ]
      set Need-Cash                      0
   ]
   if (Need-Cash > 0) and ([Available-Credit-Basel] of My-Nearest-Bank > 0) and (Available-Credit < Need-Cash) and (Cases-of-Bankruptcy < T-Ban) [                                       ; check if the need of a firm is lower then the available credit
      set Current-Retail-Loans           Current-Retail-Loans + Available-Credit                                                   ; the nearest bank offer a loan up to the limit
      set Bank-Account-Firm              Bank-Account-Firm +  Available-Credit                                                     ; updating the bank account with the money received
      ask My-Nearest-Bank [
          set Available-Credit-Basel     Available-Credit-Basel - Available-Credit
      ]
      set Need-Cash                      Need-Cash - Available-Credit
   ]
   ifelse Update-Interest?             [ SubF-Update-Interest-Retail-C ] [ set eta0  taylor-interest-rate ]                        ; call a subfunction to update the interest rate of this firm
end 

to SubF-Update-Interest-Retail-C                                                                                                   ; update the interest rate of a C-firm
   set Probability-of-Bankruptcy      (1 / (1 + e ^ ( - Beta_1-C-Firms - (Beta_2-C-Firms * leverage))))                            ; save the probability of dying of this C-Firm, and for the Betas see above
   set T-expected                     (1 / Probability-of-Bankruptcy)                                                              ; calculate the life expectation of this firm (eq 24)
   let Numerator                      (1 + (taylor-interest-rate / annuity-rate))                                                  ; local auxiliar variable, first part to calculate the new interest rate
   let Denominator                    ((1 - (1 - annuity-rate) ^ (T-expected + 1)) / annuity-rate)                                 ; // // second part of the new interest rate
   let new-int                        Bank-gross-mark-up * ((numerator / denominator) - annuity-rate)                              ; calculating the new interest rate (eq 26 or 8.8 in Assenza, Gatti, Grazzini et al. 2015)
   set eta0                          (eta0  * (Current-Retail-Loans - Need-Cash) + new-int * Need-Cash) / Current-Retail-Loans     ; update the interest rate as mean of the new and the later interest rate
end 

to SubF-Ask-for-K-Credit                                                                                                                                 ; this subfunction is called when there is need for a loan, C-Firm type

  ; how much money the nearest bank may offer as a loan, see eq. 8.11 in Assenza, Gatti, Grazzini et al. 2015
   let Available-Credit-Assenza1  (Bank-loss-parameter * ([Bank-Equity] of My-Nearest-Bank - Probability-of-Bankruptcy * [Clients-Loans-with-the-Bank] of My-Nearest-Bank)) / Probability-of-Bankruptcy
   ; how much money the nearest bank may offer as a loan, see eq. 27 of Elder Silva's document
   let Available-Credit-Assenza2   Bank-loss-parameter * ([Bank-Equity] of My-Nearest-Bank * B-Lev * Risk - [Clients-Loans-with-the-Bank] of My-Nearest-Bank)
   set Available-Credit-Assenza    min (list Available-Credit-Assenza1 Available-Credit-Assenza2)
   let Available-Credit            Available-Credit-Assenza

   if (Need-Cash > 0) and ([Available-Credit-Basel] of My-Nearest-Bank > 0) and (Available-Credit >= Need-Cash) and (Cases-of-Bankruptcy < T-Ban) [      ; check if the need of a firm is lower then the available credit
      set Current-Retail-Loans           Current-Retail-Loans  +  Need-Cash                                                                              ; updating the loans parameter
      set Bank-Account-Firm              Bank-Account-Firm +  Need-Cash                                                                                  ; updating the bank account with the money received
      ask My-Nearest-Bank [
          set Available-Credit-Basel     Available-Credit-Basel - Need-Cash
      ]
      set Need-Cash                      0
   ]
   if (Need-Cash > 0) and ([Available-Credit-Basel] of My-Nearest-Bank > 0) and (Available-Credit < Need-Cash) and (Cases-of-Bankruptcy < T-Ban) [       ; check if the need of a firm is lower then the available credit
      set Current-Retail-Loans           Current-Retail-Loans + Available-Credit                                                                         ; the nearest bank offer a loan up to the limit
      set Bank-Account-Firm              Bank-Account-Firm + Available-Credit                                                                            ; updating the bank account with the money received
      ask My-Nearest-Bank [
          set Available-Credit-Basel     Available-Credit-Basel - Available-Credit
      ]
      set Need-Cash                      Need-Cash - Available-Credit
   ]
   ifelse Update-Interest?             [ SubF-Update-Interest-Retail-K ] [ set eta0  taylor-interest-rate ]                         ; call a subfunction to update the interest rate of this firm
end 

to SubF-Update-Interest-Retail-K                                                                                                    ; update the interest rate of a K-firm
   set Probability-of-Bankruptcy      (1 / (1 + e ^ ( - Beta_1-K-Firms - (Beta_2-K-Firms * leverage))))                             ; save the probability of dying of this K-Firm, and for the Betas see above
   set T-expected                     (1 / Probability-of-Bankruptcy)                                                               ; calculate the life expectation of this firm (eq 24)
   let Numerator                      (1 + (taylor-interest-rate / annuity-rate))
   let Denominator                   ((1 - (1 - annuity-rate) ^ (T-expected + 1)) / annuity-rate)
   let new-int                         Bank-gross-mark-up * ((numerator / denominator) - annuity-rate)                              ; calculating the new interest rate (eq 26 or 8.9 in Assenza, Gatti, Grazzini et al. 2015)
   set eta0                           (eta0 * (Current-Retail-Loans - Need-Cash) + new-int * Need-Cash) / Current-Retail-Loans
end 

to SubF-Go-Bankruptcy-C-Firms                                                                           ; this subfunction rules the process for the C-firm bankruptcy
  set C-Broke                                      C-Broke + 1                                          ; increase the global parameter which count the broke status
  set Cases-of-Bankruptcy                          0                                                    ; reset the parameter
  ask out-owner-neighbors [                                                                             ; find out who is the owner of this firm
          ifelse Bank-Account-Household >= Initial-liquidity-of-Firms [                                 ; if the owner has enough money for paying the initial capital of the new firm
                 set Bank-Account-Household        Bank-Account-Household - Initial-liquidity-of-Firms  ; update the bank account of the capitalist, reduce the money used to rebuild the firm
                 ask in-owner-neighbors [                                                               ; the owner asks the firm to reset the following variables
                     set Current-Retail-Loans      0                                                    ; reset the parameter
                     if Capital-Destruction?     [ set Capital       Initial-Capital ]                  ; reset the capital of the C-Firm, the input applied to the production of C goods
                     set Bank-Account-Firm         Initial-liquidity-of-Firms                           ; updated the bank account with the money from the capitalist
                 ]
          ] [                                                                                           ; if the owner does not have enough money for paying the initial capital of the firm with problems...
                 set Bank-Account-Household        0                                                    ; ...the owner pay the debts with all his/her current assets
                 set Worker?                       true                                                 ; the capitalist is broken, and he/she becomes a poor worker
                 set Number-of-Workers             Number-of-Workers + 1
                 set color                         yellow                                               ; just for fun, not necessary for the model, used only for display in HUD netlogo
                 set Human-Wealth                  1                                                    ; initial value for Human Wealth, utilized to calculate the consumption process
                 set Current-Income                0                                                    ; intitial income
                 set Bank-Account-Household        Initial-households-personal-assets                   ; initial value of deposits at the banks, a vital minimum
                 set Desired-Consumption           0                                                    ; initial value for desire consume
                 set Consumption                   0                                                    ; initial value for Consumption
                 set C-Firm-List                  [ ]                                                   ; setup for the list which will be used to colect the C-Firms visited
                 set Employed?                     false                                                ; this worker is unemployed for the moment
                 ask in-owner-neighbors [                                                               ; the owner asks the firm to reset the following variables
                     set Current-Retail-Loans      0                                                    ; reset the parameter... in fact this is unnecesary because the firm will die soon...
                     die                                                                                ; ... I warned you about it... the C-Firm dies, and all its links
                     set Number-of-C-Firms         Number-of-C-Firms - 1
                 ]
         ]
  ]                                                                                                     ; end asking the owner
end 

to SubF-Go-Bankruptcy-K-Firms                                                                           ; this subfunction rules the process for the K-firm bankruptcy
  set K-Broke                                     K-Broke + 1                                           ; increase the global parameter which count the broke status
  set Cases-of-Bankruptcy                         0                                                     ; reset the parameter
  ask out-owner-neighbors [                                                                             ; find out who is the owner of this firm... there is only one
          ifelse Bank-Account-Household >= Initial-liquidity-of-Firms [                                 ; if the owner has enough money for paying the initial capital of the new firm
                 set Bank-Account-Household       Bank-Account-Household - Initial-liquidity-of-Firms   ; update the bank account of the capitalist, reduce the money used to rebuild the firm
                 ask in-owner-neighbors [                                                               ; the owner asks the firm to reset these variables
                     set Current-Retail-Loans     0                                                     ; reset the parameter
                     set Bank-Account-Firm        Initial-liquidity-of-Firms                            ; updated the bank account with the money from the capitalist
                 ]
          ] [                                                                                           ; if the owner does not have enough money for paying the initial capital of the firm with problems...
                 set Bank-Account-Household       0                                                     ; ...the owner pay the debts with all his/her current assets
                 set Worker?                      true                                                  ; the capitalist is broken, and he/she becomes a poor worker
                 set Number-of-Workers            Number-of-Workers + 1
                 set color                        yellow                                                ; just for fun, not necessary for the model, used only for display in HUD netlogo
                 set Human-Wealth                 1                                                     ; initial value for Human Wealth, utilized to calculate the consumption process
                 set Current-Income               0                                                     ; intitial income
                 set Bank-Account-Household       Initial-households-personal-assets                    ; initial value of deposits at the banks, a vital minimum
                 set Desired-Consumption          0                                                     ; initial value for desire Consumption
                 set Consumption                  0                                                     ; initial value for Consumption
                 set C-Firm-List                 [ ]                                                    ; setup for the list which will be used to colect the C-Firms visited
                 set Employed?                    false                                                 ; this worker is unemployed for the moment
                 ask in-owner-neighbors [                                                               ; the owner asks the firm to reset these variables
                     set Current-Retail-Loans     0                                                     ; reset the parameter... in fact this is unnecesary because the K-Firm will die soon...
                     die                                                                                ; ... I warned you about it... the K-Firm dies, and all its links
                     set Current-Number-of-K-Firms        Current-Number-of-K-Firms - 1
                 ]
         ]
  ]                                                                                                     ; end asking the owner
end 

to SubF-Ask-for-Credit-to-Central-Bank                                                                  ; this subfunction is called when the retail bank needs for a loan due to liquidity problems
   if Own-Reserves / Clients-Accounts-at-the-Bank_1 < RR [
      let Needed-Liquidity                        Clients-Accounts-at-the-Bank_1 * RR - Own-Reserves
      set Central-Bank-Loans                      Central-Bank-Loans + Needed-Liquidity
   ]
end 




; FUNCTION-CENTRAL-BANK: SETTING INTEREST RATE AND CONDITIONS FOR THE LOANS TO THE RETAIL BANKS

to Function-Central-Bank
   SubF-Set-Interest-Rates                           ; different interest rates are calculated by the central bank
   SubF-Set-Macroprudential-Rules                    ; a set of macroprudential rules included in the Basel III catalogue
end 

to SubF-Set-Interest-Rates
   set Total-Loans_1             Total-Loans
   set Total-Loans               Total-Loans-Firms + Total-Central-Bank-Loans
   set inflation_1               inflation                                                                                                                                                              ; store the inflation value for use with adaptative functions
   set inflation                 ((ln Goods-Price-Level - ln Goods-Price-Level_1) + (ln Capital-Price-Level - ln Capital-Price-Level_1))                                                                ; this approximation with logarithms is good only if the rate is close to zero
   set P_GDP                     Productivity-of-labor * Number-of-Workers                                                                                                                              ; P_GDP is potential GDP, and this is the maximum production, by using all resources (Unemployment = 0)
   let sensity_inflation         Taylor-rule-parameter-for-inflation * (inflation - desired-inflation)                                                                                                  ; Taylor-rule-parameter-for-inflation & Desire-inflation-for-the-monetary-authority
   let sensity_product           Taylor-rule-parameter-for-product   * (ln GDP - ln P_GDP)                                                                                                              ; Taylor-rule-parameter-for-product
   let sensity_credit            Taylor-rule-parameter-for-credit    * (ln Total-Loans - ln Total-Loans_1)                                                                                              ; the parameter for the credit component of the Taylor rule
   if taylor-rule = "conservative" [
   set taylor-interest-rate    max list 0.01 ( (inflation + natural-interest-rate + sensity_inflation) * (Slow_taylor) + (1 - slow_taylor) * taylor-interest-rate )                                     ; conservative Taylor rule: inflation (eq 18 of Popoyan et al)
   ]
   if taylor-rule = "dual-mandate" [
   set taylor-interest-rate    max list 0.01 ( (inflation + natural-interest-rate + sensity_inflation + sensity_product) * (Slow_taylor) + (1 - slow_taylor) * taylor-interest-rate )                   ; dual mandate Taylor rule: inflation and output gap (eq 30 of Silva or eq 19 of Popoyan et al)
   ]
   if taylor-rule = "three-mandate" [
   set taylor-interest-rate    max list 0.01 ( (inflation + natural-interest-rate + sensity_inflation + sensity_product + sensity_credit) * (Slow_taylor) + (1 - slow_taylor) * taylor-interest-rate )  ; three-mandate Taylor rule: inflation, output gap and credit (eq 20 of Popoyan et al)
   ]
end 

to SubF-Set-Macroprudential-Rules                                                                     ; we follow here Popoyan et al (2017), pp. 120-121 and 125-127

   ; First, we prepare the global variables needed below

   set Credit-on-GDP_1                             Credit-on-GDP                                      ; we store the value of the previous period
   set Credit-on-GDP                               Total-Loans-Firms / GDP                            ; this is the basic ratio used in the Counter-Cyclical-Capital-Buffer defined in Basel III rules
   let Credit-on-GDP_bis                           Total-Client-Loans / GDP                           ; this is a different way for the same result, and we should see Credit-on-GDP = Credit-on-GDP_bis
   set Matrix-Basel-Buffer matrix:set-and-report Matrix-Basel-Buffer 0 Mjb Credit-on-GDP              ; update the first row of the matrix with information about the explained variable: every (0, Mjb) element is replaced by Credit-on-GDP of the current period
   set Matrix-Basel-Buffer matrix:set-and-report Matrix-Basel-Buffer 1 Mjb ticks                      ; update the second row of the matrix with information about the explicative variable: every (1, Mjb) element is replaced by Credit-on-GDP of the previous period
   set Mjb Mjb + 1 if Mjb > (Time-Window2 - 1) [ set Mjb 0 ]                                          ; move the matrix element to the next position, so the replacements in the matrix are sequential, and the time-window controls how many observations we'll have

   let A matrix:get-row Matrix-Basel-Buffer 0                                                         ; create an object with the first row (0) of the matrix, which contains current Credit-on-GDP
   let B matrix:get-row Matrix-Basel-Buffer 1                                                         ; create an object with the second row (1) of the matrix, which contains Credit-on-GDP of the previous period

   r:put   "a" A                                                                                      ; call R and put there the object A
   r:put   "b" B                                                                                      ; call R and put there the object B
   r:eval  "c <- lm(a ~ b)"                                                                           ; call R and ask to solve the OLS regression with the inputs A and B, lm stands for "linear model". The OLS regression is Credit-on-GDP = a + b * ticks + e

   let C    r:get "c$fitted.values"                                                                   ; call R and put the fitted values into an object C, which is a list
   let long-Run-Credit-on-GDP  last C                                                                 ; save the last fitted value as a new variable used in the calculation of the gap
   set Credit-on-GDP-Gap                           Credit-on-GDP - long-Run-Credit-on-GDP             ; we create the gap variable here... and then we proceeed to the calculation of the capital buffer


   ; Now we start with the definition of the macroprudential rules and their implications for the available credit of banks

   ask Banks [                                                                                                                ; this is important because the rules are applied to a macro scale but also to a micro scale, for every bank
       if Macroprudential-Rules = "basel2" [                                                                                  ; we have created a chooser called "macroprudential-rules" with several possibilities: basel2, basel31, basel32, basel312
          set Available-Credit-Basel2              max (list 0 (Own-Bank-Capital * 12.5 - Clients-Loans-with-the-Bank))       ; available-credit = Own-Bank-Capital * 12.5 - Total-Loans-Firms, the maximum limit minus the current level of loans
          let Minimum-Capital-Requirement-Basel2   Own-Bank-Capital / (Clients-Loans-with-the-Bank + available-credit-basel2) ; Basel II sets this ratio as 8% as a minimum
          set Available-Credit-Basel               Available-Credit-Basel2                                                    ; Available-Credit-Assenza are the particular constraints of the bank to new loans, and it is combined with Available-Credit-Basel determined by monetary authorities
       ]

       if Macroprudential-Rules = "basel3_1" [
          let Available-Credit-Basel31a            max (list 0 (Own-Bank-Capital * 22.2 - Clients-Loans-with-the-Bank))          ; available-credit = Own-Bank-Capital * 22.2 - Total-Loans-Firms, the maximum limit minus the current level of loans
          let Minimum-Capital-Requirement-Basel3   Own-Bank-Capital / (Clients-Loans-with-the-Bank + Available-Credit-Basel31a)  ; Basel II sets this ratio as 4,5% as a minimum

          let Available-Credit-Basel31b            0
          set Capital-Buffer                       0
          let Buffer-Add-On                        0

          if Credit-on-GDP-Gap < 2 [
             set Capital-Buffer                    0                                                                                   ; there is no buffer here, and therefore there are no specific constraits on new available-credits. The capital Buffer is a percentage on Total-Loans-Firms.
             set Buffer-Add-On                     0                                                                                   ; the Capital Buffer is a % of the Total-Loans-Firms not available for firms, this is, for each $ loaned this % must be reserved as a buffer...
          ]                                                                                                                            ; end of first case
          if Credit-on-GDP-Gap <= 10 and Credit-on-GDP-Gap >= 2 [
             set Capital-Buffer                    max (list 0 ((Credit-on-GDP-Gap - 2) * 0.003125))                                   ; 0.003125 = 0.025 / 8 and from here we have a range of values for the Capital-Buffer... (Total-Loans-Firms + Available-Credit-Basel32)
             set Available-Credit-Basel31b        (Clients-Accounts-at-the-Bank + Own-Bank-Capital + Central-Bank-Loans - Own-Reserves - Clients-Loans-with-the-Bank - Clients-Loans-with-the-Bank * Capital-Buffer) / (1 + Capital-Buffer)          ; Deposits-Total includes Own-Bank-Capital
             set Buffer-Add-On                     Capital-Buffer * (Clients-Loans-with-the-Bank + Available-Credit-Basel31b)          ; the aggregate constraint is (Deposits-Total + Central-Bank-Loans + Own-Capital-Bank - Reserves - Total-Loans-Firms - Buffer-Add-On) = Available-Credit-Basel31b
          ]                                                                                                                            ; and aggregate Buffer-Add-On = Capital-Buffer * (Total-Loans-Firms + Available-Credit-Basel31)...
          if Credit-on-GDP-Gap > 10 [
             set Capital-Buffer                    0.025
             set Available-Credit-Basel31b         max (list 0 ((Clients-Accounts-at-the-Bank + Own-Bank-Capital + Central-Bank-Loans - Own-Reserves - Clients-Loans-with-the-Bank - Clients-Loans-with-the-Bank * Capital-Buffer) / (1 + Capital-Buffer)))     ; Deposits-Total includes Own-Bank-Capital
             set Buffer-Add-On                     Capital-Buffer * (Clients-Loans-with-the-Bank + Available-Credit-Basel31b)          ; the aggregate constraint is (Deposits-Total + Total-Central-Bank-Loans + sum (Own-Capital-Bank) - Reserves - Total-Loans-Firms - Buffer-Add-On) = Available-Credit-Basel31b
          ]                                                                                                                            ; end of third case


          let Leverage-Requirement-Basel3          Own-Bank-Capital / Assets                                                           ; this is the third ratio of the first macroprudential rule of Basel III, and the ratio has to be equal to or higher than 3%
          let Available-Credit-Basel31c            max (list 0 ((Own-Bank-Capital - 0.03 * Assets) / 0.03))                            ; 0.03 = Own-Bank-Capital / (Assets of Banks + Available-Credit-Basel31c) and therefore...

          set Available-Credit-Basel31             min (list Available-Credit-Basel31a Available-Credit-Basel31b Available-Credit-Basel31c)
          set Available-Credit-Basel               Available-Credit-Basel31
       ]

       if Macroprudential-Rules = "basel3_2" [
           let High-Quality-Liquid-Assets         (Own-Reserves + Own-Bank-Capital) * 1.75
           set Available-Credit-Basel32           (High-Quality-Liquid-Assets - (taylor-interest-rate + annuity-rate) * Central-Bank-Loans - 0.1 * Clients-Accounts-at-the-Bank - 0.25 * Central-Bank-Loans + I-Received + D-Received - 0.5 * Clients-Loans-with-the-Bank) * 2
           let Expected-Net-Cash-Outflows         (taylor-interest-rate + annuity-rate) * Central-Bank-Loans + 0.1 * Clients-Accounts-at-the-Bank + 0.25 * Central-Bank-Loans - I-Received - D-Received + 0.5 * (Clients-Loans-with-the-Bank + Available-Credit-Basel32)
           let Liquidity-Coverage-Ratio            High-Quality-Liquid-Assets / Expected-Net-Cash-Outflows                             ; Liquidity-Coverage-Ratio >= 1
           set Available-Credit-Basel              Available-Credit-Basel32
       ]

       if Macroprudential-Rules = "basel3_12" [
           set Available-Credit-Basel              min (list Available-Credit-Basel31 Available-Credit-Basel32)
       ]
   ]
end 







; FUNCTION-CALL-STATE

to Function-State-Manage-Budget                                                                                         ; the State get taxes, sells PublicDebt to the Central Bank if there is a deficit and buys PublicDebt to the Central Bank if there is a superavit and pays unemployment benefits
   set State-Budget                               State-Budget - PublicDebt * (taylor-interest-rate * annuity-rate)     ; the unemploymet benefits was substracted from the State Budget when the State paid for it
   let State-Budget-Balance                       State-Budget                                                          ; we record the budget balance
   let State-Budget-Balance_1                     State-Budget-Balance                                                  ; we store the surplus or deficit of this period
   if State-Budget-Balance < 0 and Do_We_Have_Central-Bank? = true and QEasing? = true [                                ; if the Central Bank exists and it buys public debt without limits, all the deficit is converted to government bonds sold to the CB
      set PublicDebt                              PublicDebt + abs State-Budget                                         ; new debt is added to the existing
      set State-Budget                            0                                                                     ; when the deficit is covered, the State budget is in equilibrium
   ]                                                                                                                    ; if the Quantitative Easing is not activated the State Budget cannot be negative (we might consider a constraint of 3% of deficit instead of 0%)
   if State-Budget-Balance > 0 and PublicDebt > 0 and PublicDebt >= State-Budget-Balance and Do_We_Have_Central-Bank? = true [                         ; if the Central Bank exists and there is a surplus...
      set PublicDebt                              PublicDebt - State-Budget                                             ; new debt is added to the existing
      set State-Budget                            0                                                                     ; when the deficit is covered, the State budget is in equilibrium
   ]                                                                                                                    ; end of this case
   if State-Budget-Balance > 0 and PublicDebt >= 0 and PublicDebt < State-Budget-Balance and Do_We_Have_Central-Bank? = true [                         ; if the Central Bank exists and there is a surplus...
      set State-Budget                            State-Budget-Balance - PublicDebt                                     ; new debt is added to the existing
      set PublicDebt                              0                                                                     ; the public debt is cancelled
      set Account-of-State-at-Central-Bank        Account-of-State-at-Central-Bank + State-Budget                       ; the surplus goes to the account of the State at the Central Bank, and this reduces the amount of money in the system
      set State-Budget                            0                                                                     ; when the surplus is applied, the State budget is in equilibrium
   ]                                                                                                                    ; end of this case
end 

to Function-Update-System
   SubF-Update-Wages
   SubF-Update-Monetary-Variables
   SubF-Entry-New-Firms
end 




 To SubF-Update-Wages                                                                           ; this subfunction adjusts wages depending on unempleyment rate, and this wage is applied to the next period
   set cpi_1           cpi                                                                      ; store the cpi value for use with adaptative functions... it is a global variable
   set cpi             ln Goods-Price-Level - ln Goods-Price-Level_1                            ; cpi is the consumer prince index, user for indexing salaries
   set Wage-on-GDP_1   Wage-on-GDP                                                              ; store the Wage-on-GDP value for use with adaptative functions
   set Wage-on-GDP    (sum [Number-of-Employees] of Firms * Wage) / GDP                             ; total salaries as a percentage of the GDP, then Wage = (Wage-on-GDP * GDP) / Number-of-Employees is the wage that keeps that proportion constant
   set Wage_1          Wage                                                                     ; store the Wage value for use with adaptative functions
   ifelse Unemployment-Rate <= frictional-unemployment-rate + 3 [                               ; if the unemployment rate approaches the frictional unemployment rate (of about 5%), then trade unions get stronger and wages rise
          set Wage  min list ((1 + cpi_1) * Wage) ((Wage-on-GDP_1 * GDP) / sum [Number-of-Employees] of Firms) ; two options: the previous wage increased by the consumer price index or the wage which keeps Wage-on-GDP constant
   ] [                                                                                          ; the second option for wage comes from finding the value of wage in (Wage-on-GDP_1 = Wage-on-GDP)
          set Wage  minimum-wage                                                                ; if the unemployment rate is higher than the frictional unemployment rate plus a margin, the wages cannot be lower than a legal minimum
   ]                                                                                            ; trade unions try to keep purchasing power of salaries or weight of salaries on GDP constant, but they loss power if unemployment increases
end 

to SubF-Update-Monetary-Variables
   set Monetary-Base                             Total-Central-Bank-Loans + PublicDebt - Account-of-State-at-Central-Bank - Central-Bank-Own-Capital    ; monetary base is "outside money", and that difference is "coins and bills" money
   set Currency                                  Monetary-Base - Total-Reserves                                                                         ; Currency is Currency, and this plus Total-Reserves is the Monetary-Base
   set Money-Supply                              Monetary-Base / RR                                                                                     ; Monetary-Base multiplied by the money multiplier (1/RR) is the Money-Supply
end 

to SubF-Entry-New-Firms                                                                                         ; if bakruptcy of firms occurs, a procedure for regenerating firms is activated
   let C-Firms-newcomers%                        0                                                              ; local variable, a probability following a Beta distribution
   ifelse GDP > GDP_1 [ set C-Firms-newcomers%  stats:beta 6 3 ] [ set C-Firms-newcomers%  stats:beta 3 6 ]     ; the probability of new firms depends on the GDP growth, and the Beta distribution is asymmetrical
   if Number-of-C-Firms > Current-Number-of-C-Firms [                                                           ; if the number of C-Firms is lower than the maximun, there is room for newcomers
      if random-float 1 < C-Firms-newcomers% [                                                                  ; with a probability that depends on the GDP growth, new C-Firms appear in the economy
         create-firms 1 [
                 move-to one-of patches with [not any? Firms-here]                                              ; if a C-Firm and K-Firm are at the same patch, move the new firm in the setup process
                 set shape                      "factory"                                                        ; just for fun, not necessary for the model, used only for display in HUD netlogo
                 set size                        2                                                               ; just for fun, not necessary for the model, used only for display in HUD netlogo
                 set color                       orange                                                          ; just for fun, not necessary for the model, used only for display in HUD netlogo
                 set C-Firm?                     true                                                            ; proper of the Firms, true means it is a consumption producer firm
                 set Owner?                      false                                                           ; this firm will have an owner, but at this moment does not have it
                 set Price                       random-float 2                                                  ; initial value for price
                 set Capital                     Initial-capital                                                 ; initial value for capital
                 set Stock                       Initial-production-C-firms                                      ; initial value for stock
                 set Production                  Initial-production-C-firms                                      ; initial value for production
                 set Revenue                     0                                                               ; initial value for revenue
                 set Sales                       0                                                               ; initial value for sales
                 set Need-Cash                   0                                                               ; initial value for cash needed before production, because lack of liquidity for starting it
                 set Cases-of-Bankruptcy         0                                                               ; the total number of bankruptcies by this firm
                 set Desired-Investment          0                                                               ; initial value for desire investment
                 set Investment                  0                                                               ; initial value for investment
                 set Number-of-Employees         0                                                               ; initial value for number of employees
                 set Need-of-Employees           0                                                               ; initial value for desire employees
                 set K-Firm-List                [ ]                                                              ; setup for the list which will be used to colect the K-Firms visited
                 set Vacancy                     0                                                               ; initial value for vacancy
                 set Bank-Account-Firm           Initial-liquidity-of-Firms                                      ; initial money deposited at the bank by the firms
                 set Investment-Memory           Initial-Capital                                                 ; initial value for Investment-Memory, parameter utilized to calculate the desire investment
                 set Util-Capacity               0                                                               ; initial value for util-capacity
                 create-banker-from              min-one-of banks [distance myself] [set hidden? true]           ; this create a link between the bank and the capitalist
                 set My-Nearest-Bank             min-one-of banks [distance myself]                              ; this bank is the same to which the C-Firms is now linked with a "banker" relationship
         ]                                                                                                      ; end new firm commands
      ]                                                                                                         ; end if random 100
   ]                                                                                                            ; end condition about room for new firms

   let Newcapitalist-C                           n-of 1 Workers with-max [ Bank-Account-Household ]              ; the new firm needs a new capitalist-owner
   ask Newcapitalist-C [                                                                                        ; we ask the worker with the highest savings to buy the Firm and become a capitalist
       ask one-of my-in-hireds [                                                                                ; the new capitalist is a worker yet and we take its labor contract and...
           ask other-end [                                                                                      ; ... at the other end of that contract is a firm
                set Vacancy                      Vacancy               + 1                                       ; the worker leaves, so the firm adjust the vacancies
                set Number-of-Employees          Number-of-Employees   - 1                                       ; the firm losses one worker
           ]
       die                                                                                                       ; the link, the labor relationship, dies
       ]
       set shape                                "person"                                                         ; this is unnecessary, because the worker also has a person shape
       set size                                  1.25                                                            ; the same goes for the size
       set color                                 white                                                           ; the color changes, because workers are yellow and capitalists are white
       set Worker?                               false                                                           ; he/she is now a capitalist
       set Current-Number-of-Workers             Current-Number-of-Workers - 1
       create-owner-from                         one-of Firms with [Owner? = false] [set hidden? true]           ; this creates a link between the firm and the capitalist
   ]


                                                     ; local variable with the total number of K-Firms alive in this period
   let K-Firms-newcomers%                        0                                                              ; local variable, a probability following a Beta distribution
   ifelse GDP > GDP_1 [ set K-Firms-newcomers%  stats:beta 6 3 ] [ set K-Firms-newcomers%  stats:beta 3 6 ]     ; the probability of new firms appearing depends on the GDP growth, and the Beta distribution is asymmetrical
       if Number-of-K-Firms > Current-Number-of-K-Firms [                                                       ; if the number of K-Firms is lower than the maximun, there is room for newcomers
          if random-float 1 < K-Firms-newcomers% [                                                              ; with a probability that depends on the GDP growth, new K-Firms appear in the economy
             create-firms 1 [
                  move-to one-of patches with [not any? Firms-here]                                             ; if a C-Firm and K-Firm are at the same patch, move the K-Firm in the setup process
                  set shape                     "factory"                                                       ; just for fun, not necessary for the model, used only for display in HUD netlogo
                  set size                       2                                                              ; just for fun, not necessary for the model, used only for display in HUD netlogo
                  set color                      green                                                          ; just for fun, not necessary for the model, used only for display in HUD netlogo
                  set C-Firm?                    false                                                          ; proper of the Firms, true means it is a consumption producer firm
                  set Owner?                     false                                                          ; this firm will have an owner, but at this moment does not have it
                  set Price                      random-float 2                                                 ; initial value for price
                  set Capital                    Initial-capital                                                ; initial value for capital
                  set Stock                      Initial-production-K-firms                                     ; initial value for stock
                  set Production                 Initial-production-K-firms                                     ; initial value for production
                  set Revenue                    0                                                              ; initial value for revenue
                  set Sales                      0                                                              ; initial value for sales
                  set Need-Cash                  0                                                              ; initial value for cash needed before production, because lack of liquidity for starting it
                  set Cases-of-Bankruptcy        0                                                              ; the total number of bankruptcies by this firm
                  set Desired-Investment         0                                                              ; initial value for desire investment
                  set Investment                 0                                                              ; initial value for investment
                  set Number-of-Employees        0                                                              ; initial value for number of employees
                  set Need-of-Employees          0                                                              ; initial value for desire employees
                  set Vacancy                    0                                                              ; initial value for vacancy
                  set Bank-Account-Firm          Initial-liquidity-of-Firms                                     ; initial money deposited at the bank by the firms
                  set Investment-Memory          Initial-Capital                                                ; initial value for Investment-Memory, parameter utilized to calculate the desire investment
                  set Util-Capacity              0                                                              ; initial value for util-capacity
                  create-banker-from             min-one-of banks [distance myself] [set hidden? true]          ; this create a link between the bank and the capitalist
                  set My-Nearest-Bank            min-one-of banks [distance myself]                             ; this bank is the same to which the C-Firms is now linked with a "banker" relationship
             ]                                                                                                  ; end sprout
          ]                                                                                                     ; end if random 100
   ]                                                                                                            ; end condition about room for new firms

   let Newcapitalist-K                           n-of 1 Workers with-max [ Bank-Account-Household ]             ; the new firm needs a new capitalist-owner
   ask Newcapitalist-K [                                                                                        ; we ask the worker with the highest savings to buy the Firm and become a capitalist
          ask one-of my-in-hireds [                                                                             ; the new capitalist is a worker yet and we take its labor contract
              ask other-end [                                                                                   ; at the other end of that contract is a firm
                  set Vacancy                    Vacancy               + 1                                      ; the worker leaves, so the firm adjust the vacancies
                  set Number-of-Employees        Number-of-Employees   - 1                                      ; the firm losses one worker
              ]
          die                                                                                                   ; the link, the labor relationship, dies
          ]
          set shape                            "person"                                                         ; this is unnecessary, because the worker also has a person shape
          set size                              1.25                                                            ; the same goes for the size
          set color                             white                                                           ; the color changes, because workers are yellow and capitalists are white
          set Worker?                           false                                                           ; he/she is now a capitalist
          set Current-Number-of-Workers         Current-Number-of-Workers - 1
          create-owner-from                     one-of Firms with [Owner? = false] [set hidden? true]           ; this create a link between the firm and the capitalist
  ]
end 

There are 2 versions of this model.

Uploaded by When Description Download
Rubén Osuna about 6 years ago Changes to the code proposed by Elder Silva Download this version
Rubén Osuna over 6 years ago Initial upload Download this version

Attached files

File Type Description Last updated
Macroeconomic ABM with Banking Instability and Macroprudential Rules.png preview Preview for 'Macroeconomic ABM with Banking Instability and Macroprudential Rules' over 6 years ago, by Rubén Osuna Download

This model does not have any ancestors.

Children:

Graph of models related to 'Macroeconomic ABM with Banking Instability and Macroprudential Rules'