<jupyter_start><jupyter_text>A Consumer Class<jupyter_code>class Consumer:
    def __init__(self, w):
        "Initialize consumer with w dollars of wealth."
        self.wealth = w
    def earn(self, y):
        "The consumer earns y dollars."
        self.wealth += y
    def spend(self, x):
        "The consumer spends x dollars if feasible."
        new_wealth = self.wealth - x
        if new_wealth < 0:
            print("Insufficent funds.")
        else:
            self.wealth = new_wealth
    
c1 = Consumer(10)
c1.spend(5)
c1.wealth
c1.earn(15)
c1.spend(100)
c1 = Consumer(10)
c2 = Consumer(12)
c2.spend(4)
c2.wealth
c1.__dict__
print(Consumer.__dict__) # 展示__dict__属性
# 设置一种等价表示
c1 = Consumer(10)
c1.earn(10)
c1.wealth
# 等价于
Consumer.earn(c1,10) # 这里解释了为什么需要用到self作为第一个变量参数<jupyter_output><empty_output><jupyter_text>Example: The Solow Growth Model<jupyter_code>class Solow:
    '''
    Implements the Solow growth model with the update rule
    '''
    def __init__(self,
                 n = 0.05, # population growth rate
                 s = 0.25, # savings rate
                 delta = 0.1, # depreciation rate
                 alphas = 0.3, # share of labor
                 z = 2.0, # productivity
                 k = 1.0 ): # current capital stock
        self.n, self.s, self.delta, self.alphas, self.z = n, s, delta, alphas, z
        self.k = k
    def h(self):
        "Evaluate the h function."
        # unpack parameters (get rid of self to simplify notation)
        n, s, delta, alphas, z = self.n, self.s, self.delta, self.alphas, self.z
        # Apply the update rule
        return (s * z * (self.k ** alphas) + (1 - delta) * self.k) / (1 + n)
    def update(self):
        "Update eht current state (i.e., the capital stock)."
        self.k = self.h()
    def steady_state(self):
        "Compute the steady state value of capital."
        #Unpack parameters (get rid of self to simplify notation)
        n, s, delta, alphas, z = self.n, self.s, self.delta, self.alphas, self.z
        # Compute and return steady state
        return ((s * z) / (n + delta))**(1 / (1 - alphas))
    def generate_sequence(self, t):
        "Generate and return a time series of length t."
        path = []
        for i in range(t):
            path.append(self.k)
            self.update()
        return path
s1 = Solow()
s2 = Solow(k=8.0)

T = 60
fig, ax = plt.subplots(figsize = (9,6))
ax.plot([s1.steady_state()]*T, "k-", label = "steady state")

for s in s1, s2:
    lb = f"sapital series from initial state {s.k}"
    ax.plot(s.generate_sequence(T), 'o-', lw = 2, alpha = 0.6, label = lb)

ax.set_xlabel("$k_{t+1}$", fontsize = 14)
ax.set_ylabel("$k_t$", fontsize = 14)
ax.legend()
plt.show()<jupyter_output><empty_output><jupyter_text>Example: A Market<jupyter_code>from scipy.integrate import quad
class Market:
    def __init__(self, ad, bd, az, bz, tax):
        self.ad, self.bd, self.az, self.bz, self.tax = ad, bd, az, bz, tax
        if ad < az:
            raise ValueError("Insufficient demand.")
    
    def price(self):
        return (self.ad - self.az + self.bz * self.tax) / (self.bd + self.bz) # 解出供需平衡时的价格

    def quantity(self):
        return self.ad - self.bd * self.price() # 解出均衡价格时的量
    
    def consumer_surp(self):
        integrand = lambda x: (self.ad / self.bd) - (1/self.bd)*x
        area, error = quad(integrand, 0, self.quantity())
        return area - self.price() * self.quantity()
    
    def producer_surp(self):
        integrand = lambda x: -(self.az / self.bz) + (1/self.bz)*x
        area, error = quad(integrand, 0, self.quantity())
        return (self.price() - self.tax) * self.quantity() - area

    def taxrev(self):
        return self.tax * self.quantity()

    def inverse_demand(self, x):
        return self.ad / self.bd - (1 / self.bd) * x

    def inverse_supply(self, x):
        return -(self.az / self.bz) + (1 / self.bz) * x + self.tax
    
    def inverse_supply_no_tax(self, x):
        return -(self.az / self.bz) + (1 / self.bz) * x
baseline_params = 15, .5, -2, .5, 3
m = Market(*baseline_params)
print("Equilibrium price = ", m.price())
print("Consumer surplus = ", m.consumer_surp())
q_max = m.quantity() * 2
q_grid = np.linspace(0.0, q_max, 100)
pd = m.inverse_demand(q_grid)
ps = m.inverse_supply(q_grid)
psno = m.inverse_supply_no_tax(q_grid)

fig, ax = plt.subplots()
ax.plot(q_grid, pd, lw=2, alpha=0.6, label='demand')
ax.plot(q_grid, ps, lw=2, alpha=0.6, label='supply')
ax.plot(q_grid, psno, '--k', lw=2, alpha=0.6, label='supply without tax')
ax.set_xlabel('quantity', fontsize = 14)
ax.set_xlim(0, q_max)
ax.set_ylabel('price', fontsize = 14)
ax.legend(loc="lower right", frameon = False, fontsize = 14)
plt.show()
def deadw(m):
    m_no_tax = Market(m.ad, m.bd, m.az, m.bz, 0)
    surp1 = m_no_tax.consumer_surp() + m_no_tax.producer_surp()
    surp2 = m.consumer_surp() + m.producer_surp() + m.taxrev()
    return surp1 - surp2
deadw(m)<jupyter_output><empty_output><jupyter_text>Example: Chaos<jupyter_code>class Chaos:
    def __init__(self, x0, r):
        self.x, self.r = x0, r
    
    def update(self):
        self.x = self.r * self.x * (1 - self.x)

    def generate_sequence(self,n):
        path = []
        for i in range(n):
            path.append(self.x)
            self.update()
        return path
ch = Chaos(0.1, 4.0)
ch.generate_sequence(5)
ch = Chaos(0.1, 4.0)
ts_length = 250

fig, ax = plt.subplots()
ax.set_xlabel('$t$', fontsize = 14)
ax.set_ylabel('$x_t$', fontsize = 14)
x = ch.generate_sequence(ts_length)
ax.plot(range(ts_length), x, 'bo-', alpha=0.5, lw=2, label='$x_t$')
plt.show()<jupyter_output><empty_output><jupyter_text>Special Method<jupyter_code>x = (10, 20)
len(x)
class Foo:
    def __len__(self):
        return 42
f = Foo()
len(f)
class Foo:
    def __call__(self, x):
        return x + 42
f = Foo()
f(8)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14867617107942974, 'fraction_numerical': 0.024100475220638153, 'mean_word_length': 2.639901173563928, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '313212', 'license': 'MIT', 'n_tokens_mistral': 2353, 'n_tokens_neox': 2243, 'n_words': 555, 'path': '0. quant_econ_with_py_codes/0. Basic Knowledge of Economic with Python/Chapter6_Codes/Ch6_Codes.ipynb', 'repo_name': 'Matrix-JCG/quant_econ_with_python', 'size': '5892'}