{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "fa858cac",
   "metadata": {},
   "source": [
    "$$\n",
    "\\newcommand{\\argmax}{arg\\,max}\n",
    "\\newcommand{\\argmin}{arg\\,min}\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "02cdf40d",
   "metadata": {},
   "source": [
    "\n",
    "<a id='supply-demand-heterogeneity'></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b9fe1d8a",
   "metadata": {},
   "source": [
    "# Market Equilibrium with Heterogeneity"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9bb10804",
   "metadata": {},
   "source": [
    "## Overview\n",
    "\n",
    "In the [previous lecture](https://intro.quantecon.org/supply_demand_multiple_goods.html), we studied competitive equilibria in an economy with many goods.\n",
    "\n",
    "That economy contained a single representative consumer.\n",
    "\n",
    "Households, firms and other economic agents differ from one another along many dimensions.\n",
    "\n",
    "This lecture introduces heterogeneity across consumers by letting their preferences and endowments differ.\n",
    "\n",
    "We set production aside and study a pure exchange economy throughout.\n",
    "\n",
    "We compute competitive equilibria, construct a representative consumer, and verify both welfare theorems.\n",
    "\n",
    "Here are some imports:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "151abdbc",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from scipy.linalg import inv"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "61f99522",
   "metadata": {},
   "source": [
    "## A simple example\n",
    "\n",
    "Let’s study a simple example of a **pure exchange** economy without production.\n",
    "\n",
    "Two consumers differ in their endowment vectors $ e_i $ and their bliss point vectors $ b_i $ for $ i=1,2 $.\n",
    "\n",
    "Both consumers share the same matrix $ \\Pi $.\n",
    "\n",
    "The shared $ \\Pi $ lets us aggregate the two consumers into a single representative consumer below.\n",
    "\n",
    "The total endowment is $ e_1 + e_2 $.\n",
    "\n",
    "A competitive equilibrium requires that\n",
    "\n",
    "$$\n",
    "c_1 + c_2 = e_1 + e_2\n",
    "$$\n",
    "\n",
    "Recall from [Supply and Demand with Many Goods](https://intro.quantecon.org/supply_demand_multiple_goods.html) that each consumer’s demand curve is\n",
    "\n",
    "$$\n",
    "c_i = (\\Pi^\\top \\Pi )^{-1}(\\Pi^\\top b_i -  \\mu_i p )\n",
    "$$\n",
    "\n",
    "Competitive equilibrium then requires that\n",
    "\n",
    "$$\n",
    "e_1 + e_2 =\n",
    "    (\\Pi^\\top \\Pi)^{-1}(\\Pi^\\top (b_1 + b_2) - (\\mu_1 + \\mu_2) p )\n",
    "$$\n",
    "\n",
    "which, after a line or two of linear algebra, implies that\n",
    "\n",
    "\n",
    "<a id='equation-eq-old6'></a>\n",
    "$$\n",
    "(\\mu_1 + \\mu_2) p = \\Pi^\\top(b_1+ b_2) - \\Pi^\\top \\Pi (e_1 + e_2) \\tag{53.1}\n",
    "$$\n",
    "\n",
    "We take $ \\Pi $ to be square and invertible, as in [Supply and Demand with Many Goods](https://intro.quantecon.org/supply_demand_multiple_goods.html), so that $ (\\Pi^\\top \\Pi)^{-1}\\Pi^\\top = \\Pi^{-1} $.\n",
    "\n",
    "We normalize prices by setting $ \\mu_1 + \\mu_2 =1 $ and then solve\n",
    "\n",
    "\n",
    "<a id='equation-eq-old7'></a>\n",
    "$$\n",
    "\\mu_i(p,e) = \\frac{p^\\top (\\Pi^{-1} b_i - e_i)}{p^\\top (\\Pi^\\top \\Pi )^{-1} p} \\tag{53.2}\n",
    "$$\n",
    "\n",
    "for $ \\mu_i, i = 1,2 $."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d7e84800",
   "metadata": {},
   "source": [
    "## Exercise 53.1\n",
    "\n",
    "Show that, up to normalization by a positive scalar, the same competitive equilibrium price vector that you derived in the preceding two-consumer economy would prevail in a single-consumer economy in which a single **representative consumer** has utility function\n",
    "\n",
    "$$\n",
    "- \\frac{1}{2} (\\Pi c -b) ^\\top (\\Pi c -b )\n",
    "$$\n",
    "\n",
    "and endowment vector $ e $,  where\n",
    "\n",
    "$$\n",
    "b = b_1 + b_2\n",
    "$$\n",
    "\n",
    "and\n",
    "\n",
    "$$\n",
    "e = e_1 + e_2 .\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b0f3eab2",
   "metadata": {},
   "source": [
    "## Solution\n",
    "\n",
    "For the two-consumer economy, equation [(53.1)](#equation-eq-old6) says that the competitive equilibrium price vector satisfies\n",
    "\n",
    "$$\n",
    "(\\mu_1 + \\mu_2)\\, p = \\Pi^\\top (b_1 + b_2) - \\Pi^\\top \\Pi (e_1 + e_2)\n",
    "  = \\Pi^\\top b - \\Pi^\\top \\Pi e\n",
    "$$\n",
    "\n",
    "Now consider the single representative consumer with bliss point $ b = b_1 + b_2 $ and endowment $ e = e_1 + e_2 $.\n",
    "\n",
    "Because that consumer is alone in the economy, market clearing requires $ c = e $, so their demand curve implies the price vector $ \\tilde p $ that satisfies\n",
    "\n",
    "$$\n",
    "\\tilde \\mu \\, \\tilde p = \\Pi^\\top b - \\Pi^\\top \\Pi e\n",
    "$$\n",
    "\n",
    "The right sides of the two displayed equations are identical, so\n",
    "\n",
    "$$\n",
    "\\tilde p = \\frac{\\mu_1 + \\mu_2}{\\tilde \\mu}\\, p\n",
    "$$\n",
    "\n",
    "The two price vectors are therefore proportional, with a positive factor of proportionality because marginal utilities of wealth are positive.\n",
    "\n",
    "Since only relative prices matter, the two economies have the same competitive equilibrium prices; normalizing $ \\mu_1 + \\mu_2 = \\tilde\\mu = 1 $ makes the two price vectors equal.\n",
    "\n",
    "We verify this more carefully, and allow for transfers of wealth, in the section [deducing a representative consumer](#rep-consumer) below."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b2b1f368",
   "metadata": {},
   "source": [
    "## Pure exchange economy\n",
    "\n",
    "Let’s further explore a pure exchange economy with $ n $ goods and $ m $ people.\n",
    "\n",
    "In this lecture $ m $ denotes the number of consumers.\n",
    "\n",
    "In [Supply and Demand with Many Goods](https://intro.quantecon.org/supply_demand_multiple_goods.html) $ m $ denoted the number of rows of $ \\Pi $."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e24116b6",
   "metadata": {},
   "source": [
    "### Competitive equilibrium\n",
    "\n",
    "We’ll compute a competitive equilibrium.\n",
    "\n",
    "To compute a competitive equilibrium of a pure exchange economy, we use the fact that\n",
    "\n",
    "- Relative prices in a competitive equilibrium are the same as those in a special single person or  representative consumer economy with preference $ \\Pi $ and $ b=\\sum_i b_i $, and endowment $ e = \\sum_i e_{i} $.  \n",
    "\n",
    "\n",
    "This aggregation requires that all consumers share the same matrix $ \\Pi $.\n",
    "\n",
    "Consumer $ i $ faces the budget constraint\n",
    "\n",
    "\n",
    "<a id='equation-eq-budget-i'></a>\n",
    "$$\n",
    "p^{\\top}\\left(c_{i}-e_{i}\\right)=W_{i} \\tag{53.3}\n",
    "$$\n",
    "\n",
    "where $ W_{i} $ is a lump-sum transfer of wealth measured in units of the numeraire good, and the transfers satisfy $ \\sum_i W_{i}=0 $.\n",
    "\n",
    "Setting $ W_{i}=0 $ for every $ i $ returns a pure exchange economy in which a consumer’s endowment is their only source of income.\n",
    "\n",
    "Substituting the demand curve into [(53.3)](#equation-eq-budget-i) and solving for $ \\mu_i $ gives\n",
    "\n",
    "\n",
    "<a id='equation-eq-mu-i'></a>\n",
    "$$\n",
    "\\mu_{i}=\\frac{-W_{i}+p^{\\top}\\left(\\Pi^{-1}b_{i}-e_{i}\\right)}{p^{\\top}(\\Pi^{\\top}\\Pi)^{-1}p} \\tag{53.4}\n",
    "$$\n",
    "\n",
    "These are **Marshallian** demand curves in the terminology of [Supply and Demand with Many Goods](https://intro.quantecon.org/supply_demand_multiple_goods.html): we solve for $ \\mu_i $ from a budget constraint instead of fixing it.\n",
    "\n",
    "We compute a competitive equilibrium in three steps.\n",
    "\n",
    "- First we solve the single representative consumer economy by normalizing $ \\mu = 1 $, then renormalize the price vector by using the first consumption good as a numeraire.  \n",
    "- Next we compute each consumer’s marginal utility of wealth from [(53.4)](#equation-eq-mu-i).  \n",
    "- Finally we compute a competitive equilibrium allocation from the demand curves:  \n",
    "\n",
    "\n",
    "$$\n",
    "c_{i}=\\Pi^{-1}b_{i}-(\\Pi^{\\top}\\Pi)^{-1}\\mu_{i}p\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a6d24a88",
   "metadata": {},
   "source": [
    "### Designing some Python code\n",
    "\n",
    "Below we shall construct a Python class with the following attributes:\n",
    "\n",
    "- **Preferences** in the form of  \n",
    "  - an $ n \\times n $ invertible matrix $ \\Pi $, shared by all consumers, which makes $ \\Pi^\\top \\Pi $ positive definite  \n",
    "  - an $ n \\times 1 $ vector of bliss points $ b_i $ for each consumer $ i $  \n",
    "- **Endowments** in the form of  \n",
    "  - an $ n \\times 1 $ vector $ e_i $ for each consumer $ i $  \n",
    "  - a scalar “wealth” $ W_i $ for each consumer $ i $, with default value $ 0 $  \n",
    "\n",
    "\n",
    "The class will include a test to make sure that $ b_i \\gg \\Pi e_i $ and raise an exception if it is violated\n",
    "(at some threshold level we’d have to specify).\n",
    "\n",
    "- **A Pure Exchange Economy** will consist of  \n",
    "  - a collection of $ m $ **persons**, each described by a bliss point $ b_i $, an endowment $ e_i $ and a wealth $ W_i $  \n",
    "    - $ m=2 $ in all of the economies that we study below  \n",
    "  - an equilibrium price vector $ p $ (normalized somehow)  \n",
    "  - an equilibrium allocation $ c_1, c_2, \\ldots, c_m $ – a collection of $ m $ vectors of dimension $ n \\times 1 $  \n",
    "\n",
    "\n",
    "Now let’s proceed to code."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a0cd9604",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "class ExchangeEconomy:\n",
    "    def __init__(self,\n",
    "                 Π,\n",
    "                 bs,\n",
    "                 es,\n",
    "                 Ws=None,\n",
    "                 thres=1.5):\n",
    "        \"\"\"\n",
    "        Set up the environment for an exchange economy\n",
    "\n",
    "        Args:\n",
    "            Π (np.array): shared matrix of substitution\n",
    "            bs (list): all consumers' bliss points\n",
    "            es (list): all consumers' endowments\n",
    "            Ws (list): all consumers' wealth\n",
    "            thres (float): a threshold used to test whether b >> Π e is violated\n",
    "        \"\"\"\n",
    "        n, m = Π.shape[0], len(bs)\n",
    "\n",
    "        # check non-satiation\n",
    "        for b, e in zip(bs, es):\n",
    "            if np.min(b / np.max(Π @ e)) <= thres:\n",
    "                raise Exception('set bliss points further away')\n",
    "\n",
    "        if Ws is None:\n",
    "            Ws = np.zeros(m)\n",
    "        elif not np.isclose(np.sum(Ws), 0):\n",
    "            raise Exception('invalid wealth distribution')\n",
    "\n",
    "        self.Π, self.bs, self.es, self.Ws, self.n, self.m = Π, bs, es, Ws, n, m\n",
    "\n",
    "    def competitive_equilibrium(self):\n",
    "        \"\"\"\n",
    "        Compute the competitive equilibrium prices and allocation\n",
    "        \"\"\"\n",
    "        Π, bs, es, Ws = self.Π, self.bs, self.es, self.Ws\n",
    "        n, m = self.n, self.m\n",
    "        slope_dc = inv(Π.T @ Π)\n",
    "        Π_inv = inv(Π)\n",
    "\n",
    "        # aggregate\n",
    "        b = sum(bs)\n",
    "        e = sum(es)\n",
    "\n",
    "        # compute price vector with mu=1 and renormalize\n",
    "        p = Π.T @ b - Π.T @ Π @ e\n",
    "        p = p / p[0]\n",
    "\n",
    "        # compute marginal utility of wealth\n",
    "        μ_s = []\n",
    "        c_s = []\n",
    "        A = p.T @ slope_dc @ p\n",
    "\n",
    "        for i in range(m):\n",
    "            μ_i = (-Ws[i] + p.T @ (Π_inv @ bs[i] - es[i])) / A\n",
    "            c_i = Π_inv @ bs[i] - μ_i * slope_dc @ p\n",
    "            μ_s.append(μ_i)\n",
    "            c_s.append(c_i)\n",
    "\n",
    "        for c_i in c_s:\n",
    "            if any(c_i < 0):\n",
    "                print('allocation: ', c_s)\n",
    "                raise Exception('negative allocation: equilibrium does not exist')\n",
    "\n",
    "        return p, c_s, μ_s"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "57da500d",
   "metadata": {},
   "source": [
    "## Implementation\n",
    "\n",
    "Next we use the class `ExchangeEconomy` defined above to study\n",
    "\n",
    "- a two-person economy without production,  \n",
    "- a dynamic economy, and  \n",
    "- an economy with risk and Arrow securities.  "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7a9d5e87",
   "metadata": {},
   "source": [
    "### Two-person economy without production\n",
    "\n",
    "Here we study how competitive equilibrium $ p, c_1, c_2 $ respond to different $ b_i $ and $ e_i $, $ i \\in \\{1, 2\\} $.\n",
    "\n",
    "We also report each consumer’s marginal utility of wealth $ \\mu_i $.\n",
    "\n",
    "A high $ \\mu_i $ identifies a consumer who is poor at equilibrium prices, in the sense that an extra unit of wealth would be worth a lot to them."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "283ba32c",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "Π = np.array([[1, 0],\n",
    "              [0, 1]])\n",
    "\n",
    "bs = [np.array([5, 5]),  # first consumer's bliss points\n",
    "      np.array([5, 5])]  # second consumer's bliss points\n",
    "\n",
    "es = [np.array([0, 2]),  # first consumer's endowment\n",
    "      np.array([2, 0])]  # second consumer's endowment\n",
    "\n",
    "EE = ExchangeEconomy(Π, bs, es)\n",
    "p, c_s, μ_s = EE.competitive_equilibrium()\n",
    "\n",
    "print('Competitive equilibrium price vector:', p)\n",
    "print('Competitive equilibrium allocation:', c_s)\n",
    "print('Marginal utilities of wealth:', μ_s)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7132477f",
   "metadata": {},
   "source": [
    "The two consumers have identical preferences and differ only in which good they are endowed with.\n",
    "\n",
    "They trade to a symmetric allocation, and their marginal utilities of wealth are equal.\n",
    "\n",
    "What happens if the first consumer likes the first good more and the second consumer likes the second good more?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "41b35a60",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "EE.bs = [np.array([6, 5]),  # first consumer's bliss points\n",
    "         np.array([5, 6])]  # second consumer's bliss points\n",
    "\n",
    "p, c_s, μ_s = EE.competitive_equilibrium()\n",
    "\n",
    "print('Competitive equilibrium price vector:', p)\n",
    "print('Competitive equilibrium allocation:', c_s)\n",
    "print('Marginal utilities of wealth:', μ_s)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "37ed865f",
   "metadata": {},
   "source": [
    "Each consumer now ends up with more of the good that they like better.\n",
    "\n",
    "Let the first consumer be poorer.\n",
    "\n",
    "Each cell below sets both the bliss points and the endowments, so that no experiment inherits values from the preceding one."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a63b5709",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "EE.bs = [np.array([6, 5]),  # first consumer's bliss points\n",
    "         np.array([5, 6])]  # second consumer's bliss points\n",
    "\n",
    "EE.es = [np.array([0.5, 0.5]),  # first consumer's endowment\n",
    "         np.array([1, 1])]  # second consumer's endowment\n",
    "\n",
    "p, c_s, μ_s = EE.competitive_equilibrium()\n",
    "\n",
    "print('Competitive equilibrium price vector:', p)\n",
    "print('Competitive equilibrium allocation:', c_s)\n",
    "print('Marginal utilities of wealth:', μ_s)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9636e04c",
   "metadata": {},
   "source": [
    "The poorer consumer has the higher marginal utility of wealth.\n",
    "\n",
    "The first consumer consumes none of the second good.\n",
    "\n",
    "Our quadratic utility function does not rule out such corners.\n",
    "\n",
    "A poorer first consumer would drive the allocation negative, and our class would raise an exception.\n",
    "\n",
    "Now let’s construct an autarky (i.e., no-trade) equilibrium."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5c4d654f",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "EE.bs = [np.array([4, 6]),  # first consumer's bliss points\n",
    "      np.array([6, 4])]  # second consumer's bliss points\n",
    "\n",
    "EE.es = [np.array([0, 2]),  # first consumer's endowment\n",
    "      np.array([2, 0])]  # second consumer's endowment\n",
    "\n",
    "p, c_s, μ_s = EE.competitive_equilibrium()\n",
    "\n",
    "print('Competitive equilibrium price vector:', p)\n",
    "print('Competitive equilibrium allocation:', c_s)\n",
    "print('Marginal utilities of wealth:', μ_s)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "09bbf2e3",
   "metadata": {},
   "source": [
    "The equilibrium allocation reproduces the endowments, and no trade occurs.\n",
    "\n",
    "Each consumer likes the good with which they are endowed enough to keep it at the equilibrium price vector.\n",
    "\n",
    "The aggregate endowment and the aggregate bliss point have been symmetric across the two goods in every experiment so far, and the equilibrium price vector has been $ (1, 1) $.\n",
    "\n",
    "With $ \\Pi = I $, equation [(53.1)](#equation-eq-old6) makes $ p $ proportional to $ b - e $, so symmetry of both aggregates produces equal prices.\n",
    "\n",
    "Let’s now make the second good scarcer in the aggregate."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "486c835e",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "EE.bs = [np.array([6, 5]),  # first consumer's bliss points\n",
    "         np.array([5, 6])]  # second consumer's bliss points\n",
    "\n",
    "EE.es = [np.array([1.25, 0.75]),  # first consumer's endowment\n",
    "         np.array([1.25, 0.75])]  # second consumer's endowment\n",
    "\n",
    "p, c_s, μ_s = EE.competitive_equilibrium()\n",
    "\n",
    "print('Competitive equilibrium price vector:', p)\n",
    "print('Competitive equilibrium allocation:', c_s)\n",
    "print('Marginal utilities of wealth:', μ_s)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c74b9d53",
   "metadata": {},
   "source": [
    "The relative price of the second good now exceeds $ 1 $, because the second good is the scarcer of the two.\n",
    "\n",
    "The two consumers have identical endowments, so their differing tastes drive all trade.\n",
    "\n",
    "Now let’s redistribute endowments before trade."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "613b689d",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "bs = [np.array([5, 5]),  # first consumer's bliss points\n",
    "      np.array([5, 5])]  # second consumer's bliss points\n",
    "\n",
    "es = [np.array([1, 1]),  # first consumer's endowment\n",
    "      np.array([1, 1])]  # second consumer's endowment\n",
    "\n",
    "Ws = [0.5, -0.5]\n",
    "EE_new = ExchangeEconomy(Π, bs, es, Ws)\n",
    "p, c_s, μ_s = EE_new.competitive_equilibrium()\n",
    "\n",
    "print('Competitive equilibrium price vector:', p)\n",
    "print('Competitive equilibrium allocation:', c_s)\n",
    "print('Marginal utilities of wealth:', μ_s)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "97fcd70b",
   "metadata": {},
   "source": [
    "A lump-sum transfer of wealth from the second consumer to the first leaves the equilibrium price vector at $ (1,1) $.\n",
    "\n",
    "It moves the allocation from $ (1,1) $ for each consumer to $ (1.25, 1.25) $ and $ (0.75, 0.75) $.\n",
    "\n",
    "Redistributing wealth before trade has supported a different Pareto optimal allocation as a competitive equilibrium, an instance of the **second welfare theorem** of [Supply and Demand with Many Goods](https://intro.quantecon.org/supply_demand_multiple_goods.html)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c56c1422",
   "metadata": {},
   "source": [
    "### Exercise 53.2\n",
    "\n",
    "Take $ \\Pi = I $ and bliss points $ b_1 = (6,5)^\\top $ and $ b_2 = (5,6)^\\top $.\n",
    "\n",
    "Consider two ways of dividing the *same* aggregate endowment $ e_1 + e_2 = (3, 1.5)^\\top $:\n",
    "\n",
    "- distribution A: $ e_1 = (2, 0.5)^\\top $ and $ e_2 = (1, 1)^\\top $  \n",
    "- distribution B: $ e_1 = (0.5, 1.5)^\\top $ and $ e_2 = (2.5, 0)^\\top $  \n",
    "\n",
    "\n",
    "a. Compute the equilibrium price vector, allocation and marginal utilities of wealth under each distribution.\n",
    "\n",
    "What changes and what does not?\n",
    "\n",
    "b. Verify that $ \\sum_i \\mu_i $ is also the same under the two distributions, and explain why by using equation [(53.1)](#equation-eq-old6).\n",
    "\n",
    "c. Which consumer has the higher marginal utility of wealth under distribution A, and why?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "afab31e6",
   "metadata": {},
   "source": [
    "### Solution"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "06bc0404",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "Π = np.array([[1, 0],\n",
    "              [0, 1]])\n",
    "\n",
    "bs = [np.array([6, 5]),\n",
    "      np.array([5, 6])]\n",
    "\n",
    "distributions = {'A': [np.array([2, 0.5]), np.array([1, 1])],\n",
    "                 'B': [np.array([0.5, 1.5]), np.array([2.5, 0])]}\n",
    "\n",
    "for name, es in distributions.items():\n",
    "    EE_d = ExchangeEconomy(Π, bs, es)\n",
    "    p, c_s, μ_s = EE_d.competitive_equilibrium()\n",
    "    print(f'distribution {name}: aggregate endowment = {sum(es)}')\n",
    "    print(f'  price vector : {p}')\n",
    "    print(f'  allocation   : {[np.round(c, 4) for c in c_s]}')\n",
    "    print(f'  μ_1, μ_2     : {np.round(μ_s, 4)}, sum = {np.sum(μ_s):.4f}\\n')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "58ef5933",
   "metadata": {},
   "source": [
    "The price vector is identical under the two distributions.\n",
    "\n",
    "The allocations differ.\n",
    "\n",
    "Equation [(53.1)](#equation-eq-old6) makes the price vector depend on the individual $ b_i $ and $ e_i $ only through the sums $ b = \\sum_i b_i $ and $ e = \\sum_i e_i $, and redistributing a fixed aggregate endowment leaves both sums unchanged.\n",
    "\n",
    "All consumers share the same $ \\Pi $, so every demand curve has the same slope $ -(\\Pi^\\top \\Pi)^{-1} p $ with respect to the marginal utility of wealth.\n",
    "\n",
    "Moving wealth from one consumer to another shifts one demand curve down and the other up by offsetting amounts.\n",
    "\n",
    "For part b, $ \\sum_i \\mu_i = 8.0 $ under both distributions.\n",
    "\n",
    "Equation [(53.1)](#equation-eq-old6) pins that sum down given $ p $, $ b $ and $ e $.\n",
    "\n",
    "It equals the marginal utility of wealth $ \\tilde\\mu $ of the representative consumer constructed below.\n",
    "\n",
    "For part c, the second consumer has the higher marginal utility of wealth under distribution A.\n",
    "\n",
    "Their endowment sells for less at equilibrium prices, so an extra unit of wealth is worth more to them."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eb13468e",
   "metadata": {},
   "source": [
    "### A dynamic economy\n",
    "\n",
    "Now let’s use the tricks described in [Supply and Demand with Many Goods](https://intro.quantecon.org/supply_demand_multiple_goods.html) to study a dynamic economy, one with two periods.\n",
    "\n",
    "We give our two consumers identical preferences but endow them at different dates: the first consumer is endowed early and the second consumer late."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c75e574e",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "beta = 0.95\n",
    "\n",
    "Π = np.array([[1, 0],\n",
    "              [0, np.sqrt(beta)]])\n",
    "\n",
    "bs = [np.array([5, np.sqrt(beta) * 5]),\n",
    "      np.array([5, np.sqrt(beta) * 5])]\n",
    "\n",
    "es = [np.array([2, 0]),   # first consumer is endowed at date 1\n",
    "      np.array([0, 2])]   # second consumer is endowed at date 2\n",
    "\n",
    "EE_DE = ExchangeEconomy(Π, bs, es)\n",
    "p, c_s, μ_s = EE_DE.competitive_equilibrium()\n",
    "\n",
    "print('Competitive equilibrium price vector:', p)\n",
    "print('Competitive equilibrium allocation:', c_s)\n",
    "print('Gross interest rate R = p1/p2:', p[0] / p[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a882a983",
   "metadata": {},
   "source": [
    "The gross interest rate is $ R = \\beta^{-1} = 1.0526 $.\n",
    "\n",
    "The first consumer is endowed early and lends to the second consumer, who is endowed late.\n",
    "\n",
    "Each consumer’s consumption is constant across the two dates.\n",
    "\n",
    "Neither consumer’s endowment is constant.\n",
    "\n",
    "The exercise below derives that flatness from the condition $ \\beta R = 1 $ of [Consumption Smoothing](https://intro.quantecon.org/cons_smooth.html).\n",
    "\n",
    "[The Overlapping Generations Model](https://intro.quantecon.org/olg.html) studies an economy with the same two-period structure, in which the young and the old trade at a gross interest rate.\n",
    "\n",
    "[The Overlapping Generations Model](https://intro.quantecon.org/olg.html) adds production and an unending sequence of overlapping generations.\n",
    "\n",
    "Our economy has a single pair of consumers and no production."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f0f7ed55",
   "metadata": {},
   "source": [
    "### Exercise 53.3\n",
    "\n",
    "Consider the two-period economy just computed, in which both consumers have bliss point $ \\Pi (5,5)^\\top $.\n",
    "\n",
    "a. Show that consumer $ i $’s consumption is constant across the two dates if and only if $ \\beta R = 1 $, where $ R = p_1 / p_2 $.\n",
    "\n",
    "b. Now let the aggregate endowment grow, by setting $ e_1 = (1.5, 0)^\\top $ and $ e_2 = (0, 2.5)^\\top $.\n",
    "\n",
    "Recompute the equilibrium.  What happens to $ R $ and to the shapes of the two consumption paths?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2dea9bcc",
   "metadata": {},
   "source": [
    "### Solution\n",
    "\n",
    "For part a, the demand curve is $ c_i = \\Pi^{-1} b_i - \\mu_i (\\Pi^\\top \\Pi)^{-1} p $.\n",
    "\n",
    "Here $ \\Pi^{-1} b_i = (5,5)^\\top $ and $ (\\Pi^\\top \\Pi)^{-1} = \\operatorname{diag}(1, \\beta^{-1}) $, so\n",
    "\n",
    "$$\n",
    "c_{i,2} - c_{i,1} = - \\mu_i \\left( \\frac{p_2}{\\beta} - p_1 \\right)\n",
    "                  = - \\mu_i p_1 \\left( \\frac{1}{\\beta R} - 1 \\right)\n",
    "$$\n",
    "\n",
    "This difference is zero for every consumer if and only if $ \\beta R = 1 $, because $ \\mu_i > 0 $ and $ p_1 > 0 $.\n",
    "\n",
    "[Consumption Smoothing](https://intro.quantecon.org/cons_smooth.html) obtains a flat consumption path from the same condition."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b066ef7f",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "bs = [np.array([5, np.sqrt(beta) * 5]),\n",
    "      np.array([5, np.sqrt(beta) * 5])]\n",
    "\n",
    "es = [np.array([1.5, 0]),\n",
    "      np.array([0, 2.5])]\n",
    "\n",
    "EE_growth = ExchangeEconomy(Π, bs, es)\n",
    "p, c_s, μ_s = EE_growth.competitive_equilibrium()\n",
    "\n",
    "print('Competitive equilibrium price vector:', p)\n",
    "print('Competitive equilibrium allocation:', [np.round(c, 4) for c in c_s])\n",
    "print(f'R       = {p[0] / p[1]:.6f}')\n",
    "print(f'1 / beta = {1 / beta:.6f}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6b062462",
   "metadata": {},
   "source": [
    "The aggregate endowment grows from $ 1.5 $ at date $ 1 $ to $ 2.5 $ at date $ 2 $.\n",
    "\n",
    "The gross interest rate rises to $ R = 1.1930 $ and exceeds $ \\beta^{-1} = 1.0526 $.\n",
    "\n",
    "Both consumption paths tilt upward over time, because $ \\beta R > 1 $.\n",
    "\n",
    "The two consumers share the consumption growth; they do not share the endowment growth."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9bd073d5",
   "metadata": {},
   "source": [
    "### Risk economy with Arrow securities\n",
    "\n",
    "We use the tricks described in [Supply and Demand with Many Goods](https://intro.quantecon.org/supply_demand_multiple_goods.html) to interpret  $ c_1, c_2 $ as “Arrow securities” that are state-contingent claims to consumption goods.\n",
    "\n",
    "The first consumer is endowed only in state $ 1 $ and the second consumer only in state $ 2 $.\n",
    "\n",
    "The economy-wide endowment is therefore one unit in each state, so the economy carries **individual** risk and no **aggregate** risk."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ce50e128",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "prob = 0.7\n",
    "\n",
    "Π = np.array([[np.sqrt(prob), 0],\n",
    "              [0, np.sqrt(1 - prob)]])\n",
    "\n",
    "bs = [np.array([np.sqrt(prob) * 5, np.sqrt(1 - prob) * 5]),\n",
    "      np.array([np.sqrt(prob) * 5, np.sqrt(1 - prob) * 5])]\n",
    "\n",
    "es = [np.array([1, 0]),\n",
    "      np.array([0, 1])]\n",
    "\n",
    "EE_AS = ExchangeEconomy(Π, bs, es)\n",
    "p, c_s, μ_s = EE_AS.competitive_equilibrium()\n",
    "\n",
    "print('Competitive equilibrium price vector:', p)\n",
    "print('Competitive equilibrium allocation:', c_s)\n",
    "print('Ratio of state prices p1/p2:', p[0] / p[1])\n",
    "print('Ratio of probabilities λ/(1-λ):', prob / (1 - prob))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2dc65ba0",
   "metadata": {},
   "source": [
    "The relative price of the two Arrow securities equals the odds ratio $ \\lambda/(1-\\lambda) = 0.7/0.3 $, so state-contingent claims trade at **actuarially fair odds**.\n",
    "\n",
    "Each consumer’s consumption is the same in both states: $ c_1 = (0.7, 0.7) $ and $ c_2 = (0.3, 0.3) $.\n",
    "\n",
    "The market in Arrow securities delivers **complete insurance**.\n",
    "\n",
    "No consumer’s consumption depends on which state occurs.\n",
    "\n",
    "Consumption differs across the two consumers because they are not equally rich.\n",
    "\n",
    "The first consumer owns the endowment in the state that occurs with probability $ 0.7 $.\n",
    "\n",
    "That endowment sells for more at equilibrium prices, and the market converts its value into a safe consumption stream."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c3d97d18",
   "metadata": {},
   "source": [
    "### Exercise 53.4\n",
    "\n",
    "Return to the Arrow securities economy just computed.\n",
    "\n",
    "a. Introduce **aggregate** risk by setting $ e_1 = (1.5, 0)^\\top $ while leaving $ e_2 = (0,1)^\\top $, so that the economy-wide endowment is $ 1.5 $ in state $ 1 $ and $ 1 $ in state $ 2 $.\n",
    "\n",
    "Recompute the equilibrium.  Is consumption still state-independent?  Does $ p_1/p_2 $ still equal the odds ratio?\n",
    "\n",
    "b. Explain which kind of risk a complete set of Arrow securities can eliminate and which kind it cannot."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7c4d0cd2",
   "metadata": {},
   "source": [
    "### Solution"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f43d4e8c",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "es = [np.array([1.5, 0]),\n",
    "      np.array([0, 1])]\n",
    "\n",
    "EE_agg = ExchangeEconomy(Π, bs, es)\n",
    "p, c_s, μ_s = EE_agg.competitive_equilibrium()\n",
    "\n",
    "print('aggregate endowment:', sum(es))\n",
    "print('Competitive equilibrium price vector:', p)\n",
    "print('Competitive equilibrium allocation:', [np.round(c, 4) for c in c_s])\n",
    "print(f'p1/p2 = {p[0] / p[1]:.4f},  odds λ/(1-λ) = {prob / (1 - prob):.4f}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b48371b0",
   "metadata": {},
   "source": [
    "Insurance is no longer complete.\n",
    "\n",
    "Consumption is state-dependent for both consumers.\n",
    "\n",
    "Both consume more in state $ 1 $, the state in which the economy as a whole has more.\n",
    "\n",
    "The price ratio falls to $ 2.2037 $, below fair odds, because state $ 1 $ consumption is now abundant and cheap.\n",
    "\n",
    "For part b, a complete set of Arrow securities eliminates individual risk, which concerns who receives the goods.\n",
    "\n",
    "It cannot eliminate aggregate risk, which concerns how many goods the economy has.\n",
    "\n",
    "Consumers share aggregate risk, and it shows up in state-contingent consumption and in state prices that depart from the odds.\n",
    "\n",
    "\n",
    "<a id='rep-consumer'></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e84d750b",
   "metadata": {},
   "source": [
    "## Deducing a representative consumer\n",
    "\n",
    "In the class of multiple consumer economies that we are studying here, it turns out that there\n",
    "exists a single **representative consumer** whose preferences and endowments can be deduced from lists of preferences and endowments for separate individual consumers.\n",
    "\n",
    "Consider a multiple consumer economy with an initial distribution of wealth $ W_i $ satisfying $ \\sum_i W_{i}=0 $.\n",
    "\n",
    "We allow an initial redistribution of wealth.\n",
    "\n",
    "We have the following objects:\n",
    "\n",
    "- The demand curve:  \n",
    "\n",
    "\n",
    "$$\n",
    "c_{i}=\\Pi^{-1}b_{i}-(\\Pi^{\\top}\\Pi)^{-1}\\mu_{i}p\n",
    "$$\n",
    "\n",
    "- The marginal utility of wealth:  \n",
    "\n",
    "\n",
    "$$\n",
    "\\mu_{i}=\\frac{-W_{i}+p^{\\top}\\left(\\Pi^{-1}b_{i}-e_{i}\\right)}{p^{\\top}(\\Pi^{\\top}\\Pi)^{-1}p}\n",
    "$$\n",
    "\n",
    "- Market clearing:  \n",
    "\n",
    "\n",
    "$$\n",
    "\\sum c_{i}=\\sum e_{i}\n",
    "$$\n",
    "\n",
    "Denote aggregate consumption $ \\sum_i c_{i}=c $ and $ \\sum_i \\mu_i = \\mu $.\n",
    "\n",
    "Market clearing requires\n",
    "\n",
    "$$\n",
    "\\Pi^{-1}\\left(\\sum_{i}b_{i}\\right)-(\\Pi^{\\top}\\Pi)^{-1}p\\left(\\sum_{i}\\mu_{i}\\right)=\\sum_{i}e_{i}\n",
    "$$\n",
    "\n",
    "which, after a few steps, leads to\n",
    "\n",
    "$$\n",
    "p=\\mu^{-1}\\left(\\Pi^{\\top}b-\\Pi^{\\top}\\Pi e\\right)\n",
    "$$\n",
    "\n",
    "where\n",
    "\n",
    "$$\n",
    "\\mu = \\sum_i\\mu_{i}\n",
    "    = \\frac{-\\sum_i W_{i} + p^{\\top}\\left(\\Pi^{-1}b-e\\right)}{p^{\\top}(\\Pi^{\\top}\\Pi)^{-1}p}\n",
    "    = \\frac{p^{\\top}\\left(\\Pi^{-1}b-e\\right)}{p^{\\top}(\\Pi^{\\top}\\Pi)^{-1}p}\n",
    "$$\n",
    "\n",
    "Here the wealth transfers have dropped out of the sum because $ \\sum_i W_{i}=0 $.\n",
    "\n",
    "Now consider the representative consumer economy specified above.\n",
    "\n",
    "Denote the marginal utility of wealth of the representative consumer by $ \\tilde{\\mu} $.\n",
    "\n",
    "The demand function is\n",
    "\n",
    "$$\n",
    "c=\\Pi^{-1}b-(\\Pi^{\\top}\\Pi)^{-1}\\tilde{\\mu} p\n",
    "$$\n",
    "\n",
    "Substituting this into the representative consumer’s budget constraint $ p^{\\top}(c-e)=0 $, which contains no wealth term because $ \\sum_i W_{i}=0 $, gives\n",
    "\n",
    "$$\n",
    "\\tilde{\\mu}=\\frac{p^{\\top}\\left(\\Pi^{-1}b-e\\right)}{p^{\\top}(\\Pi^{\\top}\\Pi)^{-1}p}\n",
    "$$\n",
    "\n",
    "In an equilibrium $ c=e $, so\n",
    "\n",
    "$$\n",
    "p=\\tilde{\\mu}^{-1}(\\Pi^{\\top}b-\\Pi^{\\top}\\Pi e)\n",
    "$$\n",
    "\n",
    "Thus, we have  verified that, up to the choice of a numeraire in which to express absolute prices, the price\n",
    "vector in our representative consumer economy is the same as that in an underlying  economy with multiple consumers.\n",
    "\n",
    ">**Note**\n",
    ">\n",
    ">Aggregation worked because all of our consumers share the same matrix $ \\Pi $, which gives every demand curve a common slope in wealth.\n",
    "\n",
    "Preferences with this property take the **Gorman form**.\n",
    "\n",
    "Without it, the equilibrium price vector would depend on the distribution of wealth, and no representative consumer would exist.\n",
    "\n",
    "The representative consumer computes prices.\n",
    "\n",
    "It tells us nothing about how goods are distributed among individual consumers, and its utility is not a social welfare function."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8bb247ec",
   "metadata": {},
   "source": [
    "## Negishi weights and the first welfare theorem\n",
    "\n",
    "[Supply and Demand with Many Goods](https://intro.quantecon.org/supply_demand_multiple_goods.html) verified a version of the **first welfare theorem**: a competitive equilibrium quantity vector solves a planning problem.\n",
    "\n",
    "That lecture contained a single consumer, so its planner had nobody to choose among.\n",
    "\n",
    "A planner with many consumers must attach a weight to each of them.\n",
    "\n",
    "Let $ \\theta_i > 0 $ be the weight that a planner attaches to consumer $ i $ and consider the planning problem\n",
    "\n",
    "$$\n",
    "\\max_{\\{c_i\\}} \\ \\sum_i \\theta_i \\left(-\\frac{1}{2}\\right)(\\Pi c_{i}-b_{i})^{\\top}(\\Pi c_{i}-b_{i})\n",
    "\\quad \\text{subject to} \\quad \\sum_i c_{i}=\\sum_i e_{i}\n",
    "$$\n",
    "\n",
    "Form the Lagrangian\n",
    "\n",
    "$$\n",
    "L = \\sum_i \\theta_i \\left(-\\frac{1}{2}\\right)(\\Pi c_{i}-b_{i})^{\\top}(\\Pi c_{i}-b_{i})\n",
    "    + \\eta^{\\top}\\left(\\sum_i e_{i}-\\sum_i c_{i}\\right)\n",
    "$$\n",
    "\n",
    "where $ \\eta $ is a vector of Lagrange multipliers on the resource constraint.\n",
    "\n",
    "First-order conditions with respect to $ c_i $ are\n",
    "\n",
    "$$\n",
    "-\\theta_{i}\\Pi^{\\top}(\\Pi c_{i}-b_{i})-\\eta=0\n",
    "$$\n",
    "\n",
    "so that\n",
    "\n",
    "\n",
    "<a id='equation-eq-negishi-demand'></a>\n",
    "$$\n",
    "c_{i}=\\Pi^{-1}b_{i}-(\\Pi^{\\top}\\Pi)^{-1}\\frac{\\eta}{\\theta_{i}} \\tag{53.5}\n",
    "$$\n",
    "\n",
    "Now compare [(53.5)](#equation-eq-negishi-demand) with the competitive equilibrium demand curve\n",
    "\n",
    "$$\n",
    "c_{i}=\\Pi^{-1}b_{i}-(\\Pi^{\\top}\\Pi)^{-1}\\mu_{i}p\n",
    "$$\n",
    "\n",
    "The two coincide when\n",
    "\n",
    "$$\n",
    "\\theta_{i}=\\frac{1}{\\mu_{i}} \\quad \\text{and} \\quad \\eta = p\n",
    "$$\n",
    "\n",
    "A competitive equilibrium allocation solves a planning problem whose welfare weights are the reciprocals of the consumers’ marginal utilities of wealth.\n",
    "\n",
    "[Takashi Negishi](https://en.wikipedia.org/wiki/Takashi_Negishi) introduced weights of this kind, and they carry his name.\n",
    "\n",
    "A consumer who is poor at equilibrium prices has a high $ \\mu_i $, and a planner attaches a low weight $ \\theta_i $ to them to justify the market outcome.\n",
    "\n",
    "The multiplier $ \\eta $ on the resource constraint equals the equilibrium price vector.\n",
    "\n",
    "Shadow prices of scarce resources are market prices, as [Linear Programming](https://intro.quantecon.org/lp_intro.html) discusses."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0824134a",
   "metadata": {},
   "source": [
    "## Exercise 53.5\n",
    "\n",
    "Verify these claims numerically.\n",
    "\n",
    "a. Write a function that solves the planner’s problem for arbitrary weights $ \\theta_i $ by combining [(53.5)](#equation-eq-negishi-demand) with the resource constraint.\n",
    "\n",
    "b. Check that setting $ \\theta_i = 1/\\mu_i $ reproduces the competitive equilibrium allocation, and that $ \\eta $ is proportional to $ p $.\n",
    "\n",
    "Do this both for the two-person economy in which the second good is scarce and for the Arrow securities economy.\n",
    "\n",
    "c. Now set equal weights $ \\theta_1 = \\theta_2 $ and describe how the planner’s allocation differs from the competitive one."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "79009776",
   "metadata": {},
   "source": [
    "## Solution"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e207843c",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "def planner_allocation(Π, bs, es, θs):\n",
    "    \"\"\"\n",
    "    Solve the planner's problem for welfare weights θs\n",
    "    \"\"\"\n",
    "    slope_dc = inv(Π.T @ Π)\n",
    "    Π_inv = inv(Π)\n",
    "    e = sum(es)\n",
    "\n",
    "    # the resource constraint pins down the multiplier η\n",
    "    A = slope_dc * sum(1 / θ for θ in θs)\n",
    "    rhs = sum(Π_inv @ b for b in bs) - e\n",
    "    η = np.linalg.solve(A, rhs)\n",
    "\n",
    "    c_s = [Π_inv @ bs[i] - slope_dc @ η / θs[i] for i in range(len(bs))]\n",
    "    return η, c_s"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "268c84e2",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "# the two-person economy in which the second good is scarce\n",
    "Π_1 = np.array([[1, 0],\n",
    "                [0, 1]])\n",
    "bs_1 = [np.array([6, 5]), np.array([5, 6])]\n",
    "es_1 = [np.array([1.25, 0.75]), np.array([1.25, 0.75])]\n",
    "\n",
    "# the Arrow securities economy\n",
    "prob = 0.7\n",
    "Π_2 = np.array([[np.sqrt(prob), 0],\n",
    "                [0, np.sqrt(1 - prob)]])\n",
    "bs_2 = [np.array([np.sqrt(prob) * 5, np.sqrt(1 - prob) * 5]),\n",
    "        np.array([np.sqrt(prob) * 5, np.sqrt(1 - prob) * 5])]\n",
    "es_2 = [np.array([1, 0]), np.array([0, 1])]\n",
    "\n",
    "economies = [('scarce good 2', Π_1, bs_1, es_1),\n",
    "             ('Arrow securities', Π_2, bs_2, es_2)]\n",
    "\n",
    "for name, Π_i, bs_i, es_i in economies:\n",
    "    p, c_s, μ_s = ExchangeEconomy(Π_i, bs_i, es_i).competitive_equilibrium()\n",
    "    η, c_pl = planner_allocation(Π_i, bs_i, es_i, θs=[1 / μ for μ in μ_s])\n",
    "\n",
    "    print(name)\n",
    "    print(f'  competitive allocation : {[np.round(c, 4) for c in c_s]}')\n",
    "    print(f'  planner allocation     : {[np.round(c, 4) for c in c_pl]}')\n",
    "    print(f'  p                      : {np.round(p, 4)}')\n",
    "    print(f'  η / η[0]               : {np.round(η / η[0], 4)}')\n",
    "    print(f'  allocations agree      : {np.allclose(c_s, c_pl)}\\n')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0a1863ba",
   "metadata": {},
   "source": [
    "Setting $ \\theta_i = 1/\\mu_i $ reproduces the competitive allocation, and the normalized multiplier $ \\eta $ equals the competitive price vector.\n",
    "\n",
    "Now give the two consumers equal weights."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "950963e6",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "for name, Π_i, bs_i, es_i in economies:\n",
    "    η, c_pl = planner_allocation(Π_i, bs_i, es_i, θs=[1, 1])\n",
    "    print(f'{name}: equal-weight allocation = {[np.round(c, 4) for c in c_pl]}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc9aa224",
   "metadata": {},
   "source": [
    "The equal-weight planner disregards who owns what.\n",
    "\n",
    "In the Arrow securities economy it gives each consumer $ (0.5, 0.5) $, an equal share of the aggregate endowment in each state.\n",
    "\n",
    "The market delivers $ (0.7, 0.7) $ and $ (0.3, 0.3) $ and respects each consumer’s ownership of their state-contingent endowment.\n",
    "\n",
    "A lump-sum redistribution of wealth would decentralize the equal-weight allocation as a competitive equilibrium, by the second welfare theorem.\n",
    "\n",
    "The first welfare theorem makes the market outcome a planner’s outcome for some weights.\n",
    "\n",
    "The second welfare theorem turns a planner’s outcome for any weights into a market outcome, given the right transfers."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8798dda7",
   "metadata": {},
   "source": [
    "## Concluding remarks\n",
    "\n",
    "This lecture studied a competitive equilibrium of a pure exchange economy whose consumers differ in their preferences and their endowments.\n",
    "\n",
    "The equilibrium price vector depends on individual consumers only through the **aggregate** bliss point and the **aggregate** endowment.\n",
    "\n",
    "A single representative consumer reproduces the equilibrium prices of an economy with many consumers.\n",
    "\n",
    "A competitive equilibrium allocation solves a planning problem whose welfare weights are the reciprocals of the consumers’ marginal utilities of wealth, an instance of the first welfare theorem.\n",
    "\n",
    "Redistributing wealth before trade changes the allocation and leaves prices unchanged, an instance of the second welfare theorem.\n",
    "\n",
    "The same apparatus describes borrowing and lending when goods are dated, and insurance when goods are state-contingent.\n",
    "\n",
    "A competitive equilibrium delivers complete consumption smoothing when $ \\beta R = 1 $ and complete insurance when no aggregate risk exists.\n",
    "\n",
    "Neither result survives variation in the aggregate endowment across dates or across states.\n",
    "\n",
    "Consumers share aggregate risk and aggregate growth; they cannot eliminate them."
   ]
  }
 ],
 "metadata": {
  "date": 1795846200.7663357,
  "filename": "supply_demand_heterogeneity.md",
  "kernelspec": {
   "display_name": "Python",
   "language": "python3",
   "name": "python3"
  },
  "title": "Market Equilibrium with Heterogeneity"
 },
 "nbformat": 4,
 "nbformat_minor": 5
}