Last time, I explained how to set the conditions using the economic model, so this time I will explain what kind of code was used to construct the situation. If you want to look back from the condition settings, please check the previous Using python class …… ①.
(1) Substitute specific numerical values for the parameters of the model set last time. ② Check the code. ③ Check the result.
According to the "Empirical Analysis of Evolving Economics" in the special issue of Economic Seminar (2016) that I read the other day, In a recent macroeconomics paper, after econometrically verifying whether an economic model can represent reality, the estimated parameters are substituted into the economic model, and then anti-real virtual simulation (if subsidy is issued). What would have happened to the farmer's production if it had not been done?). Taylor (2005) and Dyer (2006), which I introduced in the previous article, also easily estimated and simulated the parameters in the production function and utility function (Cobb-Douglas type) from a rural survey in Mexico. On the other hand, in this simulation, the parameters were not estimated, and the numerical values selected appropriately were substituted. Below, we will introduce the numerical values applied to the parameters in this simulation.
\Pi = p_A*Q_A+p_B*Q_B+200*L_n...(1) \\ Q_A = 3*L_A^{0.3} *K_A^{0.7}...(2) \\ Q_B = L_B^{0.7} *K_B^{0.3}...(3) \\ 24 = L_A+L_B+L_n...(4) \\ 10 = K_A+K_B...(5)
$ p_A (initial price of A) $: 100 $ p_B (initial price of B) $: 300
U = c_A^{0.4}+c_B^{0.6}...(1) \\ I_t = I_{t-1} + 5000 - C_{t-1} > C_t = p_A*c_A + p_B*c_B...(2:Budget constraint) \\ Q_{A,t} + s_{A,t-1} > c_{A,t}...(3:Supply+Remainder> Consumption) \\ Q_{B,t} + s_{B,t-1} > c_{B,t}...(4:Supply+Remainder> Consumption) \\ c_A + c_B < 40...(5:Satiety constraint)
$ p_A (initial price of A) $: 100 $ p_B (initial price of B) $: 300
① Next budget: $ I_ {t + 1} = I_t + 5000 --c_t $
② Carry-over amount for the next term: $ s_ {t + 1} = s_t + Q_t --c_t $
③ How to determine the price for the next term
if
I explained in the previous article why I set it this way. Please check there.
"""
sell&buy.py program
Farmers and consumers repeat production and purchase
Farmers maximize profits, consumers maximize utility
Farmers use their own labor and capital for production
The price of the next term will fluctuate based on the stock + production volume-consumption volume of the previous term.
"""
#Module import
import random
import numpy as np
import matplotlib.pyplot as plt
#Global variables
alpha = 0.3 #Parameters related to the production of product A
beta = 0.7 #Parameters related to the production of product B
gamma = 0.4 #Parameters related to the utility that consumers obtain when consuming each product
w = 200 #wage
appe = 40 #The maximum amount that one person can eat is set to 40
SEED = 32768 #Seed value
R = 100 #Number of transaction repetitions
#Class definition Farmer
class Farmer:
"""Definition of a class that represents a farmer"""
def __init__(self, cat): #constructor
self.category = cat
self.maxprofit = 0 #Maximum profit (0 for the time being)
self.mqa = 0 #A production volume at maximum profit
self.mqb = 0 #B production at maximum profit
self.mLA = 0 #Below, the amount of each production factor used at the maximum profit
self.mKA = 0
self.mLB = 0
self.mKB = 0
self.mLn = 0
self.L = 24 #Self-labor
self.K = 10 #Amount of own capital
def solvePmax(self): #Produce A and B to maximize profits
"""Reset the best profit"""
self.maxprofit = 0
"""Solving profit optimization problems"""
for i in range(nlimit):
self.calcprofit(Market) #Profit is calculated (profit is calculated)
def calcprofit(self, Market): #Profit calculation
"""Randomly obtain combinations that satisfy the self-constraint of production factors"""
LA = int(random.randrange(24)) #Choose an integer between 0 and 24
LB = int(random.randrange(24 - LA)) #Choose an integer between 0 and 24-LA
Ln = self.L - LA - LB #Put surplus labor into non-agricultural labor
KA = int(random.randrange(10))
KB = self.K - KA
"""Production function"""
qa = 3 * LA ** (alpha) * KA ** (1 - alpha)
qb = 1 * LB ** (beta) * KB ** (1 - beta)
"""Profit function"""
profit = Market.pA * qa + Market.pB * qb + w * Ln
"""Update best solution"""
if profit >= self.maxprofit:
self.maxprofit = profit
self.mqa = qa
self.mqb = qb
self.mLA = LA
self.mKA = KA
self.mLB = LB
self.mKB = KB
self.mLn = Ln
#End of definition of class Farmer
#Class definition Consumer
class Consumer:
"""Definition of a class that represents a consumer"""
def __init__(self, cat): #constructor
self.category = cat
self.maxutility = 0 #Maximum utility (0 for the time being)
self.mca = 0 #Product A consumption
self.mcb = 0 #Product B consumption
self.C = 0 #Total spending
self.I = 5000 #Saving S as an initial budget=Gave 5000
def solveUmax(self): #Consume A and B to maximize utility
"""Reset utility and budget constraints"""
self.maxutility = 0
I = self.I + 5000 #One-time income is 5000
"""Solve utility optimization problems"""
for i in range(nlimit):
self.calcutil(I, Market) #Utility is calculated (utility is calculated)
def calcutil(self, I, Market): #Utility calculation
"""Randomly select the consumption of products A and B"""
ca = int(random.randrange(appe)) #0 to appe=Choose an integer within 40
cb = int(random.randrange(appe - ca)) #0 to appe=40 -Choose an integer within ca
"""Calculate total spending for the current term"""
C = Market.pA * ca + Market.pB * cb
"""Utility function"""
utility = ca ** (gamma) + cb ** (1 - gamma)
"""Update best solution"""
if I > C and Market.sa > ca and Market.sb > cb:
if utility >= self.maxutility: #Update best solution
self.maxutility = utility
self.mca = ca
self.mcb = cb
self.C = C
self.I = I - C #I will calculate the budget for the next term, so I subtracted the expenditure
#End of class Consumer
#Class definition Market
class Market:
def __init__(self):
self.pA = 100 #Initial produce price
self.pB = 300
self.sa = 2 * (12 ** 0.3) * (5 ** 0.7) #We used the values when half of the production factors owned by ourselves were allocated to the production of A and B, respectively.
self.sb = 1 * (12 ** 0.7) * (5 ** 0.3)
def save(self, f): #The amount produced by the farmer is put in the storage
for i in range(len(f)):
self.sa += f[i].mqa
self.sb += f[i].mqb
def eaten(self, c): #The amount consumed by the consumer is attracted from the storage, and one more/Only 3 are eaten by mice
for i in range(len(c)): #Eating by humans reduces storage for the next term
self.sa -= c[i].mca
self.sb -= c[i].mcb
self.sa *= 2 / 3 #Eating by mice reduces storage for the next term
self.sb *= 2 / 3
def price(self, c): #Calculate the price for the next term
Tca = 0
Tcb = 0
for i in range(len(c)):
Tca += c[i].mca
Tcb += c[i].mcb
if (self.sa * 3 / 2) / (self.sa * 3 / 2 + Tca) <= 0.3:
self.pA *= 1.01
else:
self.pA *= 0.99
if (self.sb * 3 / 2) / (self.sb * 3 / 2 + Tcb) <= 0.3:
self.pB *= 1.01
else:
self.pB *= 0.99
#Definition of subcontracting function
#Calcn that oversees the next calculation()Function definition
def calcn(t, f, c, Market):
#(1) Listed the time, the price of the previous term, and the product surplus of the previous term.
pAlist.append(Market.pA) #price
pBlist.append(Market.pB)
salist.append(Market.sa) #The remainder of the product
sblist.append(Market.sb)
tlist.append(t + 1) #time
#② Optimizing farm profits
for i in range(len(f)):
f[i].solvePmax()
#(3) Aggregated value of production volume of products on the market and other factors
mqa = 0
mqb = 0
maxprofit = 0
mLA = 0
mKA = 0
mLB = 0
mKB = 0
mLn = 0
for i in range(len(f)):
mqa += f[i].mqa
mqb += f[i].mqb
maxprofit += f[i].maxprofit
mLA += f[i].mLA
mKA += f[i].mKA
mLB += f[i].mLB
mKB += f[i].mKB
mLn += f[i].mLn
#④ Put the aggregated value of each farmer's output in the list
maxprofitlistF.append(maxprofit)
mqalistF.append(mqa)
mqblistF.append(mqb)
mLAlistF.append(mLA)
mKAlistF.append(mKA)
mLBlistF.append(mLB)
mKBlistF.append(mKB)
mLnlistF.append(mLn)
#⑤ Agricultural products are on the market
Market.save(f)
#⑥ Optimizing consumer utility
for i in range(len(c)):
c[i].solveUmax()
#⑦ Aggregated value of product consumption and other factors occurring in the market
mca = 0
mcb = 0
maxutility = 0
C = 0
mI = 0
for i in range(len(c)):
mca += c[i].mca
mcb += c[i].mcb
maxutility += c[i].maxutility
C += c[i].C
mI += c[i].I
#⑧ Put the aggregated value of each consumer output in the list
maxutilitylistC.append(maxutility)
mcalistC.append(mca)
mcblistC.append(mcb)
ClistC.append(C)
IlistC.append(mI)
#⑨ Surplus of products carried over to the next term
Market.eaten(c)
#⑩ Next price
Market.price(c)
#Main executive
#Initialization
random.seed(SEED) #Random number initialization
Market = Market() #Put an instance of class Market in a variable
#Duplicate instances of Category 0 Farmer and Consumer in the list (planned to be created, one by one this time). If you create an instance with a list, it seems that you cannot use the variable alone.
f = [Farmer(0)]
c = [Consumer(0)]
#Listing of farmer status
maxprofitlistF = []
mqalistF = []
mqblistF = []
mLAlistF = []
mKAlistF = []
mLBlistF = []
mKBlistF = []
mLnlistF = []
#Listing of consumer status
maxutilitylistC = []
mcalistC = []
mcblistC = []
ClistC = []
IlistC = []
#Listing prices and product remainders
pAlist = []
pBlist = []
salist = []
sblist = []
#List of times
tlist = []
#Enter the number of trials
nlimit = int(input("Specify the number of times to pursue the best solution. The larger the number, the closer to the optimal solution. :"))
#Agent simulation
for t in range(R):
calcn(t, f, c, Market) #Calculate the state at the next time
#End of simulation part
#Decimal adjustment of numbers in a particular list
#Adjust profit, production, utility, C, s, income
maxprofitlistF = [round(maxprofitlistF[n]) for n in range(len(maxprofitlistF)) ]
mqalistF = [round(mqalistF[n], 1) for n in range(len(mqalistF))]
mqblistF = [round(mqblistF[n], 1) for n in range(len(mqblistF))]
maxutilitylistC = [round(maxutilitylistC[n], 1) for n in range(len(maxutilitylistC))]
ClistC = [round(ClistC[n]) for n in range(len(ClistC))]
IlistC = [round(IlistC[n]) for n in range(len(IlistC))]
salist = [round(salist[n], 2) for n in range(len(salist))]
sblist = [round(sblist[n], 2) for n in range(len(sblist))]
#Graph display
print("profit","\n",maxprofitlistF,"\n","\n","A production volume","\n",mqalistF,"\n","\n","B production","\n",mqblistF,"\n","\n","LA","\n",mLAlistF,"\n","\n","LB","\n",mLBlistF,"\n","\n","Ln","\n",mLnlistF,"\n","\n","utility","\n",maxutilitylistC, "\n","\n","A consumption","\n",mcalistC,"\n","\n","B consumption","\n",mcblistC,"\n","\n","C","\n",ClistC,"\n","\n","pA","\n",pAlist,"\n","\n","pB","\n",pBlist,"\n","\n","sa","\n",salist,"\n","\n","sb","\n",sblist,"\n","\n","income","\n",IlistC)
pA = plt.plot(tlist, pAlist)
pB = plt.plot(tlist, pBlist)
plt.title("the price change of product A and B")
plt.xlabel("time")
plt.ylabel("price")
plt.legend((pA[0], pB[0]), ("pA", "pB"), loc=4)
plt.show()
# sell&buy.py
As written in the title, I tried using class. There are three types of classes created here: "Farmer", "Consumer", and "Market". Farmer produces A and B to maximize profit, Consumer consumes A and B to maximize utility under constraints, Market manages A and B inventory and adjusts prices.
I don't know how the optimization problem is solved in other economic simulations, Here, we randomly tried the combination of selection variables a specified number of times, and updated the combination when the utility or profit was the largest and the constraint condition was satisfied.
The code is written according to Tomohiro Odaka (2018): "Numerical calculation and simulation by Python", but there may be a part where Mr. Odaka misinterpreted the words used.
The reason for this is that I wanted to increase the number of agents later. In the future, when making it more like a multi-agent, I will increase the number of agents with different parameters. When disperse agent parameters ① Do you feel that the parameters are fine-tuned according to the probability distribution? (2) I am worried about whether to make the structure that the parameters change under the influence of other exogenous variables.
When I ran, the result was output as follows. Since it is long, some parts are omitted.
Specify the number of times to pursue the best solution. The larger the number, the closer to the optimal solution. : 100 A production volume [11.7, 21.2, 22.0, 16.3, 11.4, 21.2, 17.2, 17.9, 19.4, 14.4, 17.9, 17.2, 23.9, 19.4, 15.8, 22.6, 19.5, 19.4, 15.8, 15.8, 19.4, 19.5, 21.2, 17.2, 17.9, 22.0, 14.6, 22.6, 16.3, 17.2, 19.5, 19.4, 25.0, 17.8, 19.5, 23.9, 23.9, 25.0, 17.9, 27.0, 22.6, 14.4, 19.5, 21.2, 19.5, 19.4, 23.9, 15.8, 17.2, 26.1, 17.9, 19.4, 21.2, 17.2, 21.2, 26.1, 19.4, 22.6, 26.1, 22.6, 23.9, 21.2, 23.9, 22.6, 19.0, 26.1, 25.0, 27.9, 19.5, 22.6, 21.2, 25.0, 19.5, 22.6, 22.0, 21.2, 19.4, 27.0, 25.0, 27.0, 24.0, 19.4, 27.9, 21.2, 22.6, 19.5, 27.9, 27.0, 25.0, 27.0, 20.8, 30.1, 25.0, 23.9, 23.9, 26.1, 29.4, 19.4, 17.2, 25.0]
B production [5.4, 0.0, 3.8, 4.9, 6.3, 1.6, 1.0, 3.2, 0.0, 2.3, 3.2, 2.2, 1.0, 2.6, 3.2, 1.6, 2.0, 1.0, 3.2, 2.0, 2.6, 2.7, 2.2, 0.0, 2.0, 1.2, 5.9, 1.6, 4.3, 1.0, 3.2, 1.0, 1.6, 3.0, 1.2, 1.6, 2.6, 2.6, 1.2, 1.6, 2.2, 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 16, 19, 11, 16, 19, 16, 16, 18, 20, 16, 20, 19, 16, 22, 16, 16, 20, 18, 16, 19, 18, 19, 16, 18, 17, 12, 17, 11, 15, 16, 19, 14, 19, 18, 13, 19, 14, 15, 12, 14, 14, 18, 9, 19, 17, 16, 13, 14, 15, 15, 18, 10, 17, 14, 15, 14, 12, 18, 21, 15]
A consumption [23, 11, 28, 16, 12, 14, 19, 17, 21, 7, 23, 16, 23, 20, 16, 12, 26, 17, 16, 7, 20, 21, 19, 19, 15, 21, 10, 22, 10, 23, 16, 22, 20, 20, 16, 26, 20, 24, 16, 25, 23, 9, 13, 28, 19, 20, 20, 6, 22, 24, 20, 19, 20, 20, 12, 28, 14, 25, 26, 1, 39, 21, 13, 29, 18, 24, 20, 32, 17, 24, 20, 26, 15, 17, 25, 23, 11, 23, 20, 34, 16, 21, 22, 18, 27, 11, 33, 23, 28, 28, 28, 28, 28, 15, 25, 27, 27, 10, 22, 26]
B consumption [12, 1, 3, 5, 5, 2, 1, 3, 0, 2, 3, 2, 1, 1, 3, 2, 2, 0, 2, 3, 1, 1, 4, 0, 0, 2, 6, 1, 4, 1, 2, 2, 1, 1, 1, 2, 3, 2, 1, 2, 1, 3, 6, 2, 1, 3, 1, 2, 2, 0, 0, 2, 3, 3, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 2, 3, 0, 2, 3, 2, 1, 2, 1, 1, 4, 1, 2, 1, 3, 1, 2, 1, 3, 1, 2, 3, 0, 1, 2, 2, 2, 2, 2, 0, 2, 1, 0, 2, 0, 2]
C [5900, 1414, 3700, 3101, 2724, 2048, 2244, 2660, 2185, 1341, 3310, 2299, 2753, 2459, 2668, 1930, 3438, 1859, 2391, 1707, 2520, 2651, 3363, 2161, 1723, 3042, 3006, 2861, 2394, 2977, 2486, 3209, 2696, 2717, 2250, 3795, 3368, 3608, 2330, 3797, 3276, 2066, 3479, 4192, 2764, 3521, 2946, 1405, 3502, 3200, 2693, 3165, 3627, 3627, 1681, 3884, 2255, 3468, 3642, 141, 5463, 3256, 2145, 4387, 3135, 4317, 2915, 5279, 3389, 4184, 3326, 4563, 2614, 2947, 5039, 3890, 2334, 3889, 4052, 5613, 3134, 3588, 4385, 3176, 4869, 2676, 5205, 3972, 5115, 5115, 5115, 5115, 5115, 2537, 4867, 4959, 4704, 2351, 3833, 5166]
income [4100, 7686, 8986, 10886, 13162, 16114, 18870, 21210, 24025, 27684, 29374, 32075, 34322, 36863, 39195, 42265, 43827, 46968, 49578, 52870, 55350, 57700, 59337, 62176, 65452, 67410, 69404, 71543, 74149, 76171, 78685, 80477, 82781, 85064, 87813, 89018, 90650, 92042, 94712, 95916, 97639, 100573, 102095, 102902, 105138, 106617, 108672, 112267, 113764, 115565, 117872, 119707, 121080, 121080, 124399, 125515, 128260, 129792, 131150, 136009, 135546, 137290, 140145, 140758, 142623, 143307, 145392, 145112, 146723, 147539, 149212, 149649, 152036, 154089, 154050, 155160, 157827, 158937, 159885, 159272, 161138, 162550, 163164, 164989, 165120, 167444, 167239, 168267, 168152, 168152, 168152, 168152, 168152, 170616, 170748, 170789, 171085, 173734, 174901, 174735]
If you really try to summarize the results of your consideration, it will take longer, so I would like to briefly describe your impressions of the results.
I found it quite difficult to output the result using matplotlib. This time, I made a diagram of only the price changes and showed the changes of other variables just by pasting a list appropriately, but I wish I could make all the variables a bar graph. The next challenge.
The reason why I only tabulated the price changes was because I was wondering if the prices would converge to something like an equilibrium price. Looking at the figure, You can see that the price of Product A (the image of low-priced, capital-intensive grain) has risen steadily. And the consumption of A is almost constant, and the production seems to have increased gradually. It is normal for farmers to make more A with higher prices, but it is strange that the amount of A consumed by consumers has not changed. Perhaps the reason is that due to satiety constraints, the amount of increase in consumption is too small for the amount of increase in income, and the budget is too large to make sense. In that case, the consumption allocation may converge to a consumption equilibrium (the most favorite consumption allocation when the price does not change), which is determined by the parameters of the utility function regardless of the budget. Well, it's profound ... Should I remove the satiety constraint? Or maybe it would be better to increase the number of agents ...
To explain the input tendency of production factors in one word "The wages for non-farm labor are so high that everyone only farms for the purpose of side business." It turns out that most of the time was invested in Ln, but the wage of 200 may have been too big. Also, product B (an image of high-priced, labor-intensive fruits) was rarely produced, and only A was produced in large numbers. With this condition setting, it can be said that farmers tended to produce a lot of A, which has a high input productivity of production factors, instead of B, which has a slightly high initial price. It looks like a Japanese part-time rice farmer. By the way, if you enter a different number in the parameter, a completely different result will be output. After all it may be necessary to stick to the value of the parameter a little more.
As my friend said, the designer of the cellular automaton doesn't know what kind of pattern will be drawn at the end until the program is run. This time, I (the god of this program) tried to make a model that could imitate the behavior of farmers and consumers, but I didn't know what the result would be before the run, and after seeing the result, why? I couldn't even determine the reason for the result. I feel that scientists may be taking on a reckless challenge. The reality is more complicated than this simulation. After all, all human beings can do is "(1) find a basic theory that is a bone when explaining some phenomenon. (2) stick various bones together to make meat when explaining a specific phenomenon." think.
So, it's abrupt, but it ends here. Next, I'm thinking of making a simulation of a self-sufficient farmer, or studying pygame and making a simple game that makes the farmer feel like moving around.
~ Paper ~ [1]Alain de Janvry, Marcel Fafchamps and Elisabeth Sadoulet(1991) “Peasant household behavior with missing markets: some paradoxes explained” Economic Journal. Vol.101, pp.1400-1417. [2]George A. Dyer, Steve Boucher, and J. Edward Taylor(2006) “Subsistence response to market shocks” American journal of agricultural economics. Vol. 88, pp. 279-291. [3]J.Edward Taylor, George A. Dyer, Antonio Yu'nez-Naude(2005) "Disaggregated Rural Economywide Models for Policy Analysis" World Development. vol. 33, pp. 1671-1688
~ Textbook ~ [1] Tomohiro Odaka (2018): "Numerical Calculation and Simulation with Python", Ohmsha [2]Jake VanderPlas(2016) "Python Data Science Handbook: Essential Tools for Working with Data", O'Reilly Media