tpemartin / 112-2-programming-for-economic-modeling

MIT License
0 stars 1 forks source link

Exercise Demand and Suppy in OOP #9

Open tpemartin opened 1 year ago

chengpeter88 commented 1 year ago
######
class Demand:
    def __init__(self, ad, bd):
        self.ad = ad
        self.bd = bd

    def quantity(self, price):
        return self.ad - self.bd * price

    def __str__(self):
        return f'Demand(ad={self.ad}, bd={self.bd})'
######
class Supply:
    def __init__(self, az, bz):
        self.az = az
        self.bz = bz

    def quantity(self, price):
        "Compute quantity supplied at given price"
        return self.az + self.bz * price

    def __str__(self):
        return f'Supply(az={self.az}, bz={self.bz})'

#####
class Market:
    def __init__(self, demand, supply):
        self.demand = demand
        self.supply = supply

    def price(self):
        "Compute equilibrium price"
        return (self.demand.ad - self.supply.az) / (self.demand.bd + self.supply.bz)

    def quantity(self):
        "Compute equilibrium quantity"
        return self.demand.quantity(self.price())

    def __str__(self):
        return f'Market(demand={self.demand}, supply={self.supply})'

########
demand = Demand(ad=100, bd=0.5)
supply = Supply(az=20, bz=0.3)

market = Market(demand=demand, supply=supply)

price = market.price()
quantity = market.quantity()

print(f'Equilibrium price: {price:.2f}')
print(f'Equilibrium quantity: {quantity:.2f}')
12Maggie11 commented 1 year ago
import numpy as np
from numpy.linalg import inv
class Demand:
    def __init__(self, D, h):
        self.D=D
        self.h=h
    def quantity(self, pd):
        qd=np.array((self.D@pd)+self.h)
        return qd
class Supply:
    def __init__(self, C, e):
        self.C=C
        self.e=e
    def quantity(self, ps):
        qs=np.array((self.C@ps)+self.e)
        return qs 
class Market:
    def __init__(self, demand, supply):
        self.demand=demand
        self.supply=supply
    def price(self):
        pe=inv(C-D)@(h-e)
        return pe
    def quantity(self):
        qe=D@self.price()+h
        return qe

demand = Demand(D, h)
supply = Supply(C, e)
market = Market(demand, supply)

D=np.array([
    [-10,-5],
    [-1,-10]
])
h=np.array([
    [100],
    [50]
])
C=np.array([
    [10,5],
    [5,10]
])
e=np.array([
    [0],
    [0]
])

market.price(), market.quantity(), demand.quantity([[2],[4]]), supply.quantity([[1],[3]])