Version 2

No preview image

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

1 collaborator

Yo Rubén Osuna (Author)

Tags

(This model has yet to be categorized with any tags)
Visible to everyone | Changeable by everyone
Model was written in NetLogo 6.0.2 • Viewed 278 times • Downloaded 23 times • Run 0 times
Download the 'Version 2' 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

Please start the discussion about this model! (You'll first need to log in.)

Click to Run Model

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

globals [
  Taylor-Interest-Rate                                        ; interest rate as set by the central bank
  P_GDP                                                       ; potential GDP
  GDP_1
  GDP
  GDP_va
  GDP_exp                                                    ; sum of Total-Consumption and total-investment
  GDP_inc
  GDP_or
  Recession-lenght
  Recession-Periods
  Growth-lenght
  Growth-Rate
  Unemployment-Rate                                           ; sum of the households without a job
  Unemployed-People
  Total-Consumption                                           ; sum of goods sold by the consumptions firms
  Total-Investment                                            ; sum of total capital sold by the capital production firms
  Total-Inventory-investment                                  ; sum of inventory investments of all K-Firms
  Total-Inventory-investment_1
  Goods-Price-Level                                           ; sum (price * qt) / Qt sold
  Goods-Price-Level_1
  Capital-Price-Level                                         ; sum (price * qt) / Qt sold
  Capital-Price-Level_1
  General-Price-Level                                         ; General price level starting from 1
  General-Price-Level_1
  cpi_1
  kpi_1
  gpi_1
  kpi                                                         ; Capital price rate
  cpi                                                         ; Consumption price rate
  gpi                                                         ; general price rate, including capital and consumption goods
  C-Index                                                     ; Consumption price index
  K-Index                                                     ; Capital price index
  G-Index                                                     ; General price index
  C-Firms                                                     ; group of firms with property consumption production
  K-Firms                                                     ; group of firms with property capital production
  Workers                                                     ; group of households with property worker
  Capitalists                                                 ; group of households with property capitalist
  Employed                                                    ; building the group with all employed workers
  Unemployed                                                  ; building the group with all unemployed workers
  Employment_1
  Employment
  Wage
  Wage_1
  Labor-Share_1
  Labor-Share
  Monetary-Base
  Currency
  Money-Supply
  Available-Credit-Basel2
  Available-Credit-Basel31
  Available-Credit-Basel32
  Available-Credit-Basel
  Capital-Buffer
  State-Budget
  Helped-Households
  Public-Debt
  Account-of-State-at-Central-Bank
  Central-Bank-Own-Capital
  C-Broken                                                    ; number of consumption firms that went broken
  K-Broken                                                    ; number of capital production firms that went broken
  B-Broken                                                    ; number of times that banks went broken
  Bail-outs
  Bail-ins
  Promoted                                                    ; number of workers that became capitalists
  Demoted                                                     ; number of capitalists that became workers
  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
  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)
  Beta_1-Banks                                                ; parameter utilized by the banks to calculate the interest rate for the firms (eq 26)
  Beta_2-Banks                                                ; 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
  ]

breed               [Households Household]                    ; agent class
breed               [Firms      Firm     ]                    ; agent class
breed               [Banks      Bank     ]                    ; 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 to their owner/capitalist

Households-own [
  Worker?                                                     ; property of the household, yes if it is a worker, not if it is a capitalist
  Bankrupt?
  Employed?
  Human-Wealth                                                ; parameter to calibrate 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 consumed
  C-Expenses                                                  ; expenditures in consumtion goods
  Interest-Earned
  Price-List                                                  ; list with the prices of firms the household visited last period
  ]

Firms-own [
  C-Firm?                                                     ; property of the firms, yes if it is a consumption production firm, not if is a capital production firm
  Owner?
  Price                                                       ; last price practiced by the firm
  Demand                                                      ; last quantity demanded
  Production                                                  ; actual production of the firm
  Inventory-investment                                        ; stock of machines produced this period but not sold
  Stock                                                       ; amount available for sales (inventories)
  Delta                                                       ; parameter used to calculate new price
  Number-of-Employees                                         ; actual number of employees of this firm
  Desired-Employees                                           ; ideal number of employees for this firm
  Vacancy                                                     ; number of opened places at this firm for new workers
  New-Credit-Available                                        ; additional credit available for the firm at a particular moment
  Max-Credit-to-Firm                                          ; maximum amount of loans a firm may get in its balances
  Revenue                                                     ; sum of quantity sold times the price
  K-Expenses                                                  ; this only applies to C-Firms and it is the nominal expenses in capital (net investment)
  Sales                                                       ; sum of quantity sold last period
  Profit                                                      ; revenue less the expenditures
  EBIT                                                        ; Profits Before Taxes
  Dividend                                                    ; part of the profit given to the owner, from firms and banks
  Need-Cash                                                   ; money that will be asked to the bank as a new loan
  Bank-Account-Firm                                           ; money available at the bank owned by the firms
  Bank-Account-Firm_1                                         ; money available at the bank at the beginning of the period
  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
  Equity
  Current-Retail-Loan                                         ; sum of loans with the retail bank
  Interest-Retail                                             ; actual interest rate applied to this firm by the retail bank
  Cases-of-Bankruptcy                                         ; the probability to go bankruptcy by this firm, calculated by the retail 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
  Probability-of-Bankruptcy                                   ; probability of dying for each and every firm
  Capital                                                     ; property of the C-firms, indicate the capital available to be used at the production process this period... this is a real variable
  Desired-Investment                                          ; property of the C-Firms, ideal investment needed this period... this is a real variable
  Price-List                                                  ; property of the C-Firms, list of prices from the K-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
  ]

Banks-own [
  Total-Accounts-Workers                                      ; sum of deposit at bank of the households, equity is net worth, the difference between assets and debt
  Total-Accounts-Capitalists                                  ; sum of deposit at bank of the capitalists, equity is net worth, the difference between assets and debt
  Total-Accounts-C-Firms                                      ; sum of deposit at bank of the C-Firms, equity is net worth, the difference between assets and debt
  Total-Accounts-K-Firms                                      ; sum of deposit at bank of the K-Firms, equity is net worth, the difference between assets and debt
  Own-Bank-Capital                                            ; bank own equity, equity is net worth, the difference between assets and debt
  Total-Accounts_1
  Total-Accounts                                              ; sum of all equities, equity is net worth, the difference between assets and debt
  Total-Loans_1
  Total-Loans                                                 ; sum of loans
  Total-Loans-C-Firms                                         ; sum of loans with the C-Firms
  Total-Loans-K-Firms                                         ; sum of loans with the K-Firms
  Central-Bank-Loans
  Dividend
  Leverage-C-Firms                                            ; mean leverage of the C-Firms, every bank have their number
  Leverage-K-Firms                                            ; mean leverage of the K-Firms, every bank have their number
  Interests-Received                                          ; sum of interest received last period
  Interests-Paid
  Installments-Received                                       ; sum of installment received last period
  Profit                                                      ; sum of interest received less the bank losses with their loans
  EBIT                                                        ; Profits Before Taxes
  Reserves
  Assets
  Liabilities
  Bank-Equity
  ]

             ; TO SETUP

to Setup
  clear-all
  if Do_We_Have_Workers?              [ Setup-Workers    ]                ; call the setup for workers
  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_Capitalists?          [ Setup-Capitalist ]                ; call the setup for Capitalists
  if Do_We_Have_Banks?                [ Setup-Bank       ]                ; call the setup for banks
  Setup-Globals                                                           ; call the setup for globals
  reset-ticks                                                             ; netlogo need this
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                         0.50                                                 ; just for fun, not necessary for the model, used only for display in HUD netlogo
    set color                        blue                                                 ; 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
    set Bankrupt?                    false
    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       max list 0 (random-normal Initial-households-personal-assets 0.5)   ; initial value of deposits at the banks
    set Desired-Consumption          0                                                    ; initial value for desire Consumption
    set Consumption                  0                                                    ; initial value for Consumption
    set Price-List                   [ ]                                                  ; setup for the list which will be use to colect the price of the C-Firms visited
    ]
end 

to Setup-Capitalist
  ask n-of 250 patches [                                                                  ; each patches represent one firm, this command ensure will be one capitalist for each firm
    sprout-Households 1 [                                                                 ; ask to create one capitalist in each position
      set shape                     "person"                                              ; just for fun, not necessary for the model, used only for display in HUD netlogo
      set size                       0.50                                                 ; 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 Employed?                  false
      set Human-Wealth               1                                                    ; initial value for human wealth
      set Current-Income             0                                                    ; initial value for Current income
      set Bank-Account-Household     max list 0 (random-normal Initial-households-personal-assets 0.5)   ; 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 Price-List                 [ ]                                                  ; setup for the list which will be used to colect the price of the C-Firms visited
      create-Owner-from              one-of Firms-Here [set hidden? true]                 ; this create a link between the firm and the capitalist. Thus, one will know each other for all the purposes, like divide, rebuild a broken firm, etc.
      ]
    ]
end 

to Setup-C-Firms
  ask n-of 200 patches with [pycor < 8] [                                                 ; this command ask the 200 patches which are position at grid with y coordinates less than 8
    sprout-Firms 1 [                                                                      ; ask to create one firm at this patche
      set shape                      "house"                                              ; just for fun, not necessary for the model, used only for display in HUD netlogo
      set size                       0.75                                                 ; 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
      set Price                      1.0001                                               ; 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 Probability-of-Bankruptcy  0.0001
      set Revenue                    0                                                    ; initial value for revenue
      set Sales                      0                                                    ; initial value for sales
      set Need-Cash                  0                                                    ; initial value for cash need
      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 Desired-Employees          0                                                    ; initial value for desire employees
      set Price-List                 [ ]                                                  ; setup for the list which be used to colect the prices from the K-firms visited trying to buy capital
      set Vacancy                    0                                                    ; initial value for vacancy
      set Bank-Account-Firm          max list 0 (random-normal Initial-liquidity-of-Firms 1)           ; initial money deposited at the bank by the firms
      set Bank-Account-Firm_1        Bank-Account-Firm
      set Investment-Memory          Initial-Capital                                      ; initial value for Investment-Memory
      set Util-Capacity              0                                                    ; initial value for util-capacity
      ]
    ]
end 

to Setup-K-Firms
    ask n-of 50 patches with [pycor >= 8] [                                             ; this command ask 50 patches which are located at coordinates y >= 8
    sprout-Firms 1 [                                                                    ; ask to create one firm in each of those patches
      set shape                      "house"                                            ; just for fun, not necessary for the model, used only for display in HUD netlogo
      set size                       0.75                                               ; just for fun, not necessary for the model, used only for display in HUD netlogo
      set color                      brown                                              ; 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
      set Price                      1.0001                                             ; initial value for price
      set Capital                    Initial-capital                                    ; initial value for capital
      set Inventory-investment       0
      set Stock                      Initial-production-K-firms                         ; initial value for stock
      set Production                 Initial-production-K-firms                         ; initial value for production
      set Probability-of-Bankruptcy  0.0001
      set Revenue                    0                                                  ; initial value for revenue
      set Sales                      0                                                  ; initial value for sales
      set Need-Cash                  0                                                  ; initial value for cash needed
      set Desired-Investment         0                                                  ; initial value for desire investment
      set Investment                 ""                                                 ; initial value for investment
      set Number-of-Employees        0                                                  ; initial number for employees
      set Desired-Employees          0                                                  ; initial value for desired employees
      set Price-List                 ""                                                 ; not applied to K-Firms
      set Vacancy                    0                                                  ; initial value for vacancy
      set Bank-Account-Firm          max list 0 (random-normal Initial-liquidity-of-Firms 1)         ; initial money deposited at the banks by the firms
      set Bank-Account-Firm_1        Bank-Account-Firm
      set Investment-Memory          ""                                                 ; not applied to K-Firms
      set Util-Capacity              ""                                                 ; not applied to K-Firms
      ]
    ]
end 

to Setup-Bank
   create-Banks 1 [                                                                      ; create one bank
    set Own-Bank-Capital             Initial-Capital-of-the-bank                         ; initial value fo the own bank equity
    set Total-Accounts               Total-Accounts-Workers + Total-Accounts-Capitalists + Total-Accounts-C-Firms + Total-Accounts-K-Firms + Own-Bank-Capital
   ]
end 

to 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
  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 Taylor-Interest-Rate              natural-interest-rate                              ; we don't need Central Bank for this
  set GDP                               1.0001                                             ; initial GDP
  set GDP_1                             1.0001
  set Unemployment-Rate                 0                                                  ; initial Unemployment-Rate rate
  set Total-Consumption                 0                                                  ; initial value of Total-Consumption
  set Total-Investment                  0                                                  ; initial value of total investment
  set Goods-Price-Level                 1.0001                                             ; initial goods price level
  set Capital-Price-Level               1.0001                                             ; initial capital goods price level
  set General-Price-Level               1.0001
  set Wage                              Minimum-Wage                                       ; initial value for wage
  set Central-Bank-Own-Capital          Initial-Capital-of-the-bank
  set Account-of-State-at-Central-Bank  0                                                  ; Account of the State at the Central Bank
  set State-Budget                      0
  set Matrix-C-Firms-Bankruptcy         matrix:make-constant  2 Time-Window 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-W" columns
  set Matrix-K-Firms-Bankruptcy         matrix:make-constant  2 Time-Window 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-W" 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 Public-Debt                       0                                                  ; public debt titles sold to the central bank
  if not Random-Seed?                  [ random-seed 12345 ]                               ; random seed may or not be used
end 


             ; TO GO

to Go                                                              ; here will be calling the functions
  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-Cash-Flows                                              ; this function update the cash flow
  Function-UpDate-Globals                                          ; this function update the globals
  if Macroprudential-Policy? [
     if ticks > 100  [Function-Set-Macroprudential-Rules]          ; this function sets the limits to available credit for firms
  ]
  Function-Credit-Market                                           ; this function update the credit market
  Function-Update-Wages
  if Firm-Regeneration? [Function-New-Firms-Entries]
  if Do_We_Have_State?  [ Function-Call-State ]
  if Do_We_Have_Central-Bank? [ Function-Call-Central-Bank ]       ; r = r*
  tick                                                             ; NetLogo needs this because it controls time
end 


             ; FUNCTIONS

             ; TO FUNCTION-JOB-MARKET

to Function-Job-Market                                                                             ; here will be called the subfunctions
  ask Firms                                 [ SubF-UpDate-Desired-Workers set Need-Cash 0 ]        ; reset the firms need for cash and update the desire workers number
  if Do_We_Have_State? = false or Unemployment-Benefits? = false [                                 ; if you do not have unemployment benefits...
     ask Workers with [not Employed?]       [ SubF-Find-a-Job ]                                    ; ask workers which did not have a job to look for one
  ]
  if Do_We_Have_State? = true and Unemployment-Benefits? = true [                                  ; if you have unemployment benefits...
     ask Workers with [not Employed?] [                                                            ; ask workers which did not have a job to look for one
         let rand                             random-float 1
         if rand > Unemployment-Cover [                                                            ; the higher the unemployment benefit, the lower the probability of looking for a job
             SubF-Find-a-Job
         ]
     ]
  ]
  ask Workers                               [ set Bank-Account-Household   Bank-Account-Household + Current-Income   ]     ; ask workers to update their income (wages)
  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 desire workers
  if C-Firm? [                                                                                                             ; if C-firms is true, only C-Firm run this, because K-Firms do not have capital for the calculation...
     set Desired-Employees        min list Desired-Employees ((Capital * Productivity-of-capital) / Productivity-of-labor) ; set desired employees considering the capital production restriction (Assanza et al. 2015, eq. 5.9)
     if Hiring-Liquidity-Constraint? [                                                                                     ; if this switch is on, the firm will hire employees limited to the Bank-Account-Firm resources
         if Desired-Employees * wage > Bank-Account-Firm [                                                                 ; if Desired-Employees multiplied by wage is larger than the Bank-Account, the Desired-Employees is updated
         set Desired-Employees    max list 0 (int (Bank-Account-Firm / Wage) + 1)                                          ; update the desired employees considering the money available
         ]                                                                                                                 ; K-Firms set their desired employees later, with "Report-K-Update-Desired-Employees"
     ]
  ]
  set Vacancy                                Desired-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 some one
         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
             ]
             die                                                                          ; die means this worker no more has a contract with the firm, fired
         ]
    set Vacancy                              Vacancy               + 1                    ; confirm the fired process, perhaps need to fire another one
    set Number-of-Employees                  Number-of-Employees   - 1                    ; update the number of employee after the firing process
  ]
end 

to SubF-Find-a-Job                                                                        ; this subfunction is used by the worker trying to find a job position
   set Current-Income                              0                                      ; reseting this variable, because the only source of income for
   repeat Number-of-firms-visited-by-unemployed-workers [                                 ; the worker can try a maximum number of times to get a job, if not find one he still unemployeed
          setxy                                    random-xcor random-ycor                ; this means the worker visit a firm at the grid
          while [not any? Firms-here] [
                setxy                              random-xcor random-ycor
          ]
          let Vacancy?                             false                                  ; auxiliar variable to this subfunction
          ask one-of Firms-here [                                                         ; ask to the firm visited if ...
              if Vacancy > 0 [                                                            ; ... it has an open position
                 set Vacancy?                      true                                   ; update auxiliar variable
                 set Number-of-Employees           Number-of-Employees + 1                ; update the number of employees, because the firm hires the worker
                 set Vacancy                       Vacancy             - 1                ; update the vacancy of this firm
              ]
          ]
          if Vacancy? [                                                                   ; using the auxiliar variable to update the worker status
             ifelse Do_We_Have_State? [
                    set Current-Income             Wage * (1 - Income-Tax)
                    set State-Budget               Wage * Income-Tax
             ] [
             set Current-Income                    Wage                                   ; update the Current-income of the worker
             ]
             create-Hired-from                     one-of Firms-here [set hidden? true]   ; we create a link with the firm here, and this link means the worker has a job, and him and the firm knows about each other
             set Employed?                         true
             stop                                                                         ; for the repeat function, if it finds a job did not need try once more
          ]
  ]
  if Unemployment-Benefits? = true and 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                                                         ; QEasing means Quantitative Easing, and this is a policy that opens unlimited buying of Public Debt
   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-GOODS-MARKET

to Function-Consumption-Market                                           ; here will be called the subfunctions of the Total-Consumption market
  ask C-firms [                                                          ; updating properties of the C-Firms
    set Demand               0
    set Sales                0
    set Revenue              0
  ]
  ask Households [                                                       ; explicit
    SubF-UpDate-Desired-Consumption                                      ; call subfunction for households update their desired Total-Consumption
    SubF-Visit-C-Firms                                                   ; call subfunction for households visit firm trying to Consumption
    if Desired-Consumption > 0 [ SubF-Try-Consumption ]                  ; if wana Consumption something, try 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 Total-Consumption, it can not be higher than the money the household has
  set Desired-Consumption                     max list  0                           Desired-Consumption                                                                  ; ensure desired consumption is not negative
end 

to SubF-Visit-C-Firms                                                                              ; this subfunction rules the shopping process, visiting the firms
   let Who01                                   ""                                                  ; auxiliar variable, save the name of the first firm visited
   let Who02                                   ""                                                  ; auxiliar variable, save the name of the second firm visited
   let Price01                                 ""                                                  ; auxiliar variable, save the price of the first firm visited
   let Price02                                 ""                                                  ; auxiliar variable, save the price of the second firm visited
   setxy random-xcor random 8                                                                      ; choose the address of one random C-firm
   while [not any? Firms-here] [
          setxy                                random-xcor random 8
   ]
   ask one-of Firms-here [
       set Who01                               Who                                                 ; save the name of this firm
       set Price01                             Price                                               ; save the price of this firm
   ]
   setxy random-xcor random 8                                                                      ; choose the address of one random C-firm
   while [not any? Firms-here] [
          setxy                                random-xcor random 8
   ]
   ask one-of Firms-here [                                                                         ; choose the address of the second firm
       set Who02                               Who                                                 ; save the name of this firm
       set Price02                             Price                                               ; save the price of this firm
   ]
   while [Who01 = Who02] [                                                                         ; if happened to visited the same firm twice, find another one, repeat the process above
         setxy                                 random-xcor random 8                                ; choose the address of one random C-firm
         while [not any? Firms-here] [
                setxy                          random-xcor random 8
         ]
         ask one-of Firms-here [
             set Who02                         Who
             set Price02                       Price
         ]
   ]
   ifelse Price01 < Price02 [set Price-List list (Firm Who01) (Firm Who02) ] [set Price-List list (Firm Who02) (Firm Who01) ]                    ; create an organized list, the firm with the lowest price comes first
end 

to SubF-Try-Consumption
  let Firm-A                                    first Price-List                                  ; extract the name of the firm with a better price
  let Firm-B                                    last  Price-List                                  ; extract the name of the firm with the worst price
  let Qtt                                       Desired-Consumption / [Price] of Firm-A           ; auxiliar variable, record the quantity that can be bought, DC/Pa
  set c-expenses                                0
  let expenses                                  0                                                 ; auxiliar variable to update the deposit at bank later
  let cons                                      0                                                 ; auxiliar variable to record the quantity Consumptiond
  ask Firm-A                                   [set Demand    Demand + Qtt ]                      ; update the demand of C-Firms
  if [Stock] of Firm-A < Qtt [                                                                    ; if there is not available goods at the first firm ...
    ask Firm-B [set Demand                      Demand + Qtt - [Stock] of Firm-A ]                ; also the second firm has a demand for their product
  ]
  ask Firm-A [                                                                                    ; trying to Consumption at the better price
    ifelse Stock > Qtt [                                                                          ; first situation, the better one in which the Consumptionr can Consumption all at the better price
      set Stock                                 Stock  - Qtt                                      ; updated the stock of the firm
      set Sales                                 Sales  + Qtt                                      ; update the sales
      set Revenue                               Price  * Qtt  + Revenue                           ; update the revenue
      set expenses                              Price  * Qtt  + expenses                          ; update the auxiliar variable, used later to update the household bank account
      set cons                                  cons   + Qtt                                      ; update the auxiliar variable to register the qtt Consumptiond
      set Qtt                                   0                                                 ; means no need to bought anymore
    ] [
      if Stock > 0 [                                                                              ; second situation, buying only part at 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 cons                                cons   +  Stock                                   ; update stock
        set Qtt                                 Qtt    -  Stock                                   ; update auxiliar variable to register the Qtt Consumptiond, Qtt = Qtt - S
        set Stock                               0                                                 ; update stock
      ]
    ]
  ]                                                                                               ; end ask Firm-A, because it already has its stock exhausted/depleted
  if Qtt > 0 [                                                                                    ; means household did not Consumption all it wanted to in the first firm
    set Qtt                                     (Qtt * [Price] of Firm-A) / [Price] of Firm-B     ; auxiliar variable, max quantity can Consumption at the new price, (Qtt - S)*Pa/Pb = [(DC)/Pa - S]*Pa/Pb = (DC - S*Pa)/Pb
    ask Firm-B [                                                                                  ; updating values at the second firm
      ifelse Stock > Qtt [                                                                        ; as above...
                                                                                                  ; first situation, buy all
        set Stock                               Stock  - Qtt
        set Sales                               Sales  + Qtt
        set Revenue                             Price  * Qtt  + Revenue
        set expenses                            Price  * Qtt  + expenses
        set cons                                cons   + Qtt
        set Qtt                                 0
        ] [
                                                                                                  ; second situation, did not Consumption all he wants
        if Stock > 0 [
          set Sales                             Sales  + Stock
          set Revenue                           Price  * Stock + Revenue
          set Expenses                          Price  * Stock + expenses
          set cons                              cons   + Stock
          set Qtt                               Qtt    - Stock
          set Stock                             0
          ]
        ]
      ]                                                                                           ; end ask Firm-B
    ]                                                                                             ; end Qtt > 0, because the process ends with an unsatisfied positive quantity
                                                                                                  ; update households atributes
  set c-expenses                                expenses
  set Consumption                               cons                                              ; update the Consumption 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 [
       set Demand                             0
       set Revenue                            0
       set Sales                              0
   ]                                                                                   ; update K-Firms properties
   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
   ]
   ask K-Firms [
       set Inventory-investment               Production - Sales
   ]
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 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 et al. 2015 eq. 5.7))
          if Investment-loan? [
             set Need-Cash                     Need-Cash + Desired-Investment * Capital-Price-Level          ; in this way the firm asks for a loan when the desired investment is set
          ]
    ]
    ]
end 

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

to SubF-Visit-K-Firms                                                                  ; searching for the better price, similar to the households sub-functions, check for details there
  let X                                           xcor                                 ; the diference is that the firm need to have a fixed position. This X and Y auxiliar variables save the firm position at the grid
  let Y                                           ycor
  let Who01                                       ""
  let Price01                                     ""
  let Who02                                       ""
  let Price02                                     ""
  setxy                                           random-xcor (random 2 + 8)
  while [not any? other Firms-here] [
        setxy                                     random-xcor (random 2 + 8)
  ]
  ask one-of other Firms-here [
    set Who01                                     Who
    set Price01                                   Price
  ]
  setxy                                           random-xcor (random 2 + 8)
  while [not any? other Firms-here] [
        setxy                                     random-xcor (random 2 + 8)
  ]
  ask one-of other Firms-here [
    set Who02                                     Who
    set Price02                                   Price
  ]
  while [ Who01 = Who02 ] [
          setxy                                   random-xcor (random 2 + 8)
          while [not any? other Firms-here] [
                 setxy                            random-xcor (random 2 + 8)
          ]
          ask one-of other Firms-here [
              set Who02                           Who
              set Price02                         Price
          ]
  ]
  ifelse Price01 < Price02 [ set Price-List list (Firm Who01) (Firm Who02) ] [set Price-List list (Firm Who02) (Firm Who01) ]
  setxy                                           X Y                                                ; return the firm to their position after the prices search
end 

to SubF-Buy-Capital                                                                                  ; sub-function to buy capital goods
  set k-expenses                                0                                                    ; sub-function auxiliar variable to save the investment expenses of the C-Firm
  let expenses                                  0
  let New-Inv                                   0                                                    ; sub-function auxiliar variable to save the number of units of capital bought by the C-Firm
  let Firm-A                                    first Price-List                                     ; extract the name of the K-Firm with the better price
  let Firm-B                                    last  Price-List                                     ; extract the name of the K-Firm with the second price
  let Qtt                                       Desired-Investment                                   ; auxiliar variable register the Qtt C-Firm want to buy

  if C-Firm_Budget_Constraint? [                                                                     ; including budget restriction, this way the demand of k-firm is afected by the monetary restriction
     let Budget                                 Qtt * [Price] of Firm-A                              ; auxiliar variable with the monetary value the C-Firm can afford to invest
     if Budget > Bank-Account-Firm [                                                                 ; check if the C-Firm has enough money to invest
        set Qtt                                 max list 0 (Bank-Account-Firm / [Price] of Firm-A)   ; rebalance the investment according to money available
     ]
  ]

  ask Firm-A [ set Demand                       Demand + Qtt ]                                       ; updating demand at the first K-Firm

  if [stock] of Firm-A < Qtt [                                                                       ; check if the K-Firm has enough stock to supply
      ask Firm-B [ set Demand                   Demand + Qtt - [Stock] of Firm-A ]                   ; when the first did no has enough stock, also update the demand of the second k-firm
  ]

  ifelse [stock] of Firm-A >= Qtt [                                                                  ; trying to buy when there is more stock than demand
    ask Firm-A [                                                                                     ; first situation, better one, it is possible to bought all at the better price
      set Stock                                 Stock   - Qtt                                        ; updating properties of the K-Firm ...
      set Revenue                               Price   * Qtt + Revenue                              ; ...
      set expenses                              Price   * Qtt + expenses                             ; ...
      set Sales                                 Sales   + Qtt                                        ; ...
      set New-Inv                               New-Inv + Qtt                                        ; ...
      set Qtt                                   0                                                    ; ... end first situation for Firm-A
    ]
  ] [
    if [stock] of Firm-A > 0 [                                                                       ; second situation, there is not enough stock at the first firm, but the stock is positive
       ask Firm-A [                                                                                  ; updating properties of the K-Firm ...
         set Revenue                            Price   * Stock + Revenue                            ; ...
         set expenses                           Price   * Stock + expenses                           ; ...
         set Sales                              Sales   + Stock                                      ; ...
         set Qtt                                Qtt     - Stock                                      ; ...
         set New-Inv                            New-Inv + Stock                                      ; ...
         set Stock                              0                                                    ; ... end second situation for Firm-A
       ]
    ]
  ]

  if Qtt > 0 [                                                                                       ; means the C-Firm did not Consumption all investment needed
    ifelse [stock] of Firm-B >= Qtt [                                                                ; first situation, it is possible to bought all it is needed
      ask Firm-B [                                                                                   ; updating properties of the K-Firm ...
        set Stock                               Stock   - Qtt                                        ; ...
        set Revenue                             Price   * Qtt + Revenue                              ; ...
        set expenses                            Price   * Qtt + expenses                             ; ...
        set Sales                               Sales   + Qtt                                        ; ...
        set New-Inv                             New-Inv + Qtt                                        ; ...
        set Qtt                                 0                                                    ; ... end first situation for Firm-B
      ]
    ] [
    if [stock] of Firm-B > 0 [                                                                       ; second situation, the C-Firm will not invest all it wants to
      ask Firm-B [                                                                                   ; updating the properties of the K-Firm ...
        set Revenue                            Price   * Stock + Revenue                             ; ...
        set expenses                           Price   * Stock + expenses                            ; ...
        set Sales                              Sales   + Stock                                       ; ...
        set Qtt                                Qtt     - Stock                                       ; ...
        set New-Inv                            New-Inv + Stock                                       ; ...
        set Stock                              0                                                     ; ... end second situation Firm-B
      ]
    ]
    ]
  ]
  set k-expenses                   expenses
  set Investment                   New-Inv                                                           ; updating this property of the C-Firm, the investment in real-terms
  set Bank-Account-Firm            Bank-Account-Firm - expenses                                      ; updating the bank account the C-Firm, which has secured the necessary liquidity with a loan (see line 590)
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 production for the next period
    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
    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 Desired-Employees    Report-K-Update-Desired-Employees    ]                     ; the user may force the K-Firm to produce capital goods ...
                                    [ set Desired-Employees    Demand   /   Productivity-of-labor   ]                     ; ...if the switcher at HUD is turned off
    ifelse K-UpDate-Price?          [ set Price                Report-K-Update-Price                ]                     ; the user may force the capital price be fixed if ...
                                    [ set Price                Wage / Productivity-of-Labor         ]                     ; ...the switcher at HUD is turned off
    ]
  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 et al. 2015)
    set Production                  min list (Number-of-Employees * Productivity-of-labor) (Capital * Productivity-of-capital)     ; leontief production function
    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 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 Desired-Employees    Report-C-Update-Desired-Employees  ]                                ; the user may force the C-Firm to produce C-goods ...
                                    [ set Desired-Employees    Demand / Productivity-of-labor   ]                                  ; ...if the switcher at HUD is turned off
    ifelse C-UpDate-Price?          [ set Price                Report-C-Update-Price            ]                                  ; the user may force the consumption good be fixed ...
                                    [ set Price                Wage / Productivity-of-Labor     ]                                  ; ...if the switcher at HUD is turned off
    ]
end 

to-report Report-C-Update-Price                                                                                                                      ; reporting the new price for C-Firms ... remember: delta = production - demand
  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 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 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 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 et al. 2015)
  report                             N-P                                                                                                             ; report new price
end 

to-report Report-C-Update-Desired-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 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 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-Desired-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 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 et al. 2015)
  report N-E                                                                                                                                                          ; report new need for employees
end 




             ; UPDATE GLOBALS

to Function-UpDate-Globals                                                                                               ; this function update the globals
  set Total-Investment                  sum [  Investment ] of C-Firms                                                   ; update investment realized by the C-Firms, in real terms (units)
  set Total-Consumption                 sum [ Consumption ] of Households                                                ; update the Total-Consumption, in real terms (units)
  set Goods-Price-Level_1               Goods-Price-Level
  set Capital-Price-Level_1             Capital-Price-Level
  set General-Price-Level_1             General-Price-Level
  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
  if sum [Sales] of K-Firms != 0 and sum [Sales] of C-Firms != 0  [                                                      ; update the general price level
     set General-Price-Level  sum [Revenue ] of Firms / sum [Sales] of Firms
  ]
  set cpi_1                             cpi                                                                              ; store the cpi value for use with adaptative functions... it is a global variable
  set cpi                              (Goods-Price-Level - Goods-Price-Level_1) /  Goods-Price-Level_1                  ; cpi is the Consumption prince index, user for indexing salaries
  set kpi_1                             kpi
  set kpi                              (Capital-Price-Level - Capital-Price-Level_1) / Capital-Price-Level_1
  set gpi_1                             gpi                                                                              ; this approximation with logarithms is good only if the rate is close to zero
  set gpi                              (General-Price-Level - General-Price-Level_1) / General-Price-Level_1
  set C-Index                           100 * (1 + cpi)
  set K-Index                           100 * (1 + kpi)
  set G-Index                           100 * (1 + gpi)
  set Employment_1                      Employment
  set Employment                        sum [Number-of-Employees] of Firms
  set Unemployed-People                 count Workers - sum [Number-of-Employees] of Firms
  set Unemployment-Rate                 1 - ((sum [Number-of-Employees] of Firms) / Number-of-Workers)                   ; update the unemployemnt rate
  set Total-Inventory-investment_1      Total-Inventory-investment
  set Total-Inventory-investment        max list 0 (sum [Inventory-investment] of K-Firms)

  set GDP_or                            (sum [ Production ] of Firms + sum [stock] of K-Firms)                           ; this was the original formula, adding up physical amounts
  set GDP_va                            (sum [ Production ] of C-Firms * Goods-Price-Level + sum [ Production ] of K-Firms * Capital-Price-Level - Total-Inventory-investment_1 * Capital-Price-Level_1) / (General-Price-Level)
  set GDP_exp                           (Total-Consumption * Goods-Price-Level + Total-Investment * Capital-Price-Level + Total-Inventory-investment * Capital-Price-Level) / (General-Price-Level)
  set GDP_inc                           (Employment * Wage + sum [EBIT] of Firms) / (General-Price-Level)

  set GDP_1                             GDP
  if GDP_approach = "original"    [     set GDP   GDP_or      if GDP <= 0 [set GDP 1] ]
  if GDP_approach = "production"  [     set GDP   GDP_va      if GDP <= 0 [set GDP 1] ]
  if GDP_approach = "income"      [     set GDP   GDP_inc     if GDP <= 0 [set GDP 1] ]
  if GDP_approach = "expenditure" [     set GDP   GDP_exp     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 Growth-lenght              0
         set Recession-Periods          Recession-Periods + 1
  ] [
         set Recession-lenght           0                                                                                ; if there is no recession, the counter is set to zero
         set Growth-lenght              Growth-lenght + 1
  ]
  if ticks > 1 [
     set Growth-Rate                   (GDP - GDP_1) * 100 / GDP_1
  ]
end 



             ; FUNCTION-CASH-FLOWS

to Function-Cash-Flows                                           ; this function set the movement of cash in the system

  ; C-FIRMS
  ask C-Firms [                                                  ; Cash flow of C-Firms
    let div                                        0             ; auxiliar variable
    ifelse  Dividend-Payments-of-Firms? [                        ; HUD control for a slighly different calculation of profits
      set EBIT                                     max list 0 (Revenue - Number-of-Employees * Wage - Depreciation-of-Capital-C * Capital * Capital-Price-Level_1 - Interest-Pay - Installment-Pay)  ; Assenza et al. eq. 9.4
      if EBIT > 0 [
         ifelse Do_We_Have_State? [
            set Profit                             EBIT * (1 - Corporate-Tax)               ; this profit is net of taxes
            set State-Budget                       State-Budget + Corporate-Tax * EBIT      ; the taxes go to the government
            set Bank-Account-Firm                  Bank-Account-Firm - Corporate-Tax * EBIT ; the firm pays the taxes
         ] [
            set Profit                             EBIT                                     ; this profit is net of taxes
         ]
         set Dividend                              dividend-payout-ratio-firms * Profit     ; if there was profit setup dividend
         ifelse Bank-Account-Firm > 0 and Bank-Account-Firm >= Dividend [
                set Bank-Account-Firm              Bank-Account-Firm - Dividend             ; the bank account of the firm is reduced by the dividend which will be payed to the capitalist
                set Div                            Dividend                                 ; auxiliar variable for bringing the div to the capitalist later
         ] [
                set Div                            Bank-Account-Firm                        ; the limit for divided payment is the bank account of the firm
                set Bank-Account-Firm              0
         ]

         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                           0
             ifelse Do_We_Have_State? [
                        set Current-Income                div * (1 - Income-Tax)                              ; update the Current income
                        set Bank-Account-Household        Bank-Account-Household  +  div * (1 - Income-Tax)   ; update the bank account of the household
                        set State-Budget                  State-Budget + Income-tax * div                     ; the taxes go to the government
                 ] [
                        set Current-Income                div                                                 ; update the Current income
                        set Bank-Account-Household        Bank-Account-Household  +  div                      ; upd
             ]
             ]
        ]
      ]

    ] [                                                                                                             ; this is a far simpler procedure

      set EBIT                                  max list 0 ( Revenue - Number-of-Employees * Wage)                  ; check if the firm had this kind of profit this period
      ifelse Do_We_Have_State? [
         set Profit                             EBIT * (1 - Corporate-Tax)                                          ; this profit is net of taxes
         set State-Budget                       State-Budget + Corporate-Tax * EBIT                                 ; the taxes go to the government
         set Bank-Account-Firm                  Bank-Account-Firm - Corporate-Tax * EBIT                            ; the firm pays the taxes
         ] [
         set Profit                             EBIT                                                                ; this profit is net of taxes and financial costs (interests paid)
         ]
      set Dividend                              min list (dividend-payout-ratio-firms * Profit) (max list 0 (Bank-Account-Firm))    ; the firm pays dividends with a maximum determined by the bank account
      set Bank-Account-Firm                     Bank-Account-Firm - Dividend                                                        ; reduce the bank account the dividen 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
          ask other-end [                                                                                                           ; other end is the capitalist
              set Current-Income                       0
              ifelse Do_We_Have_State? [
                     set Current-Income                div * (1 - Income-Tax)                              ; update the Current income
                     set Bank-Account-Household        Bank-Account-Household  +  div * (1 - Income-Tax)   ; update the bank account of the household
                     set State-Budget                  State-Budget + Income-tax * div                     ; the taxes go to the government
                 ] [
                     set Current-Income                div                                                 ; update the Current income
                     set Bank-Account-Household        Bank-Account-Household + div                        ; upd
              ]
          ]
      ]
    ]
  ]

  ; K-FIRMS
  ask K-Firms [                                                                             ; Cash flow of C-Firms
    let div                                        0                                        ; auxiliar variable
    ifelse  Dividend-Payments-of-Firms? [                                                   ; HUD control
      set EBIT                                     max list 0 ( Revenue - Number-of-Employees * Wage - Interest-Pay - Installment-Pay)        ; Assenza et al. eq. 9.9
      if EBIT > 0 [
         ifelse Do_We_Have_State? [
         set Profit                                EBIT * (1 - Corporate-Tax)               ; this profit is net of taxes
         set State-Budget                          State-Budget + Corporate-Tax * EBIT      ; the taxes go to the government
         set Bank-Account-Firm                     Bank-Account-Firm - Corporate-Tax * EBIT ; the firm pays the taxes
         ] [
         set Profit                                EBIT                                     ; this profit is net of taxes
         ]
         set Dividend                              dividend-payout-ratio-firms * Profit     ; if there was profit setup dividend
         ifelse Bank-Account-Firm > 0 and Bank-Account-Firm >= Dividend [
                set Bank-Account-Firm              Bank-Account-Firm - Dividend             ; the bank account of the firm is reduced by the dividend which will be payed to the capitalist
                set Div                            Dividend                                 ; auxiliar variable for bringing the div to the capitalist later
         ] [
                set Div                            Bank-Account-Firm
                set Bank-Account-Firm              0
         ]
         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                       0
                 ifelse Do_We_Have_State? [
                        set Current-Income                div * (1 - Income-Tax)                              ; update the Current income
                        set Bank-Account-Household        Bank-Account-Household  +  div * (1 - Income-Tax)   ; update the bank account of the household
                        set State-Budget                  State-Budget + Income-tax * div                     ; the taxes go to the government
                 ] [
                        set Current-Income                div                                                 ; update the Current income
                        set Bank-Account-Household        Bank-Account-Household + div                        ; upd
                 ]
             ]
        ]
    ]

    ] [                                                                                                 ; this is a far simpler procedure

      set EBIT                                  max list 0 ( Revenue - Number-of-Employees * Wage)      ; check if had profit this period
      ifelse Do_We_Have_State? [
         set Profit                             EBIT * (1 - Corporate-Tax)                ; this profit is net of taxes
         set State-Budget                       State-Budget + Corporate-Tax * EBIT       ; the taxes go to the government
         set Bank-Account-Firm                  Bank-Account-Firm - Corporate-Tax * EBIT  ; the firm pays the taxes
      ] [
         set Profit                             EBIT                                      ; this profit is net of taxes
      ]
      set Dividend                              min list (dividend-payout-ratio-firms * Profit) (max list 0 (Bank-Account-Firm))     ; if there was profit setup dividend
      set Bank-Account-Firm                     Bank-Account-Firm - Dividend                                                         ; reduce the bank account the dividen 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
          ask other-end [                                                                                                            ; other end is the capitalist
              set Current-Income                       0
              ifelse Do_We_Have_State? [
                     set Current-Income                div * (1 - Income-Tax)                              ; update the Current income
                     set Bank-Account-Household        Bank-Account-Household  +  div * (1 - Income-Tax)   ; update the bank account of the household
                     set State-Budget                  State-Budget + Income-tax * div                     ; the taxes go to the government
                 ] [
                     set Current-Income                div                                                 ; update the Current income
                     set Bank-Account-Household        Bank-Account-Household + div                        ; upd
                 ]
          ]
      ]
  ]
]

  ask Banks [                                                                                             ; update the data into the retail bank system... the banks also pay dividends (SubF-Distribute-Dividends)
    set Total-Accounts-Workers               sum [Bank-Account-Household] of Workers                      ; explicit
    set Total-Accounts-Capitalists           sum [Bank-Account-Household] of Capitalists                  ; explicit
    set Total-Accounts-C-Firms               sum [Bank-Account-Firm] of C-firms                           ; explicit
    set Total-Accounts-K-Firms               sum [Bank-Account-Firm] of K-firms                           ; explicit
    set Total-Accounts_1                     Total-Accounts
    set Total-Accounts                       Total-Accounts-Workers + Total-Accounts-Capitalists + Total-Accounts-C-Firms + Total-Accounts-K-Firms + Own-Bank-Capital        ; explicit
    if Do_We_Have_Central-Bank?            [ set Reserves    max list 0 (Total-Accounts * Reserve-Requirement) ]
  ]                                                                                                       ; end of ask banks
end 



; FUNCTION-CREDIT-MARKET

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

   if Do_We_Have_Banks? [                                                   ; switch in HUD to controle the retail bank

     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-Equity                                                 ; to update assets value
         SubF-Update-Leverage                                               ; to update the leverage, all this is used to rule interest rate practiced later
     ]

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

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

     let I-Received                   sum [Interest-Pay       ] of Firms    ; local variable
     let D-Received                   sum [Installment-Pay    ] of Firms    ; local variable

     ask Banks [                                                            ; the retail bank update the balance after the new was created
        set Total-Loans-C-Firms       sum [Current-Retail-Loan] of C-Firms  ; explicit
        set Total-Loans-K-Firms       sum [Current-Retail-Loan] of K-Firms  ; explicit
        set Total-Loans_1             Total-Loans
        set Total-Loans               sum [Current-Retail-Loan] of Firms    ; we introduce
        set Interests-Received        I-Received                            ; explicit
        set Installments-Received     D-Received                            ; explicit

        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 Own-Bank-Capital          Own-Bank-Capital + Interests-Received - Central-Bank-Loans * (taylor-interest-rate + Installment-on-debt)
        set Central-Bank-Loans        Central-Bank-Loans - Central-Bank-Loans * Installment-on-debt
        set Assets                    max list 0 (Total-Loans-C-Firms + Total-Loans-K-Firms + Own-Bank-Capital)
        set Liabilities               max list 0 (Total-Accounts-Workers + Total-Accounts-Capitalists + Total-Accounts-C-Firms + Total-Accounts-K-Firms + Central-Bank-Loans)
        set Bank-Equity               Assets - Liabilities
        SubF-Distribute-Dividends
     ]
  ]

  ask Firms [
      set Bank-Account-Firm_1         Bank-Account-Firm                     ; we record the deposits of the firms at this moment for the next perdiod (see SubF-Update-Cash-Need)
  ]

  if C-Bankruptcy? [                                       ; 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-Type-C                     ; subfunction to lead the broke process
         ]
     ]
  ]

  if K-Bankruptcy? [                                       ; the same as the C-firm, check above for details
     ask K-Firms [
         if (Cases-of-Bankruptcy > T-Ban) [
             SubF-Go-Bankruptcy-Type-K
         ]
     ]
  ]
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 ]
    set Mjc Mjc + 1 if Mjc > (Time-Window - 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-Window - 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 second row of the matrix, which contains the Leverage for every K-Firm

  r:put   "a" A                                                                                    ; call the R engine and put there the object A
  r:put   "b" B                                                                                    ; call the R engine 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 

to SubF-Update-Installment                                                                             ; this subfunction update the installment debt with retail banks
  set  Interest-Pay                           0                                                        ; reset parameter
  set  Installment-Pay                        0                                                        ; reset parameter, the repayment schedule
  if Current-Retail-Loan > 0 [                                                                         ; check if exist loan
     ifelse Bank-Account-Firm >= ((Installment-on-Debt + Interest-Retail) * Current-Retail-Loan) [     ; check if there is money enough to pay the debts
            set Interest-Pay                  Interest-Retail * Current-Retail-Loan                    ; update the parameter with the value will be payed
            set Installment-Pay               Installment-on-Debt * Current-Retail-Loan                ; update parameter
            set Bank-Account-Firm             Bank-Account-Firm - Installment-Pay - Interest-pay       ; update parameter
            set Current-Retail-Loan           Current-Retail-Loan - Installment-Pay                    ; update parameter... and this is important, because the bank aggregates this variable and installments are included
            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
      ]
  ]
end 

to SubF-Update-Cash-Need                ; subfuntion used for updating the need for cash (loans)
   ifelse Investment-loan? [            ; see line 590... C-Firms already asked for a loan when desired-investment (before k-expenses) was set. So it is invetment planning the key here
         set Need-Cash                  max list 0 (Need-Cash + Number-of-Employees * Wage + (Installment-on-Debt + Interest-Retail) * Current-Retail-Loan - Bank-Account-Firm_1)
   ] [
   ifelse Bank-Account-Firm >= 0 [      ; See eqs. 7.1 and 7.2 in Assenza et al. 2015.
      if C-Firm? [
         set Need-Cash                  max list 0 (Need-Cash + Number-of-Employees * Wage + K-Expenses + (Installment-on-Debt + Interest-Retail) * Current-Retail-Loan - Bank-Account-Firm_1)
      ]
      if not C-Firm? [
         set Need-Cash                  max list 0 (Need-Cash + Number-of-Employees * Wage + (Installment-on-Debt + Interest-Retail) * Current-Retail-Loan - Bank-Account-Firm_1)
      ]
   ] [
      set Need-Cash                     max list 0 (abs Bank-Account-Firm + Initial-Liquidity-of-Firms)
   ]
   ]
end 

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

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

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

  ifelse Macroprudential-Policy? [

   if Risk-Calculations-Procedure = "Original" [
      ; how much money the bank may offer as a loan, see eq. 27 of Elder Silva's document
      set New-Credit-Available             max list 0 (Bank-loss-parameter * (sum [Own-Bank-Capital] of Banks * B-Lev * ( Risk-spread ) - sum [Current-Retail-Loan] of Firms))

      ; no constraints
      if (Need-Cash > 0) and (Available-Credit-Basel > Need-Cash) and (Need-Cash < New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [                                                           ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  Need-Cash                                                           ; the reduces the available-credit-assenza with each new loan because Current-Retail-Loan increases
          set Bank-Account-Firm            Bank-Account-Firm  +  Need-Cash                                                             ; updating the bank account with the money received
          set Need-Cash                    0
          set Available-Credit-Basel       Available-Credit-Basel - Need-Cash
          ifelse Retail-Interest? and ticks > 100  [ SubF-Update-Interest-Retail-K ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]

      ; the central bank has a constraint
      if (Need-Cash > 0) and (Available-Credit-Basel <= Need-Cash) and (Need-Cash < New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [                                                           ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  Available-Credit-Basel                                              ; the reduces the available-credit-assenza with each new loan because Current-Retail-Loan increases
          set Bank-Account-Firm            Bank-Account-Firm  +  Available-Credit-Basel                                                ; updating the bank account with the money received
          set Need-Cash                    Need-Cash - Available-Credit-Basel
          set Available-Credit-Basel       0
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-K ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]

      ; the retail bank has a constraint
      if (Need-Cash > 0) and (Available-Credit-Basel > Need-Cash) and (Need-Cash >= New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [                                                            ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  New-Credit-Available                                                ; the reduces the available-credit-assenza with each new loan because Current-Retail-Loan increases
          set Bank-Account-Firm            Bank-Account-Firm  +  New-Credit-Available                                                  ; updating the bank account with the money received
          set Need-Cash                    Need-Cash - New-Credit-Available
          set Available-Credit-Basel       Available-Credit-Basel - New-Credit-Available
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-K ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]

      ; the retail bank and the central bank have a constraint, but the later's is tighter
      if (Need-Cash > 0) and (Available-Credit-Basel <= Need-Cash) and (Need-Cash >= New-Credit-Available) and (Available-Credit-Basel < New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [          ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  Available-Credit-Basel                                              ; updating the loans parameter
          set Bank-Account-Firm            Bank-Account-Firm  +  Available-Credit-Basel                                                ; updating the bank account with the money received
          set Need-Cash                    Need-Cash - Available-Credit-Basel
          set Available-Credit-Basel       0
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-K ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]

      ; the retail bank and the central bank have a constraint, but the former's is tighter
      if (Need-Cash > 0) and (Available-Credit-Basel <= Need-Cash) and (Need-Cash >= New-Credit-Available) and (Available-Credit-Basel >= New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [        ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  New-Credit-Available                                                ; updating the loans parameter
          set Bank-Account-Firm            Bank-Account-Firm  +  New-Credit-Available                                                  ; updating the bank account with the money received
          set Need-Cash                    Need-Cash - New-Credit-Available
          set Available-Credit-Basel       Available-Credit-Basel - New-Credit-Available
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-K ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]
   ]

   if Risk-Calculations-Procedure = "Assenza" [
      ; how much money the bank may offer as a loan to a particular firm (not doable at an aggregate level), see footnote 32 in Assenza, Gatti, Grazzini et al. 2015
      set Max-Credit-to-Firm               max list 0  (Bank-loss-parameter * sum [Own-Bank-Capital] of Banks / Probability-of-Bankruptcy)
      ; how much money the bank may offer as a loan, see eq. 27 of Elder Silva's document
      ; let Available-Credit-Assenza         max list 0 (Bank-loss-parameter * (sum [Own-Bank-Capital] of Banks * B-Lev * ( Risk-spread ) - sum [Current-Retail-Loan] of Firms))
      ; how much money the bank may offer as a loan to a particular firm (not doable at an aggregate level), see eq. 8.11 in Assenza, Gatti, Grazzini et al. 2015
      set New-Credit-Available               max list 0  (Max-Credit-to-Firm - Current-Retail-Loan)

      ; no constraints
      if (Need-Cash > 0) and (Available-Credit-Basel > Need-Cash) and (Need-Cash < New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [                                                           ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  Need-Cash                                                           ; the reduces the available-credit-assenza with each new loan because Current-Retail-Loan increases
          set Bank-Account-Firm            Bank-Account-Firm  +  Need-Cash                                                             ; updating the bank account with the money received
          set Need-Cash                    0
          set Available-Credit-Basel       Available-Credit-Basel - Need-Cash
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-K ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]

      ; the central bank has a constraint
      if (Need-Cash > 0) and (Available-Credit-Basel <= Need-Cash) and (Need-Cash < New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [                                                           ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  Available-Credit-Basel                                              ; the reduces the available-credit-assenza with each new loan because Current-Retail-Loan increases
          set Bank-Account-Firm            Bank-Account-Firm  +  Available-Credit-Basel                                                ; updating the bank account with the money received
          set Need-Cash                    Need-Cash - Available-Credit-Basel
          set Available-Credit-Basel       0
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-K ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]

      ; the retail bank has a constraint
      if (Need-Cash > 0) and (Available-Credit-Basel > Need-Cash) and (Need-Cash >= New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [                                                            ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  New-Credit-Available                                                ; the reduces the available-credit-assenza with each new loan because Current-Retail-Loan increases
          set Bank-Account-Firm            Bank-Account-Firm  +  New-Credit-Available                                                  ; updating the bank account with the money received
          set Need-Cash                    Need-Cash - New-Credit-Available
          set Available-Credit-Basel       Available-Credit-Basel - New-Credit-Available
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-K ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]

      ; the retail bank and the central bank have a constraint, but the later's is tighter
      if (Need-Cash > 0) and (Available-Credit-Basel <= Need-Cash) and (Need-Cash >= New-Credit-Available) and (Available-Credit-Basel < New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [          ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  Available-Credit-Basel                                              ; updating the loans parameter
          set Bank-Account-Firm            Bank-Account-Firm  +  Available-Credit-Basel                                                ; updating the bank account with the money received
          set Need-Cash                    Need-Cash - Available-Credit-Basel
          set Available-Credit-Basel       0
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-K ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]

      ; the retail bank and the central bank have a constraint, but the former's is tighter
      if (Need-Cash > 0) and (Available-Credit-Basel <= Need-Cash) and (Need-Cash >= New-Credit-Available) and (Available-Credit-Basel >= New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [        ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  New-Credit-Available                                                ; updating the loans parameter
          set Bank-Account-Firm            Bank-Account-Firm  +  New-Credit-Available                                                  ; updating the bank account with the money received
          set Need-Cash                    Need-Cash - New-Credit-Available
          set Available-Credit-Basel       Available-Credit-Basel - New-Credit-Available
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-K ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]
   ]

   if Risk-Calculations-Procedure = "Teglio" [
      ; the formula for Probability-of-Bankruptcy comes from Teglio et al. (2012), eq. 1
      set New-Credit-Available             Need-Cash

      if (Need-Cash > 0) and (Available-Credit-Basel > Need-Cash) and (Cases-of-Bankruptcy < T-Ban) [                                  ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  Need-Cash                                                           ; the reduces the available-credit-assenza with each new loan because Current-Retail-Loan increases
          set Bank-Account-Firm            Bank-Account-Firm  +  Need-Cash                                                             ; updating the bank account with the money received
          set Need-Cash                    0
          set Available-Credit-Basel       Available-Credit-Basel - Need-Cash
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-K ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]

      if (Need-Cash > 0) and (Available-Credit-Basel <= Need-Cash) and (Cases-of-Bankruptcy < T-Ban) [                                 ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  Available-Credit-Basel                                              ; the reduces the available-credit-assenza with each new loan because Current-Retail-Loan increases
          set Bank-Account-Firm            Bank-Account-Firm  +  Available-Credit-Basel                                                ; updating the bank account with the money received
          set Need-Cash                    Available-Credit-Basel - Need-Cash
          set Available-Credit-Basel       0
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-K ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]
   ]

  ] [

   if Risk-Calculations-Procedure = "Original" [
      ; how much money the bank may offer as a loan, see eq. 27 of Elder Silva's document
      set New-Credit-Available             max list 0 (Bank-loss-parameter * (sum [Own-Bank-Capital] of Banks * B-Lev * ( Risk-spread ) - sum [Current-Retail-Loan] of Firms))

      ; no constraints
      if (Need-Cash > 0) and (Need-Cash < New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [                                                           ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  Need-Cash                                                           ; the reduces the available-credit-assenza with each new loan because Current-Retail-Loan increases
          set Bank-Account-Firm            Bank-Account-Firm  +  Need-Cash                                                             ; updating the bank account with the money received
          set Need-Cash                    0
          set Available-Credit-Basel       Available-Credit-Basel - Need-Cash
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-K ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]


      ; the retail bank has a constraint
      if (Need-Cash > 0) and (Need-Cash >= New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [                                                            ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  New-Credit-Available                                                ; the reduces the available-credit-assenza with each new loan because Current-Retail-Loan increases
          set Bank-Account-Firm            Bank-Account-Firm  +  New-Credit-Available                                                  ; updating the bank account with the money received
          set Need-Cash                    Need-Cash - New-Credit-Available
          set Available-Credit-Basel       Available-Credit-Basel - New-Credit-Available
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-K ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]

   ]

   if Risk-Calculations-Procedure = "Assenza" [
      ; how much money the bank may offer as a loan to a particular firm (not doable at an aggregate level), see footnote 32 in Assenza, Gatti, Grazzini et al. 2015
      set Max-Credit-to-Firm               max list 0  (Bank-loss-parameter * sum [Own-Bank-Capital] of Banks / Probability-of-Bankruptcy)
      ; how much money the bank may offer as a loan, see eq. 27 of Elder Silva's document
      ; let Available-Credit-Assenza         max list 0 (Bank-loss-parameter * (sum [Own-Bank-Capital] of Banks * B-Lev * ( Risk-spread ) - sum [Current-Retail-Loan] of Firms))
      ; how much money the bank may offer as a loan to a particular firm (not doable at an aggregate level), see eq. 8.11 in Assenza, Gatti, Grazzini et al. 2015
      set New-Credit-Available               max list 0  (Max-Credit-to-Firm - Current-Retail-Loan)

      ; no constraints
      if (Need-Cash > 0) and (Need-Cash < New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [                                                           ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  Need-Cash                                                           ; the reduces the available-credit-assenza with each new loan because Current-Retail-Loan increases
          set Bank-Account-Firm            Bank-Account-Firm  +  Need-Cash                                                             ; updating the bank account with the money received
          set Need-Cash                    0
          set Available-Credit-Basel       Available-Credit-Basel - Need-Cash
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-K ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]

      ; the retail bank has a constraint
      if (Need-Cash > 0) and (Need-Cash >= New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [                                                            ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  New-Credit-Available                                                ; the reduces the available-credit-assenza with each new loan because Current-Retail-Loan increases
          set Bank-Account-Firm            Bank-Account-Firm  +  New-Credit-Available                                                  ; updating the bank account with the money received
          set Need-Cash                    Need-Cash - New-Credit-Available
          set Available-Credit-Basel       Available-Credit-Basel - New-Credit-Available
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-K ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]
   ]

   if Risk-Calculations-Procedure = "Teglio" [
      ; the formula for Probability-of-Bankruptcy comes from Teglio et al. (2012), eq. 1
      set New-Credit-Available             Need-Cash

      if (Need-Cash > 0) and (Cases-of-Bankruptcy < T-Ban) [                                                                           ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  Need-Cash                                                           ; the reduces the available-credit-assenza with each new loan because Current-Retail-Loan increases
          set Bank-Account-Firm            Bank-Account-Firm  +  Need-Cash                                                             ; updating the bank account with the money received
          set Need-Cash                    0
          set Available-Credit-Basel       Available-Credit-Basel - Need-Cash
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-K ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]
   ]

 ]
end 

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

   ifelse Macroprudential-Policy? [

   if Risk-Calculations-Procedure = "Original" [
      ; how much money the bank may offer as a loan, see eq. 27 of Elder Silva's document
      set New-Credit-Available             max list 0 (Bank-loss-parameter * (sum [Own-Bank-Capital] of Banks * B-Lev * ( Risk-spread ) - sum [Current-Retail-Loan] of Firms))

      ; no constraints
      if (Need-Cash > 0) and (Available-Credit-Basel > Need-Cash) and (Need-Cash < New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [                                                           ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  Need-Cash                                                           ; the reduces the available-credit-assenza with each new loan because Current-Retail-Loan increases
          set Bank-Account-Firm            Bank-Account-Firm  +  Need-Cash                                                             ; updating the bank account with the money received
          set Need-Cash                    0
          set Available-Credit-Basel       Available-Credit-Basel - Need-Cash
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-C ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]

      ; the central bank has a constraint
      if (Need-Cash > 0) and (Available-Credit-Basel <= Need-Cash) and (Need-Cash < New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [                                                           ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  Available-Credit-Basel                                              ; the reduces the available-credit-assenza with each new loan because Current-Retail-Loan increases
          set Bank-Account-Firm            Bank-Account-Firm  +  Available-Credit-Basel                                                ; updating the bank account with the money received
          set Need-Cash                    Need-Cash - Available-Credit-Basel
          set Available-Credit-Basel       0
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-C ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]

      ; the retail bank has a constraint
      if (Need-Cash > 0) and (Available-Credit-Basel > Need-Cash) and (Need-Cash >= New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [                                                            ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  New-Credit-Available                                                ; the reduces the available-credit-assenza with each new loan because Current-Retail-Loan increases
          set Bank-Account-Firm            Bank-Account-Firm  +  New-Credit-Available                                                  ; updating the bank account with the money received
          set Need-Cash                    Need-Cash - New-Credit-Available
          set Available-Credit-Basel       Available-Credit-Basel - New-Credit-Available
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-C ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]

      ; the retail bank and the central bank have a constraint, but the later's is tighter
      if (Need-Cash > 0) and (Available-Credit-Basel <= Need-Cash) and (Need-Cash >= New-Credit-Available) and (Available-Credit-Basel < New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [          ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  Available-Credit-Basel                                              ; updating the loans parameter
          set Bank-Account-Firm            Bank-Account-Firm  +  Available-Credit-Basel                                                ; updating the bank account with the money received
          set Need-Cash                    Need-Cash - Available-Credit-Basel
          set Available-Credit-Basel       0
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-C ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]

      ; the retail bank and the central bank have a constraint, but the former's is tighter
      if (Need-Cash > 0) and (Available-Credit-Basel <= Need-Cash) and (Need-Cash >= New-Credit-Available) and (Available-Credit-Basel >= New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [        ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  New-Credit-Available                                                ; updating the loans parameter
          set Bank-Account-Firm            Bank-Account-Firm  +  New-Credit-Available                                                  ; updating the bank account with the money received
          set Need-Cash                    Need-Cash - New-Credit-Available
          set Available-Credit-Basel       Available-Credit-Basel - New-Credit-Available
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-C ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]
   ]

   if Risk-Calculations-Procedure = "Assenza" [
      ; how much money the bank may offer as a loan to a particular firm (not doable at an aggregate level), see footnote 32 in Assenza, Gatti, Grazzini et al. 2015
      set Max-Credit-to-Firm               max list 0  (Bank-loss-parameter * sum [Own-Bank-Capital] of Banks / Probability-of-Bankruptcy)
      ; how much money the bank may offer as a loan, see eq. 27 of Elder Silva's document
      ; let Available-Credit-Assenza         max list 0 (Bank-loss-parameter * (sum [Own-Bank-Capital] of Banks * B-Lev * ( Risk-spread ) - sum [Current-Retail-Loan] of Firms))
      ; how much money the bank may offer as a loan to a particular firm (not doable at an aggregate level), see eq. 8.11 in Assenza, Gatti, Grazzini et al. 2015
      set New-Credit-Available               max list 0  (Max-Credit-to-Firm - Current-Retail-Loan)

      ; no constraints
      if (Need-Cash > 0) and (Available-Credit-Basel > Need-Cash) and (Need-Cash < New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [                                                           ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  Need-Cash                                                           ; the reduces the available-credit-assenza with each new loan because Current-Retail-Loan increases
          set Bank-Account-Firm            Bank-Account-Firm  +  Need-Cash                                                             ; updating the bank account with the money received
          set Need-Cash                    0
          set Available-Credit-Basel       Available-Credit-Basel - Need-Cash
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-C ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]

      ; the central bank has a constraint
      if (Need-Cash > 0) and (Available-Credit-Basel <= Need-Cash) and (Need-Cash < New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [                                                           ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  Available-Credit-Basel                                              ; the reduces the available-credit-assenza with each new loan because Current-Retail-Loan increases
          set Bank-Account-Firm            Bank-Account-Firm  +  Available-Credit-Basel                                                ; updating the bank account with the money received
          set Need-Cash                    Need-Cash - Available-Credit-Basel
          set Available-Credit-Basel       0
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-C ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]

      ; the retail bank has a constraint
      if (Need-Cash > 0) and (Available-Credit-Basel > Need-Cash) and (Need-Cash >= New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [                                                            ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  New-Credit-Available                                                ; the reduces the available-credit-assenza with each new loan because Current-Retail-Loan increases
          set Bank-Account-Firm            Bank-Account-Firm  +  New-Credit-Available                                                  ; updating the bank account with the money received
          set Need-Cash                    Need-Cash - New-Credit-Available
          set Available-Credit-Basel       Available-Credit-Basel - New-Credit-Available
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-C ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]

      ; the retail bank and the central bank have a constraint, but the later's is tighter
      if (Need-Cash > 0) and (Available-Credit-Basel <= Need-Cash) and (Need-Cash >= New-Credit-Available) and (Available-Credit-Basel < New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [          ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  Available-Credit-Basel                                              ; updating the loans parameter
          set Bank-Account-Firm            Bank-Account-Firm  +  Available-Credit-Basel                                                ; updating the bank account with the money received
          set Need-Cash                    Need-Cash - Available-Credit-Basel
          set Available-Credit-Basel       0
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-C ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]

      ; the retail bank and the central bank have a constraint, but the former's is tighter
      if (Need-Cash > 0) and (Available-Credit-Basel <= Need-Cash) and (Need-Cash >= New-Credit-Available) and (Available-Credit-Basel >= New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [        ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  New-Credit-Available                                                ; updating the loans parameter
          set Bank-Account-Firm            Bank-Account-Firm  +  New-Credit-Available                                                  ; updating the bank account with the money received
          set Need-Cash                    Need-Cash - New-Credit-Available
          set Available-Credit-Basel       Available-Credit-Basel - New-Credit-Available
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-C ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]
   ]

   if Risk-Calculations-Procedure = "Teglio" [
      ; the formula for Probability-of-Bankruptcy comes from Teglio et al. (2012), eq. 1
      set New-Credit-Available             Need-Cash

      if (Need-Cash > 0) and (Available-Credit-Basel > Need-Cash) and (Cases-of-Bankruptcy < T-Ban) [                                  ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  Need-Cash                                                           ; the reduces the available-credit-assenza with each new loan because Current-Retail-Loan increases
          set Bank-Account-Firm            Bank-Account-Firm  +  Need-Cash                                                             ; updating the bank account with the money received
          set Need-Cash                    0
          set Available-Credit-Basel       Available-Credit-Basel - Need-Cash
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-C ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]

      if (Need-Cash > 0) and (Available-Credit-Basel <= Need-Cash) and (Cases-of-Bankruptcy < T-Ban) [                                 ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  Available-Credit-Basel                                              ; the reduces the available-credit-assenza with each new loan because Current-Retail-Loan increases
          set Bank-Account-Firm            Bank-Account-Firm  +  Available-Credit-Basel                                                ; updating the bank account with the money received
          set Need-Cash                    Available-Credit-Basel - Need-Cash
          set Available-Credit-Basel       0
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-C ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]
   ]

  ] [

    if Risk-Calculations-Procedure = "Original" [
      ; how much money the bank may offer as a loan, see eq. 27 of Elder Silva's document
      set New-Credit-Available             max list 0 (Bank-loss-parameter * (sum [Own-Bank-Capital] of Banks * B-Lev * ( Risk-spread ) - sum [Current-Retail-Loan] of Firms))

      ; no constraints
      if (Need-Cash > 0) and (Need-Cash < New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [                                                           ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  Need-Cash                                                           ; the reduces the available-credit-assenza with each new loan because Current-Retail-Loan increases
          set Bank-Account-Firm            Bank-Account-Firm  +  Need-Cash                                                             ; updating the bank account with the money received
          set Need-Cash                    0
          set Available-Credit-Basel       Available-Credit-Basel - Need-Cash
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-C ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]

      ; the retail bank has a constraint
      if (Need-Cash > 0) and (Need-Cash >= New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [                                                            ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  New-Credit-Available                                                ; the reduces the available-credit-assenza with each new loan because Current-Retail-Loan increases
          set Bank-Account-Firm            Bank-Account-Firm  +  New-Credit-Available                                                  ; updating the bank account with the money received
          set Need-Cash                    Need-Cash - New-Credit-Available
          set Available-Credit-Basel       Available-Credit-Basel - New-Credit-Available
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-C ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]
   ]

   if Risk-Calculations-Procedure = "Assenza" [
      ; how much money the bank may offer as a loan to a particular firm (not doable at an aggregate level), see footnote 32 in Assenza, Gatti, Grazzini et al. 2015
      set Max-Credit-to-Firm               max list 0  (Bank-loss-parameter * sum [Own-Bank-Capital] of Banks / Probability-of-Bankruptcy)
      ; how much money the bank may offer as a loan, see eq. 27 of Elder Silva's document
      ; let Available-Credit-Assenza         max list 0 (Bank-loss-parameter * (sum [Own-Bank-Capital] of Banks * B-Lev * ( Risk-spread ) - sum [Current-Retail-Loan] of Firms))
      ; how much money the bank may offer as a loan to a particular firm (not doable at an aggregate level), see eq. 8.11 in Assenza, Gatti, Grazzini et al. 2015
      set New-Credit-Available               max list 0  (Max-Credit-to-Firm - Current-Retail-Loan)

      ; no constraints
      if (Need-Cash > 0) and (Need-Cash < New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [                                                           ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  Need-Cash                                                           ; the reduces the available-credit-assenza with each new loan because Current-Retail-Loan increases
          set Bank-Account-Firm            Bank-Account-Firm  +  Need-Cash                                                             ; updating the bank account with the money received
          set Need-Cash                    0
          set Available-Credit-Basel       Available-Credit-Basel - Need-Cash
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-C ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]

      ; the retail bank has a constraint
      if (Need-Cash > 0) and (Need-Cash >= New-Credit-Available) and (Cases-of-Bankruptcy < T-Ban) [                                                            ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  New-Credit-Available                                                ; the reduces the available-credit-assenza with each new loan because Current-Retail-Loan increases
          set Bank-Account-Firm            Bank-Account-Firm  +  New-Credit-Available                                                  ; updating the bank account with the money received
          set Need-Cash                    Need-Cash - New-Credit-Available
          set Available-Credit-Basel       Available-Credit-Basel - New-Credit-Available
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-C ] [ set Interest-Retail  Taylor-Interest-Rate ]               ; call a subfunction to update the interest rate of this firm
      ]
   ]

   if Risk-Calculations-Procedure = "Teglio" [
      ; the formula for Probability-of-Bankruptcy comes from Teglio et al. (2012), eq. 1
      set New-Credit-Available             Need-Cash

      if (Need-Cash > 0) and (Cases-of-Bankruptcy < T-Ban) [                                                                           ; check if the need of a firm is lower then the available credit
          set Current-Retail-Loan          Current-Retail-Loan  +  Need-Cash                                                           ; the reduces the available-credit-assenza with each new loan because Current-Retail-Loan increases
          set Bank-Account-Firm            Bank-Account-Firm  +  Need-Cash                                                             ; updating the bank account with the money received
          set Need-Cash                    0
          set Available-Credit-Basel       Available-Credit-Basel - Need-Cash
          ifelse Retail-Interest? and ticks > 100        [ SubF-Update-Interest-Retail-C ] [ set Interest-Retail  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

   if Risk-Calculations-Procedure = "Original" [
   ; the formula for Probability-of-Bankruptcy comes from Assenza et al. (2015), p. 15
      set Probability-of-Bankruptcy           (1 / (1 + e ^ ( (- Beta_1-C-Firms) - (Beta_2-C-Firms * leverage))))                                 ; local variable, save the prob of this firm die
      set T-expected                          (1 / Probability-of-Bankruptcy)                                                                     ; calculate the life expectation of this firm (eq 24)
      let Numerator                           (1 + (Taylor-Interest-Rate / Installment-on-Debt))                                                  ; local auxiliar variable, first part to calculate the new interest rate
      let Denominator                        ((1 - (1 - Installment-on-Debt) ^ (T-expected + 1)) / Installment-on-Debt)                           ; // // second part of the new interest rate
      let new-int                              Bank-gross-mark-up * ((numerator / denominator) - Installment-on-Debt)                             ; calculating the new interest rate (eq 26 or 8.8 in Assenza et al. 2015)
      ifelse Current-Retail-Loan > 0 [
             set Interest-Retail               max list 0 ((Interest-Retail * (Current-Retail-Loan - Need-Cash) + new-int * Need-Cash) / Current-Retail-Loan)   ; update the interest rate as mean of the new and the later interest rate
      ] [
             set Interest-Retail               Taylor-interest-rate
      ]
   ]

   if Risk-Calculations-Procedure = "Assenza" [
   ; the formula for Probability-of-Bankruptcy comes from Assenza et al. (2015), p. 15
      set Probability-of-Bankruptcy           (1 / (1 + e ^ ( (- Beta_1-C-Firms) - (Beta_2-C-Firms * leverage))))                                 ; local variable, save the prob of this firm die
      set T-expected                          (1 / Probability-of-Bankruptcy)                                                                     ; calculate the life expectation of this firm (eq 24)
      let Numerator                           (1 + (Taylor-Interest-Rate / Installment-on-Debt))                                                  ; local auxiliar variable, first part to calculate the new interest rate
      let Denominator                        ((1 - (1 - Installment-on-Debt) ^ (T-expected + 1)) / Installment-on-Debt)                           ; // // second part of the new interest rate
      let new-int                              Bank-gross-mark-up * ((numerator / denominator) - Installment-on-Debt)                             ; calculating the new interest rate (eq 26 or 8.8 in Assenza et al. 2015)
      ifelse Current-Retail-Loan > 0 [
             set Interest-Retail               max list 0 ((Interest-Retail * (Current-Retail-Loan - Need-Cash) + new-int * Need-Cash) / Current-Retail-Loan)   ; update the interest rate as mean of the new and the later interest rate
      ] [
             set Interest-Retail               Taylor-interest-rate
      ]
   ]

   if Risk-Calculations-Procedure = "Teglio" [
   ; the formula for Probability-of-Bankruptcy comes from Teglio et al. (2012), eq. 1
   ; the original formula is Probability-of-Bankruptcy = 1 - (1 / e ^ ((current-retail-loan + need-cash)/ equity)) but the exponent is related to leverage, and it is more consistent to use this
   ; if we do Probability-of-Bankruptcy = 1 - (1 / e ^ (leverage), when leverage = 1 we have Probability-of-Bankruptcy 0.63, too low... so we modify the formula assuring leverage = 1 implies Probability = 1
      ifelse ticks > 50 [
         set Probability-of-Bankruptcy         1 - (1 / e ^ (0.0001 + 5 * leverage))
      ] [
         set Probability-of-Bankruptcy         0.0001
      ]
      set T-expected                          (1 / Probability-of-Bankruptcy)                                                                      ; calculate the life expectation of this firm (eq 24)
   ; the formula for Probability-of-Bankruptcy comes from Teglio et al. (2012), eq. 2
   set Interest-Retail                         max list 0 (taylor-interest-rate + risk-spread * leverage * Probability-of-Bankruptcy)              ; the leverage is a risk spread parameter here, approaching 1 as current retail loans get larger
   ]
end 

to SubF-Update-Interest-Retail-K                                                                                                                   ; update the interest rate of a K-firm

   if Risk-Calculations-Procedure = "Original" [
   ; the formula for Probability-of-Bankruptcy comes from Assenza et al. (2015), p. 15
      set Probability-of-Bankruptcy           (1 / (1 + e ^ ( (- Beta_1-K-Firms) - (Beta_2-K-Firms * leverage))))                                  ; the same as the C-firm, check above for details
      set T-expected                          (1 / Probability-of-Bankruptcy)                                                                      ; calculate the life expectation of this firm (eq 24)
      let Numerator                           (1 + (Taylor-Interest-Rate / Installment-on-Debt))
      let Denominator                        ((1 - (1 - Installment-on-Debt) ^ (T-expected + 1)) / Installment-on-Debt)
      let new-int                              Bank-gross-mark-up * ((numerator / denominator) - Installment-on-Debt)                              ; calculating the new interest rate (eq 26 or 8.9 in Assenza et al. 2015)
      ifelse Current-Retail-Loan > 0 [
             set Interest-Retail               max list 0 ((Interest-Retail * (Current-Retail-Loan - Need-Cash) + new-int * Need-Cash) / Current-Retail-Loan)    ; update the interest rate as mean of the new and the later interest rate
      ] [
             set Interest-Retail               Taylor-interest-rate
      ]
   ]

   if Risk-Calculations-Procedure = "Assenza" [
   ; the formula for Probability-of-Bankruptcy comes from Assenza et al. (2015), p. 15
      set Probability-of-Bankruptcy           (1 / (1 + e ^ ( (- Beta_1-K-Firms) - (Beta_2-K-Firms * leverage))))                                  ; the same as the C-firm, check above for details
      set T-expected                          (1 / Probability-of-Bankruptcy)                                                                      ; calculate the life expectation of this firm (eq 24)
      let Numerator                           (1 + (Taylor-Interest-Rate / Installment-on-Debt))
      let Denominator                        ((1 - (1 - Installment-on-Debt) ^ (T-expected + 1)) / Installment-on-Debt)
      let new-int                              Bank-gross-mark-up * ((numerator / denominator) - Installment-on-Debt)                              ; calculating the new interest rate (eq 26 or 8.9 in Assenza et al. 2015)
      ifelse Current-Retail-Loan > 0 [
             set Interest-Retail               max list 0 ((Interest-Retail * (Current-Retail-Loan - Need-Cash) + new-int * Need-Cash) / Current-Retail-Loan)   ; update the interest rate as mean of the new and the later interest rate
      ] [
             set Interest-Retail               Taylor-interest-rate
      ]
   ]

   if Risk-Calculations-Procedure = "Teglio" [
   ; the formula for Probability-of-Bankruptcy comes from Teglio et al. (2012), eq. 1
   ; the original formula is Probability-of-Bankruptcy = 1 - (1 / e ^ ((current-retail-loan + need-cash)/ equity)) but the exponent is related to leverage, and it is more consistent to use this
   ; if we do Probability-of-Bankruptcy = 1 - (1 / e ^ (leverage), when leverage = 1 we have Probability-of-Bankruptcy 0.63, too low... so we modify the formula assuring leverage = 1 implies Probability = 1
      ifelse ticks > 50 [
         set Probability-of-Bankruptcy         1 - (1 / e ^ (0.0001 + 5 * leverage))
      ] [
         set Probability-of-Bankruptcy         0.0001
      ]
      set T-expected                          (1 / Probability-of-Bankruptcy)                                                                      ; calculate the life expectation of this firm (eq 24)
   ; the formula for Probability-of-Bankruptcy comes from Teglio et al. (2012), eq. 2
   set Interest-Retail                         max list 0 (taylor-interest-rate + risk-spread * leverage * Probability-of-Bankruptcy)              ; the leverage is a risk spread parameter here, approaching 1 as current retail loans get larger
   ]
end 

to SubF-Go-Bankruptcy-Type-C                                                                      ; this subfunction rules the process for the C-firm bankruptcy
  set C-Broken                                   C-Broken + 1                                     ; increase the global parameter which count the broke status
  set Cases-of-Bankruptcy                        0                                                ; reset the parameter that registers the cases of bankruptcy
  let Loss                                       Current-Retail-Loan                              ; local variable
  ask Banks [
      set Own-Bank-Capital                       Own-Bank-Capital - Loss                          ; the bank assumes the loss
  ]
  ifelse Capitalist-Bankruptcy? and random-float 1 > (1 / (1 + 0.01 * ticks)) [
         let newfunding                             Initial-Liquidity-of-Firms
         ask one-of my-out-owners [                                                               ; find out who is the owner of this firm
             ask other-end [                                                                      ; the owner
                 ifelse Bank-Account-Household >= newfunding [
                    set Bank-Account-Household      Bank-Account-Household - newfunding           ; update the bank account of the capitalist, retrieving the money invested to recreate the firm (bakrupcy != die)
                 ] [
                    set Bank-Account-Household      0
                    let C-Firms-damnation%          1 / (1 + Recession-lenght * 0.25)             ; local variable, a probability depending on the recession lenght
                    if random-float 1 > C-Firms-damnation% [                                      ; the longer the recession, the more firms will die
                       set color                       yellow
                       set Bankrupt?                   true
                       SubF-Firm-Capitalist-Damnation                                             ; the capitalist and the firm start a painful process of extintion
                    ]
                ]
             ]
        ]
  ] [                                                                                             ; in this alternative procedure the capitalist does not go bankrupt and become a worker and the firm does not die
         let newfunding                         Initial-Liquidity-of-Firms
         ask one-of my-out-owners [                                                               ; use the capitalist to rebuild the firm
             ask other-end [                                                                      ; find out who is the owner of this firm
                 set Bank-Account-Household     max list 0 (Bank-Account-Household - newfunding)  ; update the bank account of the capitalist, retrieving the money invested to recreate the firm (bakrupcy != die)
             ]
         ]
         set Current-Retail-Loan                0                                                 ; reset the loan of the firm after the bankruptcy... this is a loss for the retail bank
         if Capital-Destruction?               [ set Capital    Initial-Capital ]                 ; reset the capital of the c-firm
         set Bank-Account-Firm                  newfunding                                        ; iniciate the firm with the money from the capitalist whom owns the firm
  ]
end 

to SubF-Go-Bankruptcy-Type-K                                                    ; this subfunction rules the process for how a K-Firm broke
   set K-Broken                                  K-Broken  + 1                  ; increase the global parameter which count of broke status
   set Cases-of-Bankruptcy                       0                              ; reset this parameter, a probability calculated by retail banks
   let Loss                                      Current-Retail-Loan            ; local variable
   ask Banks [
       set Own-Bank-Capital                      Own-Bank-Capital - Loss        ; the bank assumes the loss
   ]
   ifelse Capitalist-Bankruptcy? and random-float 1 > (1 / (1 + 0.01 * ticks)) [
         let newfunding                             Initial-Liquidity-of-Firms
         ask one-of my-out-owners [                                                                   ; find out who is the owner of this firm
             ask other-end [                                                                          ; the owner
                 ifelse Bank-Account-Household >= newfunding [
                    set Bank-Account-Household      Bank-Account-Household - newfunding               ; update the bank account of the capitalist, retrieving the money invested to recreate the firm (bakrupcy != die)
                 ] [
                    set Bank-Account-Household      0
                    let K-Firms-damnation%          1 / (1 + Recession-lenght * 0.25)                 ; local variable, a probability depending on the recession lenght
                    if random-float 1 > K-Firms-damnation% [                                          ; the longer the recession, the more firms will die
                       set color                       yellow
                       set Bankrupt?                   true
                       SubF-Firm-Capitalist-Damnation                                                 ; the capitalist and the firm start a painful process of extintion
                    ]
                ]
            ]
       ]
   ] [                                                                                                ; in this alternative procedure the capitalist do not go bankrupt and become a worker
         let newfunding                          Initial-Liquidity-of-Firms
         ask one-of my-out-owners [                                                                   ; use the capitalist to rebuild the firm
             ask other-end [                                                                          ; find out who is the owner of this firm
                 set Bank-Account-Household      max list 0 (Bank-Account-Household - newfunding)     ; update the bank account of the capitalist, retrieving the money invested to recreate the firm (bakrupcy != die)
             ]
         ]
         set Current-Retail-Loan                 0                                                    ; reset the loan of the firm after the bankruptcy
         set Bank-Account-Firm                   newfunding                                           ; iniciate the firm with the money from the capitalist whom owns the firm
   ]
end 

to SubF-Firm-Capitalist-Damnation
   ask Capitalists with [Bankrupt? = true] [
       set Current-Income               0                                     ; update the current income of the capitalist/owner
       let moneyfornewlife              Initial-households-personal-assets    ; the demoted capitalists get some aid for starting a new life as worker...
       set Bank-Account-Household       moneyfornewlife                       ; update the bank account of the capitalist/owner
       if Do_We_Have_State? [
          set State-Budget              State-Budget - moneyfornewlife        ; sorry Libertarians, but the State comes to help...
          set Helped-Households         Helped-Households + 1
       ]
       set Worker?                      true                                  ; the capitalist becomes a worker... life is unfair
       set Bankrupt?                    false
       set Employed?                    false                                 ; this worker is unemployed at the start
       set Demoted                      Demoted + 1
       set color                        turquoise                             ; now you are a worker and look like one... almost
       set size                         0.50
       set Human-Wealth                 1
       set Desired-Consumption          0
       set Consumption                  0
       set Price-List                  [ ]
       ask in-owner-neighbors         [ die ]                                 ; and the former firm he/she owned finally vanishes
   ]                                                                          ; end procedure previous to bankruptcy
   set C-Firms                          Firms with      [ C-Firm?      ]      ; updating the group with all C-Firms
   set K-Firms                          Firms with      [ not C-Firm?  ]      ; updating the group with all K-firms
   set Capitalists                      Households with [ not Worker?  ]      ; updating the group with all Capitalist
   set Workers                          Households with [     Worker?  ]      ; updating the group with all workers
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 Reserves / Total-Accounts_1 < Reserve-Requirement [
      let Needed-Liquidity                            max list 0 (Total-Accounts_1 * Reserve-Requirement - Reserves)  ; this is an innecesary precaution, given the condition but...
      set Central-Bank-Loans                          Central-Bank-Loans + Needed-Liquidity
   ]
end 

to SubF-Distribute-Dividends                                                                              ; function for the calculation and distribution of dividends by banks
   ifelse Do_We_Have_Central-Bank? [
          set EBIT                                    max list 0 (Interests-Received - Central-Bank-Loans * taylor-interest-rate)               ; the profit income minus expenditures
   ] [
          set EBIT                                    max list 0 (Interests-Received)                     ; the profit income minus expenditures
   ]
   let div                                            0
   ifelse Dividend-Payments-of-Banks? [                                                                   ; HUD control for activating dividends payments by means of a sophisticated procedure...
       if EBIT >= 0 [                                                                                     ; if the profit is positive, the firm pay dividends and taxes
           ifelse Do_We_Have_State? [
                  set Profit                          EBIT * (1 - Corporate-Tax)                          ; this profit is net of taxes
                  set State-Budget                    State-Budget + Corporate-Tax * EBIT                 ; the taxes go to the government
                  set Own-Bank-Capital                Own-Bank-Capital - Corporate-Tax * EBIT             ; the bank pays the taxes
           ] [
                  set Profit                          EBIT                                                ; this profit is net of taxes
           ]
           set Dividend                               dividend-payout-ratio-banks * Profit                ; if there was a positive profit, setup dividend, the income of capitalists
           let Number-of-Capitalists                  count C-Firms + count K-Firms                       ; total number of Capitalists
           ifelse Own-Bank-Capital >= Dividend [
                  set Own-Bank-Capital                Own-Bank-Capital - Dividend                         ; reduce the bank account by the dividend which will be paid to the capitalists
                  set Div                             Dividend / Number-of-Capitalists                    ; calculate dividend as part of the total profit divided by capitalists (everyone have a share)
           ] [
                  set Div                             Own-Bank-Capital / Number-of-Capitalists            ; calculate dividend as part of the total profit divided by capitalists (everyone have a share)
                  set Own-Bank-Capital                0                                                   ; there is no devidend payments if the capital of the bank falls below zero
           ]

           ask Capitalists [                                                                              ; call each of one of the capitalist
               ifelse Do_We_Have_State? [
                      set Current-Income              Current-Income + div * (1 - Income-Tax)             ; increase the income of the capitalist with this new dividend
                      set Bank-Account-Household      Bank-Account-Household + div * (1 - Income-Tax)     ; update the bank account of the capitalist with the dividend net of taxes
                      set State-Budget                State-Budget + Income-Tax * div                     ; the State gets the income taxes
               ] [
                      set Current-Income              Current-Income + div                                ; increase the income of the capitalist with this dividend
                      set Bank-Account-Household      Bank-Account-Household + div                        ; update the bank account of the capitalist
               ]
           ]
       ]

       ; if the profit is negative (losses) there is nothing to distribute... but we may have different problems, like own bank capital falling bellow the minimum level
       if Own-Bank-Capital >= 0 and Own-Bank-Capital < Initial-capital-of-the-bank [                                        ; if the losses are larger than the Own-Bank-Capital
          ifelse Do_We_Have_Central-Bank? [
                 let Need-Capital                    max list 0 (Initial-capital-of-the-bank - Own-Bank-Capital)
                 set Central-Bank-loans              Central-Bank-loans + Need-Capital                             ; the Own-Bank-Capital needs a suplement
                 set Own-Bank-Capital                Own-Bank-Capital +  Need-Capital
          ] [
                 SubF-Bail-in-Banks
          ]
       ]

       if Own-Bank-Capital < 0 [                                                                          ; the bank has liquidity for compensating the loss
          ifelse Do_We_Have_Central-Bank? [
                 let Need-Capital                    max list 0 (abs Own-Bank-Capital)
                 set Central-Bank-loans              Central-Bank-loans + Need-Capital                  ; the Own-Bank-Capital needs a suplement
                 set Own-Bank-Capital                Own-Bank-Capital +  Need-Capital
                 SubF-Bail-in-Banks
          ] [
                 if Do_We_Have_State? and State-Budget >= abs Own-Bank-Capital [
                    set State-Budget                 State-Budget - abs Own-Bank-Capital
                    set Own-Bank-Capital             0
                 ]
                 set Own-Bank-Capital                0
                 SubF-Bail-in-Banks
          ]
      ]

    ] [                                                                                         ; alternative (simpler) procedure, without any complication related to bankruptcy processes

    if EBIT >= 0 [
    let Number-of-Capitalists        count C-Firms + count K-Firms
    ifelse Do_We_Have_State? [
           set Profit                EBIT * (1 - Corporate-Tax)                                 ; this profit is net of taxes
           set State-Budget          State-Budget + Corporate-Tax * EBIT                        ; the taxes go to the government
    ] [
           set Profit                EBIT                                                       ; this profit is net of taxes
    ]
    set Dividend                     dividend-payout-ratio-banks * Profit
    ifelse Own-Bank-Capital >= Dividend [
           set Div                   Profit  / Number-of-Capitalists                            ; calculate dividend as part of the total profit divided by capitalists
           set Own-Bank-Capital      Own-Bank-Capital - Dividend
    ] [
           set Div                   Own-Bank-Capital / Number-of-Capitalists
           set Own-Bank-Capital      0
    ]
    ask Capitalists [                                                                           ; call each of one of the capitalist
        ifelse Do_We_Have_State? [
               set Current-Income           Current-Income + div * (1 - Income-Tax)             ; update the Current income
               set Bank-Account-Household   Bank-Account-Household  +  div * (1 - Income-Tax)   ; update the bank account of the household
               set State-Budget             State-Budget + Income-tax * div                     ; the taxes go to the government
         ] [
               set Current-Income           Current-Income + div                                ; increase the income of the capitalist
               set Bank-Account-Household   Bank-Account-Household + div                        ; update the bank account of the capitalist
         ]
    ]
    ]
    ]
end 

to SubF-Bail-in-Banks                                                                                         ; this subfunction rules the process for the Bank bankruptcy and rebuilding using capitalits' resources. We ask banks here.
   set B-Broken                              B-Broken + 1                                                     ; increase the global parameter that counts the broke status
   let Original-Shares                       Initial-Capital-of-the-bank / (count C-Firms + count 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
   ifelse count Bank-Owners = 0 [                                                                             ; special procedure... if the owners cannot save the bank, the State will save the situation
          SubF-Bail-out-Banks
   ] [
   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-Capital-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
         ifelse  count Bank-Owners = 0 [                                                                      ; special procedure... if the owners cannot save the bank, the State will save the situation
                 SubF-Bail-out-Banks
                 stop
         ] [
                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
         ]
   ]
   if count Bank-Owners != 0 [
      set Bail-ins                           Bail-ins + 1
      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
      ]
   ]
   ifelse Capitalist-Bankruptcy? and ticks > 100 [
          ask Broken-Capitalists [                                                                            ; the capitalists unable to pay for the bail-in will be broken
              set Demoted                          Demoted + 1
              let moneyfornewlife                  max list 0 (random-normal Initial-households-personal-assets 0.5)
              set Bank-Account-Household           moneyfornewlife                                            ; the capitalist unable to pay for the new shares get broken
              if Do_We_Have_State? [
                 set State-Budget                  State-Budget - moneyfornewlife                             ; sorry Libertarians, but the State comes to help...
                 set Helped-Households             Helped-Households + 1
              ]
              set Worker?                          true                                                       ; the capitalist is broken, and he/she becomes a poor worker
              set Employed?                        false                                                      ; the ex-capitalist is now an unemployed worker and he has to look for an employment... life is hard...
              set Bankrupt?                        false
              set color                            turquoise                                                  ; 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 Desired-Consumption              0                                                          ; initial value for desired consumption
              set Consumption                      0                                                          ; initial value for Consumption
              set Price-List                      [ ]                                                         ; setup for the list which will be used to colect the C-Firms visited
              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                        one-of Workers with-max [ Bank-Account-Household ]         ; ...the orphan C-Firm or K-Firm needs a 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
              if Employed? [
                 ask in-hired-neighbors [                                                                     ; we contact with the firm for which this worker is employed... the only link of this worker, future capitalist, is the labor contract
                     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
                     ask one-of my-out-hireds     [ die ]                                                     ; the link, the labor contract, dies or disappear
                 ]
              ]
          set shape                                "person"                                                   ; the metamorphosis of this person is complete now... and he comes to a new (better) life...
          set size                                  0.50                                                      ; just for fun, not necessary for the model, used only for display in HUD Netlogo
          set color                                 gray                                                      ; this "new rich" is like a rich (white) but not quite
          set Worker?                               false                                                     ; false only means he/she is now a happy capitalist
          set Employed?                             false
          set Promoted                              Promoted + 1
          let My-New-Firm                           one-of Firms with [Owner? = false]
          move-to                                   My-New-Firm
          create-owner-from                         My-New-Firm [set hidden? true]                            ; this creates a link between the firm and the capitalist
          ask My-New-Firm                         [ set Owner? true ]
          ]
          set Capitalists                           Households with [ not Worker?  ]                          ; updating the group with all Capitalist
          set Workers                               Households with [     Worker?  ]                          ; updating the group with all workers
   ] [
          ask Broken-Capitalists [
              let moneyfornewlife                   max list 0 (random-normal Initial-households-personal-assets 0.5)
              set Bank-Account-Household            moneyfornewlife                                           ; the capitalist unable to pay for the new shares get broken
              if Do_We_Have_State? [
                 set State-Budget                   State-Budget - moneyfornewlife                            ; sorry Libertarians, but the State comes to help...
                 set Helped-Households              Helped-Households + 1
              ]
              set Human-Wealth                      1                                                         ; initial value for Human Wealth, utilized to calculate the consumption process
              set Current-Income                    0                                                         ; intitial income
              set Desired-Consumption               0                                                         ; initial value for desired consumption
              set Consumption                       0                                                         ; initial value for Consumption
              set Price-List                       [ ]                                                        ; setup for the list which will be used to colect the C-Firms visited
          ]
  ]
]
end 

to SubF-Bail-out-Banks
   if Do_We_Have_State? [                                                                                        ; untenable losses... if there exist a government and taxes... (we are asking banks)
      set Bail-outs                           Bail-outs + 1
      if State-Budget >= Initial-Capital-of-the-bank [                                                           ; 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-Capital-of-the-bank                         ; in this case the government pays the recapitalization of the bank and the unpaid overdraft
         set Own-Bank-Capital                 Initial-Capital-of-the-bank
      ]
      if State-Budget < Initial-Capital-of-the-bank and Do_We_Have_Central-Bank? = true and QEasing? = true [    ; 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-Capital-of-the-bank                         ; in this case the government pays the recapitalization of the bank and the unpaid overdraft
         set Own-Bank-Capital                 Initial-Capital-of-the-bank
      ]
   ]
end 

to Function-Update-Wages                                                                               ; trade unions try to keep purchasing power of salaries or rate of salaries on GDP constant, but they loss power if Unemployment-Rate increases
   set Wage_1              Wage                                                                        ; store the Wage value for use with adaptative functions
   set Labor-Share_1      (Employment_1 * Wage_1) / (GDP_1 * General-Price-Level_1)                    ; store the labor share on income (Labor-Share) value for use with adaptative functions
   set Labor-Share        (Employment * Wage) / (GDP * General-Price-Level)                            ; total salaries as a percentage of the GDP, then Wage = (Labor-Share * GDP) / Number-of-Employees is the wage that keeps that proportion constant
   ifelse Update-Wages?  [
          ifelse Unemployment-Rate <= 0.12 [                                                           ; if the Unemployment-Rate rate approaches the frictional Unemployment-Rate rate (of about 7%), then trade unions get stronger and wages rise
                 if labor-share < 0.55 [
                    set Wage         max list minimum-wage (max list (Labor-Share_1 * (GDP_1 * (General-Price-Level_1)) / Employment) (Wage * (1 + cpi)))          ; the previous wage increased by the Consumption price index
                 ]
                 if labor-share > 0.75 [
                    set Wage         max list minimum-wage (min list (Labor-Share_1 * (GDP_1 * (General-Price-Level_1)) / Employment) (Wage * (1 + cpi)))          ; the previous wage increased by the Consumption price index
                 ]
          ] [                                                                                          ; the second option for wage comes from finding the value of wage in (Labor-Share_1 = Labor-Share)
                 ifelse labor-share <= 0.40 [
                        set Wage         max list wage minimum-wage                                    ; even if unemplyment is high, when the rate of salaries on GDP falls bellow this threshold trade unions fight for preserving the current level of wages or set a minimum for them
                 ] [
                        set Wage         minimum-wage                                                  ; if the Unemployment-Rate rate is higher than the frictional Unemployment-Rate rate plus a margin and the labor share is not too low, the wages cannot be lower than a legal minimum
                 ]
          ]
   ] [

                 set Wage         minimum-wage
   ]
end 

to Function-New-Firms-Entries                                                                          ; if bakruptcy of firms occurs, a procedure for regenerating firms is activated
   if count C-Firms < 200 [                                                                            ; if the number of C-Firms is lower than the maximun, there is room for newcomers
      let C-Firms-newcomers%                     1 / (1.33 + Recession-lenght * 0.66)                  ; local variable, a probability depending on the recession lenght
      if random-float 1 < C-Firms-newcomers% [                                                         ; with a probability that depends on the GDP growth, new C-Firms appear in the economy
      ask one-of patches with [pycor < 8 and not any? Firms-here] [
         sprout-firms 1 [
                 set shape                      "factory"                                                  ; just for fun, not necessary for the model, used only for display in HUD netlogo
                 set size                        0.75                                                      ; 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                       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 Probability-of-Bankruptcy   0.001
                 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 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 Desired-Employees           0                                                         ; initial value for desire employees
                 set Price-List                 [ ]                                                        ; setup for the list which will be used to colect the K-Firms visited
                 set Vacancy                     0                                                         ; initial value for vacancy
                 set Current-Retail-Loan         0                                                         ; the new firm is born like a virgin...
                 set Bank-Account-Firm           max list 0 (random-normal Initial-liquidity-of-Firms 1)   ; initial money deposited at the bank by the firms
                 set Bank-Account-Firm_1         Bank-Account-Firm
                 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
         ]                                                                                                 ; end new firm commands
      ]                                                                                                    ; end if random 100
      set C-Firms                                Firms with [ C-Firm? ]                                    ; updating the group with all K-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
          if Employed? [
             ask in-hired-neighbors [                                                                      ; the new capitalist is a worker yet and we take its labor contract and...
                 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
                 ask one-of my-out-hireds       [ die ]
             ]
          ]
          set color                              gray                                                      ; the color changes, because this capitalist is a new rich
          set Worker?                            false                                                     ; he/she is now a capitalist
          set Promoted                           Promoted + 1
          let My-New-Firm                        one-of Firms with [Owner? = false]
          move-to                                My-New-Firm
          create-owner-from                      My-New-Firm [set hidden? true]                            ; this creates a link between the firm and the capitalist
          ask My-New-Firm                      [ set Owner? true ]
      ]
      set Capitalists                            Households with [ not Worker?  ]                          ; updating the group with all Capitalist
      set Workers                                Households with [     Worker?  ]                          ; updating the group with all workers
   ]                                                                                                       ; end condition about room for new firms
  ]

                                                                                                           ; if bakruptcy of firms occurs, a procedure for regenerating firms is activated

   if count K-Firms < 50 [                                                                                 ; if the number of C-Firms is lower than the maximun, there is room for newcomers
      let K-Firms-newcomers%                        1 / (1.2 + Recession-lenght * 0.85)                    ; local variable, a probability
      if random-float 1 < K-Firms-newcomers% [                                                             ; with a probability that depends on the GDP growth, new C-Firms appear in the economy
         ask one-of patches with [pycor >= 8 and not any? Firms-here] [
             sprout-firms 1 [
                 set shape                      "factory"                                                  ; just for fun, not necessary for the model, used only for display in HUD netlogo
                 set size                        0.75                                                      ; just for fun, not necessary for the model, used only for display in HUD netlogo
                 set color                       brown                                                     ; 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                       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 Probability-of-Bankruptcy   0.001
                 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 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 Desired-Employees           0                                                         ; initial value for desire employees
                 set Price-List                 [ ]                                                        ; setup for the list which will be used to colect the K-Firms visited
                 set Vacancy                     0                                                         ; initial value for vacancy
                 set Current-Retail-Loan         0                                                         ; the new firm is born like a virgin...
                 set Bank-Account-Firm           max list 0 (random-normal Initial-liquidity-of-Firms 1)   ; initial money deposited at the bank by the firms
                 set Bank-Account-Firm_1         Bank-Account-Firm
                 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
             ]                                                                                             ; end new firm commands
         ]
      set K-Firms                                Firms with [ not C-Firm? ]                                ; updating the group with all K-firms
      let Newcapitalist-K                        one-of 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
          if Employed? [
           ask in-hired-neighbors [                                                                        ; the new capitalist is a worker yet and we take its labor contract and...
                   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
                   ask one-of my-out-hireds       [ die ]
               ]

           ]
           set color                                 gray                                              ; the color changes, because this capitalist is a new rich
           set Worker?                               false                                             ; he/she is now a capitalist
           set Employed?                             false
           set Promoted                              Promoted + 1
           let My-New-Firm                           one-of Firms with [Owner? = false]
           move-to                                   My-New-Firm
           create-owner-from                         My-New-Firm [set hidden? true]                    ; this creates a link between the firm and the capitalist
           ask My-New-Firm                         [ set Owner? true ]
      ]
      set Capitalists                    Households with [ not Worker?  ]                              ; updating the group with all Capitalist
      set Workers                        Households with [     Worker?  ]                              ; updating the group with all workers
      ]
  ]                                                                                                    ; end condition about room for new firms
end 



             ; FUNCTION-CALL-CENTRAL-BANK

to Function-Call-Central-Bank
   if ticks > 10 [
      SubF-Set-Interest-Rates
   ]
   SubF-Update-Monetary-Variables
end 

to SubF-Set-Interest-Rates
   ; only consumption goods are final goods, because capital goods are intermediate
   let P_C                             min list (Productivity-of-capital * sum [Capital] of C-Firms) (Productivity-of-labor * sum [Number-of-Employees] of C-Firms)  ; maximum potential production of consumption goods
   let P_K                             Productivity-of-labor * sum [Number-of-Employees] of K-Firms                      ; maximum potential production of capital goods
   set P_GDP                          (P_C * Goods-Price-Level + P_K * Capital-Price-Level) / (General-Price-Level)                                                                                                                                                                             ; 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 * (gpi - desired-inflation)                   ; Taylor-rule-parameter-for-inflation & Desire-inflation-for-the-monetary-authority

   let sensity_product                 0
   if GDP != 0 and P_GDP != 0 [
      set sensity_product              Taylor-rule-parameter-for-product  * (ln GDP - ln P_GDP)                          ; Taylor-rule-parameter-for-product
   ]

   let sensity_credit                  0
   if (sum [Total-Loans] of Banks > 0) and (sum [Total-Loans_1] of Banks > 0) [
      set sensity_credit               max list 0 (Taylor-rule-parameter-for-credit * (ln sum [Total-Loans] of Banks - ln sum [Total-Loans_1] of Banks))     ; the parameter for the credit component of the Taylor rule
   ]

   if taylor-rule = "none" [
      set taylor-interest-rate         natural-interest-rate
   ]
   if taylor-rule = "conservative" [
      set taylor-interest-rate         max list 0.01 ( (Slow_taylor) * (gpi + natural-interest-rate + sensity_inflation)  + (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 ( (Slow_taylor) * (gpi + natural-interest-rate + sensity_inflation + sensity_product) + (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 ( (Slow_taylor) * (gpi + natural-interest-rate + sensity_inflation + sensity_product + sensity_credit) + (1 - slow_taylor) * taylor-interest-rate )  ; three-mandate Taylor rule: inflation, output gap and credit (eq 20 of Popoyan et al)
   ]
end 

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

   ; First, we prepare the global variables needed below

   let Credit-on-GDP                           sum [Total-Loans] of Banks / GDP                   ; this is the basic ratio used in the Counter-Cyclical-Capital-Buffer defined in Basel III rules
   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
                                                                                                  ; the Time-Winodw is set to 60 because this is the size used by Popoyana et al. in footnote 14

   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
   let 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
       ; Basel II
       set Available-Credit-Basel2              max list 0 (Own-Bank-Capital * 12.5 - Total-Loans)                     ; 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 / (Total-Loans + Available-Credit-Basel2)           ; Basel II sets this ratio as 8% as a minimum

       ; Basel III-1
       let Available-Credit-Basel31a            max list 0 (Own-Bank-Capital * 22.2 - Total-Loans)                     ; 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 / (Total-Loans + Available-Credit-Basel31a)         ; Basel III 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 Available-Credit-Basel31b         ""                                                                     ; no specific limits here... so Total-Accounts * (1 / Reserve-Requirement) would be the limit
          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        (Total-Accounts + Own-Bank-Capital + Central-Bank-Loans - Reserves - Total-Loans - Total-Loans * Capital-Buffer) / (1 + Capital-Buffer)                       ; Deposits-Total includes Own-Bank-Capital
          set Buffer-Add-On                     Capital-Buffer * (Total-Accounts + 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 ((Total-Accounts + Own-Bank-Capital + Central-Bank-Loans - Reserves - Total-Loans - Total-Loans * Capital-Buffer) / (1 + Capital-Buffer)))       ; Deposits-Total includes Own-Bank-Capital
          set Buffer-Add-On                     Capital-Buffer * (Total-Loans + 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


    if Assets > 0   [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)

       ; Basel III-2
       let High-Quality-Liquid-Assets         (Reserves + Own-Bank-Capital) * 1.75
       set Available-Credit-Basel32           max list 0 ((High-Quality-Liquid-Assets - (taylor-interest-rate + Installment-on-Debt) * Central-Bank-Loans - 0.1 * Total-Accounts - 0.25 * Central-Bank-Loans + Interests-Received + Installments-Received - 0.5 * Total-Loans) * 2)
       let Expected-Net-Cash-Outflows         (taylor-interest-rate + Installment-on-Debt) * Central-Bank-Loans + 0.1 * Total-Accounts + 0.25 * Central-Bank-Loans - Interests-Received - Installments-Received + 0.5 * (Total-Loans + Available-Credit-Basel32)
       let Liquidity-Coverage-Ratio            High-Quality-Liquid-Assets / Expected-Net-Cash-Outflows                 ; Liquidity-Coverage-Ratio >= 1

       ; setting the macroprudential rule at work

       if Macroprudential-Rules = "none" [                                                                             ; we have created a chooser called "macroprudential-rules" with several possibilities: none, basel2, basel31, basel32, basel312
          set Available-Credit-Basel               Total-Accounts / Reserve-Requirement                                ; none means there is no aggregate constraint... the only exception is the requirement-rate
       ]

       if Macroprudential-Rules = "Basel2" [
          set Available-Credit-Basel               Available-Credit-Basel2
       ]

       if Macroprudential-Rules = "Basel3_1" [
          set Available-Credit-Basel               Available-Credit-Basel31
       ]

       if Macroprudential-Rules = "Basel3_2" [
          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 

to SubF-Update-Monetary-Variables
   set Currency                         (Initial-Liquidity-of-Firms * 250 + Initial-households-personal-assets * 3250 + Initial-Capital-of-the-Bank * 2)             ; Currency is "coins and bills": the initial deposits... any initial reserve is included
   ; the initial reserves are extracted from the variable "currency", which is divided between accounts and reserves... so the additional reserves has to take this in consideration
   let Monetary-Base-uses                max list 0 (Currency + sum [Reserves] of Banks - Reserve-Requirement * Currency )                                           ; monetary base is "outside money": uses of the base approach
   let Monetary-Base-sources             max list 0 (sum [Central-Bank-Loans] of Banks + Public-Debt - Account-of-State-at-Central-Bank - Central-Bank-Own-Capital)  ; monetary base is "outside money": sources of the base approach
   if Monetary-Base-Calculation = "uses of the base" [
       set Monetary-Base                 Monetary-Base-uses
   ]
   if Monetary-Base-Calculation = "sources of the base" [
       set Monetary-Base                 Monetary-Base-sources
   ]
   set Money-Supply                      Currency + sum [Total-Accounts] of Banks                                                                                     ; Monetary-Base multiplied by the money multiplier (1/Reserve-Requirement) is the maximum Money-Supply
end                                                                                                                                                                    ; ... but the effective money supply is currency plus deposits

to Function-Call-State                                                                                                          ; the State get taxes, sells Public-Debt to the Central Bank if there is a deficit and buys Public-Debt to the Central Bank if there is a superavit and pays unemployment benefits
   set State-Budget                                 State-Budget - Public-Debt * (Taylor-Interest-Rate * Installment-on-Debt)   ; the unemploymet benefits was substracted from the State Budget when the State paid for it
   set Public-Debt                                  Public-Debt - Public-Debt * Installment-on-Debt
   let State-Budget_1                               State-Budget                                                                ; we record the budget balance

   if Do_We_Have_Central-Bank? = true [
      if State-Budget < 0 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 Public-Debt                            Public-Debt + 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 > 0 and Public-Debt >= State-Budget  [                                                                    ; if there is a surplus...
         set Public-Debt                            Public-Debt - State-Budget                                                  ; part of the debt is paid with the current surplus
         set State-Budget                           0                                                                           ; when the deficit is covered, the State budget is in equilibrium
      ]                                                                                                                         ; end of this case
      if State-Budget > 0 and Public-Debt < State-Budget   [                                                                    ; if the Central Bank exists and there is a surplus...
         set Account-of-State-at-Central-Bank       State-Budget - Public-Debt                                                  ; the surplus goes to the account of the State at the Central Bank, and this reduces the amount of money in the system
         set Public-Debt                            0
         set State-Budget                           0
      ]
  ]
end 

There are 3 versions of this model.

Uploaded by When Description Download
Rubén Osuna about 6 years ago Version 3 Download this version
Rubén Osuna about 6 years ago Minor adjustments Download this version
Rubén Osuna about 6 years ago Many changes. Working model. Download this version

Attached files

File Type Description Last updated
Sin título.jpeg jpeg Screnshot about 6 years ago, by Rubén Osuna Download

Parent: Macroeconomic ABM with Banking Instability and Macroprudential Rules

This model does not have any descendants.

Graph of models related to 'Version 2'