Using the python class, try simulating the production and consumption behavior of self-sufficient farmers very roughly and easily ② See the code and results

Now let's skip the crappy review and take a look at the code and results. Please refer to for the explanation of the condition setting.

code

"""
subsistance.py program
Self-sufficient farmers produce
Self-sufficient farmers randomly iterate production plans and implement plans that maximize utility
Self-sufficient farmers use their own labor and capital for production
1~10th term: Maximize utility at initial price
11~20th term:The price of B rises once, and the utility is maximized at that price.
21~30th term:The price of o drops once, and the utility is maximized at that price.
31~40th term:The price of B rises once, and o falls once, and the utility is maximized at that price.
"""

#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
gamma1 = 0.2   #Parameters related to the utility that consumers obtain when consuming self-sufficient food
gamma2 = 0.45  #Parameters related to the utility that consumers get when consuming other goods (such as TV and NETFLIX)
w = 200       #wage
SEED = 1234  #Seed value
R = 40        #Setting the number of repetitions

#Class definition
class Autarky:
    """Definition of a class that represents a self-sufficient farmer"""
    def __init__(self, cat):   #constructor
        self.category = cat
        self.utility = 0      #Maximum utility (0 for the time being)
        self.co = 0           #Maximum utility O consumption
        self.l = 0            #Leisure time at maximum utility
        self.C = 0            #Total consumption at maximum utility
        self.I = 5000         #Budget at maximum utility(Keep it at 5000)
        self.profit = 0       #Profit at maximum utility
        self.qa = 0           #A production volume at maximum utility
        self.qb = 0           #B production at maximum utility
        self.LA = 0           #Below, the amount of each production factor used at the maximum utility
        self.KA = 0
        self.LB = 0
        self.KB = 0
        self.Ln = 0
    def solveUmax(self):   #Produce A and B to maximize profits
        """Reset the best value of utility"""
        self.utility = 0
        """After randomly calculating the profit, solve the utility optimization problem based on the profit."""
        for i in range(nlimit):
            self.calcprofit(Market)                   #Profit is calculated
            I = self.I + self.profit                  #Farmer's income is the sum of income from agricultural labor and non-agricultural labor
            self.calcutility(I, Market)               #Utility is calculated
    def calcprofit(self, Market):    #Profit calculation
        """Randomly obtain combinations that satisfy the self-constraint of production factors"""
        LA = int(random.randrange(18))                #Choose an integer between 0 and 18
        LB = int(random.randrange(18 - LA))           #Choose an integer between 0 and 18-LA
        Ln = int(random.randrange(18 - LA - LB))      #Put surplus labor into non-agricultural labor
        l = 18 - LA - LB - Ln
        KA = int(random.randrange(10))
        KB = 10 - KA
        """Production function"""
        qa = 3 * LA ** (alpha) * KA ** (1 - alpha)
        qb = 1 * LB ** (beta) * KB ** (1 - beta)
        """Profit function"""
        profit = Market.pB * qb + w * Ln
        """Update information""" 
        self.profit = profit
        self.qa = qa
        self.qb = qb
        self.LA = LA
        self.KA = KA
        self.LB = LB
        self.KB = KB
        self.Ln = Ln
        self.l = l
    def calcutility(self, I, Market):   #Calculate the maximum utility
        """Randomly choose the consumption of o"""
        maxco = I / Market.po
        co = int(maxco)
        """Calculate total spending for the current term"""
        C = Market.po * co
        """Utility function"""
        utility = self.qa ** (gamma1) + co ** (gamma2) + self.l ** (1 - gamma1 - gamma2)
        """Update the best solution of utility"""
        if utility >= self.utility:   #Update best solution
            self.utility = utility
            self.co = co
            self.C = C
            self.I = I - C   #I will calculate the budget for the next term, so I subtracted the expenditure
#End of definition of class Autarky

#Class definition Market
class Market:
    def __init__(self):
        self.pB = 100   #Initial produce price
        self.po = 300   
    def price_B(self):   #pB price increase by 50 yen
        self.pB += 50
    def price_o(self):   #50 yen price cut for po
        self.po -= 50
#End of definition of class Market

        
#Definition of subcontracting function
#Calcn that controls the calculation of the next term when the price does not change_n()Function definition
def calcn_n(t, a, Market):
    #① Put the price at the beginning of this term in the list
    pBlist.append(Market.pB)   #price
    polist.append(Market.po)
    tlist.append(t)            #time
    #② Optimizing the utility of self-sufficient farmers
    for i in range(len(a)):
        a[i].solveUmax()


#Calcn that controls the next calculation when pB changes once_B()Function definition
def calcn_B(t, a, Market):
    #① Change in pB price
    Market.price_B()
    #② Add the price at the beginning of this term to the list
    pBlist.append(Market.pB)   #price
    polist.append(Market.po)
    tlist.append(t)            #time
    #③ Optimizing the utility of farmers
    for i in range(len(a)):
        a[i].solveUmax()

    
#Calcn that controls the next calculation when po changes once_o()Function definition
def calcn_o(t, a, Market):
    #① Change in po price
    Market.price_o()
    #② Add the price at the beginning of this term to the list
    pBlist.append(Market.pB)   #price
    polist.append(Market.po)
    tlist.append(t)            #time
    #③ Optimizing the utility of farmers
    for i in range(len(a)):
        a[i].solveUmax()


#Calcn that controls the next calculation when pB and po change once_Bo()Function definition
def calcn_Bo(t, a, Market):
    #① Changes in pB and po prices
    Market.price_B()
    Market.price_o()
    #② Add the price at the beginning of this term to the list
    pBlist.append(Market.pB)   #price
    polist.append(Market.po)
    tlist.append(t)            #time
    #③ Optimizing the utility of farmers
    for i in range(len(a)):
        a[i].solveUmax()


#Calc that calculates the aggregated value of the element and adds it to the list_list()Function definition
def calc_list(a):
    qa = 0
    qb = 0
    profit = 0
    LA = 0
    KA = 0
    LB = 0
    KB = 0
    Ln = 0
    l = 0
    cb = 0
    co = 0
    utility = 0
    C = 0
    I = 0
    for i in range(len(a)):
        qa += a[i].qa
        qb += a[i].qb
        profit += a[i].profit
        LA += a[i].LA
        KA += a[i].KA
        LB += a[i].LB
        KB += a[i].KB
        l += a[i].l
        Ln += a[i].Ln
        co += a[i].co
        utility += a[i].utility
        C += a[i].C
        I += a[i].I
    utilitylistA.append(utility)
    colistA.append(co)
    ClistA.append(C)
    IlistA.append(I)
    profitlistA.append(profit)
    qalistA.append(qa)
    qblistA.append(qb)
    LAlistA.append(LA)
    KAlistA.append(KA)
    LBlistA.append(LB)
    KBlistA.append(KB)
    LnlistA.append(Ln)
    llistA.append(l)


#Main executive
#Initialization
random.seed(SEED)      #Random number initialization
Market = Market()      #Put an instance of class Market in a variable
#Duplicate an instance of Autarky of category 0 in the list (planned to be done, this time one by one)
a = [Autarky(0)]
#Listing of farmer status
utilitylistA = []
colistA = []
ClistA = []
IlistA = []
profitlistA = []
qalistA = []
qblistA = []
LAlistA = []
KAlistA = []
LBlistA = []
KBlistA = []
LnlistA = []
llistA = []
#Listing prices and product remainders
pBlist = []
polist = []
#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. :"))

#simulation
for t in range(R):
    if t <= 10:                     # 1~10th term: Initial price
        calcn_n(t, a, Market)
        calc_list(a)
    if t == 11:                     #11th term: B price change
        calcn_B(t, a, Market)
        calc_list(a)
    if (t > 11) and (t <= 20):      # 12~20th term: Stable after B price change
        calcn_n(t, a, Market)
        calc_list(a)
    if t == 21:                     #21st term: o Price change
        calcn_o(t, a, Market)
        calc_list(a)
    if (t > 21) and (t <= 30):      # 22~30th term: o Stable after price change
        calcn_n(t, a, Market)
        calc_list(a)
    if t == 31:                     #31st term: B and o price changes
        calcn_Bo(t, a, Market)
        calc_list(a)
    if (t > 31) and (t <= 40):     # 32~40th term: B and o Stable after price change
        calcn_n(t, a, Market)
        calc_list(a)
#End of simulation part

#View the list of important variables as is
print("profit",profitlistA,"\n","\n","A production",qalistA,"\n","\n","B production",qblistA,"\n","\n","LA",LAlistA,"\n","\n","LB",LBlistA,
      "\n","\n","Ln",LnlistA,"\n","\n","l", llistA, "\n","\n",, "utility",utilitylistA, "\n","\n", "o consumption",colistA,"\n","\n","C",ClistA,
      "\n","\n","pA",pBlist,"\n","\n","po",polist,"\n","\n", "income",IlistA)

# sell&buy.py

result

This time, we set the number of times to pursue the best solution to 10,000. The seed value is fixed at 1234.

price

ダウンロード.png As set, the prices of B and o increased / decreased in the 10th, 20th, and 30th periods.

A and B production

ダウンロード (1).png The change of A is gudaguda w The production volume of A changed in a U shape after the 10th, 20th, and 30th periods. Why ...? w The production volume of B seems to be relatively constant.

A, o, l consumption

ダウンロード (2).png The consumption of o is gradually increasing. Not surprisingly, as prices are declining. On the other hand, the consumption of l (leisure) is constant.

Input of production factors

ダウンロード (3).png Hard to see w. I should have made a stacked bar graph. whatever. Somehow, I feel that there is a tendency for negative autocorrelation over time. When the amount of input in the previous term is large, it will decrease in the next term. what's this.

Profit and consumption

ダウンロード (4).png Well, it's constant. Since the price of cash crops is on the rise, I wondered if profits would increase, but the increase in production of self-sufficient grains hindered the increase in profits. The simple interpretation is that farmers' incomes have stabilized at a low level due to self-sufficient production. I wonder if this is a self-sufficient production trap.

utility

ダウンロード (5).png Wow ww After all, the amount that can be consumed is increasing, so the utility is increasing. Especially since it has risen from 20, in this simulation, the price decrease of luxury item o was a better event for a self-sufficient farmer than the price increase of cash crop B. I see.

problem

Maximization problem

As I pointed out last time, the method of maximization problem is not good. This is because the best solution is found by randomly changing the input allocation of production factors 10,000 times and adopting the best result, so changing the seed value will change the result. There is no problem if you aim to maximize profit, but if you try to maximize utility across profit calculations, it will not be stable. After all, I wonder if I have to solve the maximization problem mathematically. I know how to solve it with paper and pencil, but what kind of code should I use? Also, as an image, the Newton-Raphson method is used when estimating the parameters of the regression equation by the maximum likelihood method, but I think that it is possible to approach the solution gradually with that kind of feeling. I think it's okay as it is.

Is the Cobb-Douglas type function system good? Also, can the parameters be constant?

Somehow, I feel that farmers become more productive as they become more proficient in farming. Shouldn't the parameters be improved in this case as well? Or shouldn't the productivity of all factors increase? I am concerned about this point. Also, the functional type is fixed to the Cobb-Douglas type, but shouldn't it be a more complicated functional system in order to consider economies of scale and parameter fluctuations? Well, what should I do?

Isn't it time to make it a multi-agent?

For the time being, there are now three classes available. They are "farmers," "consumers," and "self-sufficient farmers." There is also an idea to model a hobby kitchen garden farmer or an organic farmer who finds his farming method worthwhile. I want to create a world that incorporates these people.

that's all. Next, I would like to list the production model of a hobby kitchen garden farmer or an organic farmer who feels that his farming method is worthwhile without simulation. After that, I wonder if I will run a multi-agent simulation. The method of the maximization problem will remain as it is for the time being.

Recommended Posts

Using the python class, try simulating the production and consumption behavior of self-sufficient farmers very roughly and easily ② See the code and results
Using the python class, try simulating the production and consumption behavior of self-sufficient farmers very roughly and easily ① Condition setting
Using the python class, roughly simulate the production behavior of one farmer and the consumption behavior of one consumer ② ~ Time to see the results ~
Using the python class, try to roughly simulate the production behavior of 1 farmer and the consumption behavior of 1 consumer ① ~ Time to explain the conditions ~
Try using the collections module (ChainMap) of python3
The process of making Python code object-oriented and improving it