{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "94e082a2",
   "metadata": {},
   "source": [
    "$$\n",
    "\\newcommand{\\argmax}{arg\\,max}\n",
    "\\newcommand{\\argmin}{arg\\,min}\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "21c6e4e0",
   "metadata": {},
   "source": [
    "\n",
    "<a id='supply-demand-multiple-goods'></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4af6c934",
   "metadata": {},
   "source": [
    "# Supply and Demand with Many Goods"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9f1cf467",
   "metadata": {},
   "source": [
    "## Overview\n",
    "\n",
    "In a [previous lecture](https://intro.quantecon.org/intro_supply_demand.html) we studied supply, demand\n",
    "and welfare in a market with a single consumption good.\n",
    "\n",
    "In this lecture, we study a setting with $ n $ goods and $ n $ corresponding prices.\n",
    "\n",
    "Key infrastructure concepts that we’ll encounter in this lecture are\n",
    "\n",
    "- inverse demand curves  \n",
    "- marginal utilities of wealth  \n",
    "- inverse supply curves  \n",
    "- consumer surplus  \n",
    "- producer surplus  \n",
    "- social welfare as a sum of consumer and producer surpluses  \n",
    "- competitive equilibrium  \n",
    "\n",
    "\n",
    "We will provide a version of the [first fundamental welfare theorem](https://en.wikipedia.org/wiki/Fundamental_theorems_of_welfare_economics), which was formulated by\n",
    "\n",
    "- [Leon Walras](https://en.wikipedia.org/wiki/L%C3%A9on_Walras)  \n",
    "- [Francis Ysidro Edgeworth](https://en.wikipedia.org/wiki/Francis_Ysidro_Edgeworth)  \n",
    "- [Vilfredo Pareto](https://en.wikipedia.org/wiki/Vilfredo_Pareto)  \n",
    "\n",
    "\n",
    "Important extensions to the key ideas were obtained by\n",
    "\n",
    "- [Abba Lerner](https://en.wikipedia.org/wiki/Abba_P._Lerner)  \n",
    "- [Harold Hotelling](https://en.wikipedia.org/wiki/Harold_Hotelling)  \n",
    "- [Paul Samuelson](https://en.wikipedia.org/wiki/Paul_Samuelson)  \n",
    "- [Kenneth Arrow](https://en.wikipedia.org/wiki/Kenneth_Arrow)  \n",
    "- [Gérard Debreu](https://en.wikipedia.org/wiki/G%C3%A9rard_Debreu)  \n",
    "\n",
    "\n",
    "We shall describe two classic welfare theorems:\n",
    "\n",
    "- **first welfare theorem:** for a given distribution of wealth among consumers, a competitive  equilibrium  allocation of goods solves a  social planning problem.  \n",
    "- **second welfare theorem:** An allocation of goods to consumers that solves a social planning problem can be supported by a competitive equilibrium with an appropriate initial distribution of  wealth.  \n",
    "\n",
    "\n",
    "This lecture studies a single representative consumer, so the distribution of wealth plays no role in it.\n",
    "\n",
    "We verify a version of the **first** welfare theorem only.\n",
    "\n",
    "[Market Equilibrium with Heterogeneity](https://intro.quantecon.org/supply_demand_heterogeneity.html) takes up the distribution of wealth and both welfare theorems.\n",
    "\n",
    "As usual, we start by importing some Python modules."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1d8d0894",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "# import some packages\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from scipy.linalg import inv"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3cf1c300",
   "metadata": {},
   "source": [
    "## Formulas from linear algebra\n",
    "\n",
    "[Linear Equations and Matrix Algebra](https://intro.quantecon.org/linear_equations.html) describes tools for solving the linear systems that appear in this lecture and in [Market Equilibrium with Heterogeneity](https://intro.quantecon.org/supply_demand_heterogeneity.html).\n",
    "\n",
    "We shall apply formulas from linear algebra that\n",
    "\n",
    "- differentiate an inner product with respect to each vector  \n",
    "- differentiate a product of a matrix and a vector with respect to the vector  \n",
    "- differentiate a quadratic form in a vector with respect to the vector  \n",
    "\n",
    "\n",
    "Where $ a $ is an $ n \\times 1 $ vector, $ A $ is an $ n \\times n $ matrix, and $ x $ is an $ n \\times 1 $ vector:\n",
    "\n",
    "$$\n",
    "\\frac{\\partial a^\\top x }{\\partial x} = \\frac{\\partial x^\\top a }{\\partial x} = a\n",
    "$$\n",
    "\n",
    "$$\n",
    "\\frac{\\partial A x} {\\partial x} = A\n",
    "$$\n",
    "\n",
    "$$\n",
    "\\frac{\\partial x^\\top A x}{\\partial x} = (A + A^\\top)x\n",
    "$$\n",
    "\n",
    ">**Note**\n",
    ">\n",
    ">The first and third formulas differentiate a scalar with respect to a vector and return $ n \\times 1 $ vectors.\n",
    "\n",
    "The second differentiates a vector with respect to a vector and returns an $ n \\times n $ matrix.\n",
    "\n",
    "We use the first and third formulas below."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9ee7238e",
   "metadata": {},
   "source": [
    "## From utility function to demand curve\n",
    "\n",
    "Our study of consumers will use the following primitives\n",
    "\n",
    "- $ \\Pi $, an $ m \\times n $ matrix,  \n",
    "- $ b $, an $ m \\times 1 $ vector of bliss points,  \n",
    "- $ e $, an $ n \\times 1 $ vector of endowments  \n",
    "\n",
    "\n",
    "We will analyze endogenous objects $ c $ and $ p $, where\n",
    "\n",
    "- $ c $ is an $ n \\times 1 $ vector of consumptions of various goods,  \n",
    "- $ p $ is an $ n \\times 1 $ vector of prices  \n",
    "\n",
    "\n",
    "The matrix $ \\Pi $ describes a consumer’s willingness to substitute one good for every other good.\n",
    "\n",
    "We assume that $ \\Pi $ has linearly independent columns, which implies that $ \\Pi^\\top \\Pi $ is a positive definite matrix.\n",
    "\n",
    "- it follows that $ \\Pi^\\top \\Pi $ has an inverse.  \n",
    "\n",
    "\n",
    "In all of our examples we shall set $ m = n $ and take $ \\Pi $ to be invertible, so that $ (\\Pi^\\top \\Pi)^{-1} \\Pi^\\top = \\Pi^{-1} $.\n",
    "\n",
    "The matrix $ -\\mu (\\Pi^\\top \\Pi)^{-1} $ gives the slopes of demand curves for $ c $ with respect to $ p $, holding fixed the marginal utility of wealth $ \\mu $ that we define below:\n",
    "\n",
    "$$\n",
    "\\frac{\\partial c } {\\partial p} = - \\mu (\\Pi^\\top \\Pi)^{-1}\n",
    "$$\n",
    "\n",
    "$ (\\Pi^\\top \\Pi)^{-1} $ is positive definite, so its diagonal elements are positive and the diagonal elements of $ -\\mu (\\Pi^\\top \\Pi)^{-1} $ are negative.\n",
    "\n",
    "Each good’s own-price demand curve slopes downward.\n",
    "\n",
    "The off-diagonal cross-price effects take either sign.\n",
    "\n",
    "A demand curve that holds $ \\mu $ fixed is a **Frisch** demand curve, named after [Ragnar Frisch](https://en.wikipedia.org/wiki/Ragnar_Frisch).\n",
    "\n",
    "A consumer faces $ p $ as a price taker and chooses $ c $ to maximize the utility function\n",
    "\n",
    "\n",
    "<a id='equation-eq-old0'></a>\n",
    "$$\n",
    "- \\frac{1}{2} (\\Pi c -b) ^\\top (\\Pi c -b ) \\tag{52.1}\n",
    "$$\n",
    "\n",
    "subject to the budget constraint\n",
    "\n",
    "\n",
    "<a id='equation-eq-old2'></a>\n",
    "$$\n",
    "p^\\top (c -e ) = 0 \\tag{52.2}\n",
    "$$\n",
    "\n",
    "We shall specify examples in which $ \\Pi $ and $ b $ are such that it typically happens that\n",
    "\n",
    "\n",
    "<a id='equation-eq-bversusc'></a>\n",
    "$$\n",
    "\\Pi c \\ll b \\tag{52.3}\n",
    "$$\n",
    "\n",
    "This means that the consumer has much less of each good than they want.\n",
    "\n",
    "The deviation in [(52.3)](#equation-eq-bversusc) will ultimately assure us that competitive equilibrium prices are positive, provided that $ \\Pi $ has non-negative entries, as it does in all of our examples."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "351231d3",
   "metadata": {},
   "source": [
    "### Demand curve implied by constrained utility maximization\n",
    "\n",
    "For now, we assume that the budget constraint is [(52.2)](#equation-eq-old2).\n",
    "\n",
    "So we’ll be deriving what is known as  a **Marshallian** demand curve.\n",
    "\n",
    "Our aim is to maximize [(52.1)](#equation-eq-old0) subject to [(52.2)](#equation-eq-old2).\n",
    "\n",
    "Form a Lagrangian\n",
    "\n",
    "$$\n",
    "L = - \\frac{1}{2} (\\Pi c -b)^\\top (\\Pi c -b ) + \\mu [p^\\top (e-c)]\n",
    "$$\n",
    "\n",
    "where $ \\mu $ is a Lagrange multiplier that is often called a **marginal utility of wealth**.\n",
    "\n",
    "The consumer chooses $ c $ to maximize $ L $ and $ \\mu $ to minimize it.\n",
    "\n",
    "First-order conditions for $ c $ are\n",
    "\n",
    "$$\n",
    "\\frac{\\partial L} {\\partial c}\n",
    "    = - \\Pi^\\top \\Pi c + \\Pi^\\top b - \\mu p = 0\n",
    "$$\n",
    "\n",
    "so that, given $ \\mu $, the consumer chooses\n",
    "\n",
    "\n",
    "<a id='equation-eq-old3'></a>\n",
    "$$\n",
    "c = (\\Pi^\\top \\Pi )^{-1}(\\Pi^\\top b -  \\mu p ) \\tag{52.4}\n",
    "$$\n",
    "\n",
    "Substituting [(52.4)](#equation-eq-old3) into budget constraint [(52.2)](#equation-eq-old2) and solving for $ \\mu $ gives\n",
    "\n",
    "\n",
    "<a id='equation-eq-old4'></a>\n",
    "$$\n",
    "\\mu(p,e) = \\frac{p^\\top ( \\Pi^\\top \\Pi )^{-1} \\Pi^\\top b - p^\\top e}{p^\\top (\\Pi^\\top \\Pi )^{-1} p} \\tag{52.5}\n",
    "$$\n",
    "\n",
    "Equation [(52.5)](#equation-eq-old4) tells how marginal utility of wealth depends on the endowment vector $ e $ and the price vector $ p $.\n",
    "\n",
    ">**Note**\n",
    ">\n",
    ">Equation [(52.5)](#equation-eq-old4) is a consequence of imposing $ p^\\top (c - e) = 0 $."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "644d258c",
   "metadata": {},
   "source": [
    "## Marshallian, Hicksian, and Frisch demand curves\n",
    "\n",
    "Sometimes we’ll use budget constraint [(52.2)](#equation-eq-old2) in situations in which a consumer’s endowment vector $ e $ is their **only** source of income.\n",
    "\n",
    "Other times we’ll instead assume that the consumer has another source of income (positive or negative) and write their budget constraint as\n",
    "\n",
    "\n",
    "<a id='equation-eq-old2p'></a>\n",
    "$$\n",
    "p ^\\top (c -e ) = w \\tag{52.6}\n",
    "$$\n",
    "\n",
    "where $ w $ is measured in “dollars” (or some other **numeraire**) and component $ p_i $ of the price vector is measured in dollars per unit of good $ i $.\n",
    "\n",
    "Whether the consumer’s budget constraint is [(52.2)](#equation-eq-old2) or [(52.6)](#equation-eq-old2p) and whether we take $ w $ as a free parameter or instead as an endogenous variable will affect the consumer’s marginal utility of wealth.\n",
    "\n",
    "Consequently, how we set $ \\mu $ determines which of the following three demand curves we are constructing:\n",
    "\n",
    "- a **Marshallian** demand curve, as when we use [(52.2)](#equation-eq-old2) and solve for $ \\mu $ using equation [(52.5)](#equation-eq-old4) above  \n",
    "- a **Frisch** demand curve, as when we treat $ \\mu $ as a fixed parameter and solve [(52.6)](#equation-eq-old2p) for $ w $  \n",
    "- a **Hicksian** demand curve, as when we hold the consumer’s *utility* fixed and let $ w $ be whatever is required to attain it  \n",
    "\n",
    "\n",
    "These three demand curves contemplate different mental experiments.\n",
    "\n",
    "For a Marshallian demand curve, hypothetical changes in a price vector have both **substitution** and **income** effects\n",
    "\n",
    "- income effects are consequences of changes in $ p^\\top e $ associated with the change in the price vector  \n",
    "\n",
    "\n",
    "For a Frisch demand curve, the marginal utility of wealth $ \\mu $ is frozen while $ w $ adjusts to finance the resulting consumption bundle\n",
    "\n",
    "- differentiating [(52.4)](#equation-eq-old3) while holding $ \\mu $ fixed gives the slopes $ \\frac{\\partial c}{\\partial p} = - \\mu (\\Pi^\\top \\Pi)^{-1} $ that we met above  \n",
    "\n",
    "\n",
    "For a Hicksian demand curve, $ w $ instead adjusts to keep **utility** constant, which is why a Hicksian demand curve is often called a **compensated** demand curve\n",
    "\n",
    "- the compensation is designed to disarm the income (or wealth) effect associated with a price change  \n",
    "\n",
    "\n",
    ">**Note**\n",
    ">\n",
    ">Frisch and Hicksian demand curves are distinct objects.\n",
    "\n",
    "A Hicksian demand curve minimizes expenditure $ p^\\top c $ subject to attaining a given utility level, so scaling all prices by a common positive factor leaves it unchanged.\n",
    "\n",
    "Its matrix of slopes $ S $ satisfies $ S p = 0 $.\n",
    "\n",
    "The Frisch slopes $ -\\mu (\\Pi^\\top \\Pi)^{-1} $ do not.\n",
    "\n",
    "Freezing the marginal utility of wealth differs from freezing utility.\n",
    "\n",
    "In the endowment economy below, the budget constraint [(52.2)](#equation-eq-old2) holds and $ \\mu $ normalizes the price level.\n",
    "\n",
    "In the production economy below, no budget constraint restrains the consumer, so $ \\mu $ is a free parameter of a Frisch inverse demand curve.\n",
    "\n",
    "The planning problem there uses that free parameter as the weight that a planner attaches to the consumer."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "023eadc3",
   "metadata": {},
   "source": [
    "## Endowment economy\n",
    "\n",
    "We now study a pure-exchange economy, or what is sometimes called an endowment economy.\n",
    "\n",
    "Consider a single-consumer, multiple-goods economy without production.\n",
    "\n",
    "The only source of goods is the single consumer’s endowment vector $ e $.\n",
    "\n",
    "A competitive equilibrium price vector induces the consumer to choose $ c=e $.\n",
    "\n",
    "This implies that the equilibrium price vector satisfies\n",
    "\n",
    "$$\n",
    "p = \\mu^{-1} (\\Pi^\\top b - \\Pi^\\top \\Pi e)\n",
    "$$\n",
    "\n",
    "In the present case, where we have imposed the budget constraint in the form [(52.2)](#equation-eq-old2), we are free to normalize the price vector by setting the marginal utility of wealth $ \\mu =1 $ (or any other value for that matter).\n",
    "\n",
    "This amounts to choosing a common unit (or numeraire) in which prices of all goods are expressed.\n",
    "\n",
    "(Doubling all prices will affect neither quantities nor relative prices.)\n",
    "\n",
    "We’ll set $ \\mu=1 $."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "92546fbc",
   "metadata": {},
   "source": [
    "## Exercise 52.1\n",
    "\n",
    "Verify that setting $ \\mu=1 $ in [(52.4)](#equation-eq-old3) implies that formula [(52.5)](#equation-eq-old4) is satisfied."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e6deabb3",
   "metadata": {},
   "source": [
    "## Solution\n",
    "\n",
    "Setting $ \\mu = 1 $ in [(52.4)](#equation-eq-old3) and imposing the equilibrium condition $ c = e $ gives the price vector\n",
    "\n",
    "$$\n",
    "p = \\Pi^\\top b - \\Pi^\\top \\Pi e\n",
    "$$\n",
    "\n",
    "Multiplying this by $ (\\Pi^\\top \\Pi)^{-1} $ and rearranging yields the useful identity\n",
    "\n",
    "$$\n",
    "(\\Pi^\\top \\Pi)^{-1} \\Pi^\\top b - e = (\\Pi^\\top \\Pi)^{-1} p\n",
    "$$\n",
    "\n",
    "Now substitute this into the numerator of [(52.5)](#equation-eq-old4):\n",
    "\n",
    "$$\n",
    "p^\\top \\left[ (\\Pi^\\top \\Pi)^{-1} \\Pi^\\top b - e \\right]\n",
    "    = p^\\top (\\Pi^\\top \\Pi)^{-1} p\n",
    "$$\n",
    "\n",
    "The numerator of [(52.5)](#equation-eq-old4) therefore equals its denominator, so $ \\mu(p,e) = 1 $, as required."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3b746eee",
   "metadata": {},
   "source": [
    "## Exercise 52.2\n",
    "\n",
    "Verify that setting  $ \\mu=2 $ in [(52.4)](#equation-eq-old3) also implies that formula\n",
    "[(52.5)](#equation-eq-old4) is satisfied."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "69ddf0b6",
   "metadata": {},
   "source": [
    "## Solution\n",
    "\n",
    "Setting $ \\mu = 2 $ in [(52.4)](#equation-eq-old3) and again imposing $ c = e $ gives\n",
    "\n",
    "$$\n",
    "p = \\frac{1}{2}\\left(\\Pi^\\top b - \\Pi^\\top \\Pi e\\right)\n",
    "$$\n",
    "\n",
    "so that the identity used in the previous exercise becomes\n",
    "\n",
    "$$\n",
    "(\\Pi^\\top \\Pi)^{-1} \\Pi^\\top b - e = 2 (\\Pi^\\top \\Pi)^{-1} p\n",
    "$$\n",
    "\n",
    "The numerator of [(52.5)](#equation-eq-old4) is now $ 2 p^\\top (\\Pi^\\top \\Pi)^{-1} p $, which is twice the denominator, so $ \\mu(p,e) = 2 $.\n",
    "\n",
    "The same argument works for any $ \\mu > 0 $.\n",
    "\n",
    "Doubling $ \\mu $ halves the equilibrium price vector and leaves relative prices and the allocation $ c = e $ unchanged.\n",
    "\n",
    "$ \\mu $ normalizes the price level.\n",
    "\n",
    "Here is a class that computes competitive equilibria for our economy.\n",
    "\n",
    ">**Note**\n",
    ">\n",
    ">Our code forms matrix inverses explicitly with `inv`, so that each line of code mirrors a line of algebra.\n",
    "\n",
    "For larger problems, solve the linear system directly with `numpy.linalg.solve`, as in [Linear Equations and Matrix Algebra](https://intro.quantecon.org/linear_equations.html)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4e7c1b7f",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "class ExchangeEconomy:\n",
    "    \n",
    "    def __init__(self, \n",
    "                 Π, \n",
    "                 b, \n",
    "                 e,\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",
    "            b (list):  the consumer's bliss point\n",
    "            e (list):  the consumer's endowment\n",
    "            thres (float): a threshold to check the b >> Π e condition\n",
    "        \"\"\"\n",
    "\n",
    "        # check non-satiation\n",
    "        if np.min(b / np.max(Π @ e)) <= thres:\n",
    "            raise Exception('set bliss points further away')\n",
    "\n",
    "\n",
    "        self.Π, self.b, self.e = Π, b, e\n",
    "\n",
    "    \n",
    "    def competitive_equilibrium(self):\n",
    "        \"\"\"\n",
    "        Compute the competitive equilibrium prices and allocation\n",
    "        \"\"\"\n",
    "        Π, b, e = self.Π, self.b, self.e\n",
    "\n",
    "        # compute price vector with μ=1\n",
    "        p = Π.T @ b - Π.T @ Π @ e\n",
    "        \n",
    "        # compute consumption vector\n",
    "        slope_dc = inv(Π.T @ Π)\n",
    "        Π_inv = inv(Π)\n",
    "        c = Π_inv @ b - slope_dc @ p\n",
    "\n",
    "        if any(c < 0):\n",
    "            print('allocation: ', c)\n",
    "            raise Exception('negative allocation: equilibrium does not exist')\n",
    "\n",
    "        return p, c"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b15866a4",
   "metadata": {},
   "source": [
    "## Dynamics and risk as special cases\n",
    "\n",
    "Special cases of our $ n $-good pure exchange model can be created to represent\n",
    "\n",
    "- **dynamics** — by putting different dates on different commodities  \n",
    "- **risk** — by interpreting delivery of goods as being contingent on states of the world whose realizations are described by a *known probability distribution*  \n",
    "\n",
    "\n",
    "Let’s illustrate how."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6865d041",
   "metadata": {},
   "source": [
    "### Dynamics\n",
    "\n",
    "Suppose that we want to represent a utility function\n",
    "\n",
    "$$\n",
    "- \\frac{1}{2} [(c_1 - b_1)^2 + \\beta (c_2 - b_2)^2]\n",
    "$$\n",
    "\n",
    "where $ \\beta \\in (0,1) $ is a discount factor, $ c_1 $ is consumption at time $ 1 $ and $ c_2 $ is consumption at time 2.\n",
    "\n",
    "To capture this with our quadratic utility function [(52.1)](#equation-eq-old0), set\n",
    "\n",
    "$$\n",
    "\\Pi = \\begin{bmatrix} 1 & 0 \\cr\n",
    "         0 & \\sqrt{\\beta} \\end{bmatrix}\n",
    "$$\n",
    "\n",
    "$$\n",
    "e = \\begin{bmatrix} e_1 \\cr e_2 \\end{bmatrix}\n",
    "$$\n",
    "\n",
    "and\n",
    "\n",
    "$$\n",
    "b = \\begin{bmatrix} b_1 \\cr \\sqrt{\\beta} b_2\n",
    "\\end{bmatrix}\n",
    "$$\n",
    "\n",
    "The budget constraint [(52.2)](#equation-eq-old2) becomes\n",
    "\n",
    "$$\n",
    "p_1 c_1 + p_2 c_2 = p_1 e_1 + p_2 e_2\n",
    "$$\n",
    "\n",
    "The left side is the **discounted present value** of consumption.\n",
    "\n",
    "The right side is the **discounted present value** of the consumer’s endowment.\n",
    "\n",
    "The relative price  $ \\frac{p_1}{p_2} $ has units of time $ 2 $ goods per unit of time $ 1 $ goods.\n",
    "\n",
    "Consequently,\n",
    "\n",
    "$$\n",
    "(1+r) := R := \\frac{p_1}{p_2}\n",
    "$$\n",
    "\n",
    "is the **gross interest rate** and $ r $ is the **net interest rate**.\n",
    "\n",
    "[Present Values](https://intro.quantecon.org/pv.html) computes present values by discounting future payoffs with a discount factor $ \\delta \\in (0,1) $.\n",
    "\n",
    "Here $ p_2 / p_1 = R^{-1} $ is that discount factor, determined inside the model as the relative price of goods at two dates.\n",
    "\n",
    "[Consumption Smoothing](https://intro.quantecon.org/cons_smooth.html) studies a consumer who smooths consumption completely when $ \\beta R = 1 $, a condition that Milton Friedman and Robert Hall assumed.\n",
    "\n",
    "An exercise below derives $ R = \\beta^{-1} $ from equilibrium when the endowment is the same at both dates.\n",
    "\n",
    "Here is an example."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "61a98d61",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "beta = 0.95\n",
    "\n",
    "Π = np.array([[1, 0],\n",
    "              [0, np.sqrt(beta)]])\n",
    "\n",
    "b = np.array([5, np.sqrt(beta) * 5])\n",
    "\n",
    "e = np.array([1, 1])\n",
    "\n",
    "dynamics = ExchangeEconomy(Π, b, e)\n",
    "p, c = dynamics.competitive_equilibrium()\n",
    "\n",
    "print('Competitive equilibrium price vector:', p)\n",
    "print('Competitive equilibrium allocation:', c)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5ff2d17d",
   "metadata": {},
   "source": [
    "### Exercise 52.3\n",
    "\n",
    "Consider the dynamic interpretation above, with $ \\Pi = \\begin{bmatrix} 1 & 0 \\\\ 0 & \\sqrt{\\beta}\\end{bmatrix} $,\n",
    "$ b = \\begin{bmatrix} \\bar b \\\\ \\sqrt{\\beta}\\,\\bar b \\end{bmatrix} $ and $ e = \\begin{bmatrix} e_1 \\\\ e_2\\end{bmatrix} $.\n",
    "\n",
    "a. Show analytically that the gross interest rate is\n",
    "\n",
    "$$\n",
    "R = \\frac{p_1}{p_2} = \\frac{1}{\\beta} \\cdot \\frac{\\bar b - e_1}{\\bar b - e_2}\n",
    "$$\n",
    "\n",
    "and hence that $ R = \\beta^{-1} $ whenever the endowment is flat, that is, whenever $ e_1 = e_2 $.\n",
    "\n",
    "b. Let $ e_2 = (1+g) e_1 $ with $ e_1 = 1 $, $ \\bar b = 5 $ and $ \\beta = 0.95 $.\n",
    "\n",
    "Compute $ R $ numerically for $ g \\in [-0.2, 0.2] $ and plot it against $ g $, marking $ \\beta^{-1} $ with a dashed line.\n",
    "\n",
    "c. Explain, in terms of the consumer’s desire to smooth consumption, why $ R $ rises with $ g $."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ad00ae9d",
   "metadata": {},
   "source": [
    "### Solution\n",
    "\n",
    "For part a, the equilibrium price vector is $ p = \\Pi^\\top b - \\Pi^\\top \\Pi e $.\n",
    "\n",
    "With this $ \\Pi $ and $ b $,\n",
    "\n",
    "$$\n",
    "\\Pi^\\top b = \\begin{bmatrix} \\bar b \\cr \\beta \\bar b \\end{bmatrix}, \\qquad\n",
    "\\Pi^\\top \\Pi e = \\begin{bmatrix} e_1 \\cr \\beta e_2 \\end{bmatrix}, \\qquad \\text{so} \\qquad\n",
    "p = \\begin{bmatrix} \\bar b - e_1 \\cr \\beta (\\bar b - e_2) \\end{bmatrix}\n",
    "$$\n",
    "\n",
    "Taking the ratio of the two components gives the formula, and setting $ e_1 = e_2 $ gives $ R = \\beta^{-1} $."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2dd07afd",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "beta, b_bar, e1 = 0.95, 5, 1\n",
    "\n",
    "def R_of_g(g):\n",
    "    Π = np.array([[1, 0],\n",
    "                  [0, np.sqrt(beta)]])\n",
    "    b = np.array([b_bar, np.sqrt(beta) * b_bar])\n",
    "    e = np.array([e1, (1 + g) * e1])\n",
    "    p, c = ExchangeEconomy(Π, b, e).competitive_equilibrium()\n",
    "    return p[0] / p[1]\n",
    "\n",
    "gs = np.linspace(-0.2, 0.2, 41)\n",
    "Rs = np.array([R_of_g(g) for g in gs])\n",
    "R_formula = np.array([(b_bar - e1) / (beta * (b_bar - (1 + g) * e1)) for g in gs])\n",
    "\n",
    "print(f'max |numerical - formula| = {np.max(np.abs(Rs - R_formula)):.2e}')\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "ax.plot(gs, Rs, label='$R = p_1 / p_2$')\n",
    "ax.axhline(1 / beta, linestyle='--', color='red', label=r'$\\beta^{-1}$')\n",
    "ax.set_xlabel('endowment growth rate $g$')\n",
    "ax.set_ylabel('gross interest rate $R$')\n",
    "ax.legend()\n",
    "plt.show()\n",
    "\n",
    "for g in [0, 0.1, 0.2]:\n",
    "    print(f'g = {g:>4}:  R = {R_of_g(g):.6f}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "83e84e8b",
   "metadata": {},
   "source": [
    "The numerical and analytical answers agree, and $ R = \\beta^{-1} = 1.052632 $ when $ g = 0 $.\n",
    "\n",
    "For part c, $ g > 0 $ tilts the endowment toward period $ 2 $, and the consumer wants a flat consumption path.\n",
    "\n",
    "At $ R = \\beta^{-1} $ the consumer would borrow against period $ 2 $ income.\n",
    "\n",
    "A single consumer has nobody to borrow from, so $ R $ rises until the consumer willingly consumes the endowment."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bf9bf740",
   "metadata": {},
   "source": [
    "### Risk and state-contingent claims\n",
    "\n",
    "We study risk in the context of a **static** environment, meaning that there is only one period.\n",
    "\n",
    "By **risk** we mean that an outcome is not known in advance, but that it is governed by a known probability distribution.\n",
    "\n",
    "That our consumer confronts **risk** means in particular that\n",
    "\n",
    "- there are two states of nature, $ 1 $ and $ 2 $.  \n",
    "- the consumer knows that the probability that state $ 1 $ occurs is $ \\lambda $.  \n",
    "- the consumer knows that the probability that state $ 2 $ occurs is $ (1-\\lambda) $.  \n",
    "\n",
    "\n",
    "Before the outcome is realized, the consumer’s **expected utility** is\n",
    "\n",
    "$$\n",
    "- \\frac{1}{2} [\\lambda (c_1 - b_1)^2 + (1-\\lambda)(c_2 - b_2)^2]\n",
    "$$\n",
    "\n",
    "where\n",
    "\n",
    "- $ c_1 $ is consumption in state $ 1 $  \n",
    "- $ c_2 $ is consumption in state $ 2 $  \n",
    "\n",
    "\n",
    "To capture these preferences we set\n",
    "\n",
    "$$\n",
    "\\Pi = \\begin{bmatrix} \\sqrt{\\lambda} & 0 \\cr\n",
    "                     0  & \\sqrt{1-\\lambda} \\end{bmatrix}\n",
    "$$\n",
    "\n",
    "$$\n",
    "e = \\begin{bmatrix} e_1 \\cr e_2 \\end{bmatrix}\n",
    "$$\n",
    "\n",
    "$$\n",
    "b = \\begin{bmatrix} \\sqrt{\\lambda}b_1 \\cr \\sqrt{1-\\lambda}b_2 \\end{bmatrix}\n",
    "$$\n",
    "\n",
    "A consumer’s consumption vector is\n",
    "\n",
    "$$\n",
    "c = \\begin{bmatrix} c_1 \\cr c_2 \\end{bmatrix}\n",
    "$$\n",
    "\n",
    "A price vector is\n",
    "\n",
    "$$\n",
    "p = \\begin{bmatrix} p_1 \\cr p_2 \\end{bmatrix}\n",
    "$$\n",
    "\n",
    "where $ p_i $ is the price of one unit of consumption in state $ i \\in \\{1, 2\\} $.\n",
    "\n",
    "The state-contingent goods being traded are often called **Arrow securities**.\n",
    "\n",
    "Before the random state of the world $ i $ is realized, the consumer sells their state-contingent endowment bundle and purchases a state-contingent consumption bundle.\n",
    "\n",
    "Trading such state-contingent goods is one way economists often model **insurance**.\n",
    "\n",
    "Here is an instance of the risk economy:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2aafa5cb",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "prob = 0.2\n",
    "\n",
    "Π = np.array([[np.sqrt(prob), 0],\n",
    "              [0, np.sqrt(1 - prob)]])\n",
    "\n",
    "b = np.array([np.sqrt(prob) * 5, np.sqrt(1 - prob) * 5])\n",
    "\n",
    "e = np.array([1, 1])\n",
    "\n",
    "risk = ExchangeEconomy(Π, b, e)\n",
    "p, c = risk.competitive_equilibrium()\n",
    "\n",
    "print('Competitive equilibrium price vector:', p)\n",
    "print('Competitive equilibrium allocation:', c)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6358f593",
   "metadata": {},
   "source": [
    "### Exercise 52.4\n",
    "\n",
    "Consider the instance above.\n",
    "\n",
    "Please numerically study how each of the following cases affects the equilibrium prices and allocations:\n",
    "\n",
    "- the consumer gets poorer,  \n",
    "- they like the first good more, or  \n",
    "- the probability that state $ 1 $ occurs is higher.  \n",
    "\n",
    "\n",
    "Hint: for each case, choose a value of $ e $, $ b $, or $ \\lambda $ that differs from the one used in the instance above."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2a470e47",
   "metadata": {},
   "source": [
    "### Solution\n",
    "\n",
    "A single-consumer endowment economy has no production and no trading partner, so the allocation equals the endowment.\n",
    "\n",
    "Only prices respond to the experiments below.\n",
    "\n",
    "We build a fresh economy for each experiment."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "712ccf45",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "def risk_economy(prob=0.2, b_scale=(5, 5), e=(1, 1)):\n",
    "    \"\"\"\n",
    "    Build the risk economy, allowing each element of the baseline to be changed\n",
    "    \"\"\"\n",
    "    Π = np.array([[np.sqrt(prob), 0],\n",
    "                  [0, np.sqrt(1 - prob)]])\n",
    "    b = np.array([np.sqrt(prob) * b_scale[0],\n",
    "                  np.sqrt(1 - prob) * b_scale[1]])\n",
    "    return ExchangeEconomy(Π, b, np.array(e))\n",
    "\n",
    "\n",
    "def show(economy, label):\n",
    "    p, c = economy.competitive_equilibrium()\n",
    "    print(f'{label}')\n",
    "    print(f'  price vector: {p}')\n",
    "    print(f'  allocation  : {c}\\n')\n",
    "\n",
    "\n",
    "show(risk_economy(), 'baseline')\n",
    "show(risk_economy(e=(0.5, 0.5)), 'the consumer is poorer')\n",
    "show(risk_economy(b_scale=(6, 5)), 'the consumer likes the first good more')\n",
    "show(risk_economy(prob=0.8), 'state 1 is more likely')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e1d9a17c",
   "metadata": {},
   "source": [
    "When the consumer is poorer, goods are scarcer relative to the bliss point, so **both** state-contingent prices rise.\n",
    "\n",
    "When the consumer likes the first good more, the price of a claim on state $ 1 $ rises while the price of a claim on state $ 2 $ is unchanged.\n",
    "\n",
    "When state $ 1 $ becomes more likely, a claim that pays in state $ 1 $ becomes more valuable and a claim that pays in state $ 2 $ becomes less valuable."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e70a62fb",
   "metadata": {},
   "source": [
    "### Exercise 52.5\n",
    "\n",
    "In the risk interpretation, $ p_i $ is the price of one unit of consumption contingent on state $ i $.\n",
    "\n",
    "a. Show that, with $ \\Pi = \\operatorname{diag}(\\sqrt{\\lambda}, \\sqrt{1-\\lambda}) $ and\n",
    "$ b = (\\sqrt{\\lambda}\\,\\bar b, \\ \\sqrt{1-\\lambda}\\,\\bar b)^\\top $,\n",
    "\n",
    "$$\n",
    "\\frac{p_1}{p_2} = \\frac{\\lambda}{1-\\lambda} \\cdot \\frac{\\bar b - e_1}{\\bar b - e_2}\n",
    "$$\n",
    "\n",
    "b. Conclude that when the endowment is the same in both states, state prices are proportional to probabilities, so that claims trade at **actuarially fair odds**.\n",
    "\n",
    "c. Verify both claims numerically for $ \\lambda \\in \\{0.2, 0.5, 0.8\\} $, first with $ e = (1,1) $ and then with $ e = (0.5, 1.5) $.\n",
    "\n",
    "Explain the sign of the departure from fair odds in the second case."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9a5f1970",
   "metadata": {},
   "source": [
    "### Solution\n",
    "\n",
    "For part a, again $ p = \\Pi^\\top b - \\Pi^\\top \\Pi e $, and here\n",
    "\n",
    "$$\n",
    "p = \\begin{bmatrix} \\lambda (\\bar b - e_1) \\cr (1-\\lambda)(\\bar b - e_2) \\end{bmatrix}\n",
    "$$\n",
    "\n",
    "from which the ratio follows immediately.\n",
    "\n",
    "Part b is then immediate too: if $ e_1 = e_2 $, the second factor equals $ 1 $, so $ p_1/p_2 = \\lambda/(1-\\lambda) $."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bfe20c13",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "b_bar = 5\n",
    "\n",
    "def price_ratio(λ, e):\n",
    "    Π = np.array([[np.sqrt(λ), 0],\n",
    "                  [0, np.sqrt(1 - λ)]])\n",
    "    b = np.array([np.sqrt(λ) * b_bar, np.sqrt(1 - λ) * b_bar])\n",
    "    p, c = ExchangeEconomy(Π, b, np.array(e)).competitive_equilibrium()\n",
    "    return p[0] / p[1]\n",
    "\n",
    "print(f\"{'λ':>5} | {'e':>12} | {'p1/p2':>9} | {'odds λ/(1-λ)':>13}\")\n",
    "print('-' * 48)\n",
    "for λ in [0.2, 0.5, 0.8]:\n",
    "    for e in [[1, 1], [0.5, 1.5]]:\n",
    "        print(f'{λ:>5} | {str(e):>12} | {price_ratio(λ, e):>9.4f} | {λ / (1 - λ):>13.4f}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c7c5d944",
   "metadata": {},
   "source": [
    "With $ e = (1,1) $ the price ratio equals the odds ratio exactly.\n",
    "\n",
    "With $ e = (0.5, 1.5) $ the good is scarcer in state $ 1 $, and $ p_1/p_2 $ exceeds $ \\lambda/(1-\\lambda) $ for every $ \\lambda $.\n",
    "\n",
    "State prices reflect probabilities and scarcity.\n",
    "\n",
    "Asset prices are expectations taken with respect to a probability distribution twisted toward states in which consumption is low."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6216bbe2",
   "metadata": {},
   "source": [
    "## Economies with endogenous supplies of goods\n",
    "\n",
    "Up to now we have described a pure exchange economy in which endowments of goods are exogenous, meaning that they are taken as given from outside the model."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0195aab9",
   "metadata": {},
   "source": [
    "### Supply curve of a competitive firm\n",
    "\n",
    "A competitive firm that can produce goods takes a price vector $ p $ as given and chooses a quantity $ q $\n",
    "to maximize total revenue minus total costs.\n",
    "\n",
    "The firm’s total revenue equals $ p^\\top q $ and its total cost equals $ C(q) $ where $ C(q) $ is a total cost function\n",
    "\n",
    "$$\n",
    "C(q) = h ^\\top q +  \\frac{1}{2} q^\\top J q\n",
    "$$\n",
    "\n",
    "and $ J $ is a positive definite matrix.\n",
    "\n",
    "So the firm’s profits are\n",
    "\n",
    "\n",
    "<a id='equation-eq-compprofits'></a>\n",
    "$$\n",
    "p^\\top q - C(q) \\tag{52.7}\n",
    "$$\n",
    "\n",
    "An $ n\\times 1 $ vector of **marginal costs** is\n",
    "\n",
    "$$\n",
    "\\frac{\\partial C(q)}{\\partial q} = h + H q\n",
    "$$\n",
    "\n",
    "where\n",
    "\n",
    "$$\n",
    "H =  \\frac{1}{2} (J + J^\\top)\n",
    "$$\n",
    "\n",
    "The firm maximizes total profits by setting **marginal revenue equal to marginal costs**.\n",
    "\n",
    "An $ n \\times 1 $ vector of marginal revenues for the price-taking firm is $ \\frac{\\partial p^\\top q}\n",
    "{\\partial q} = p $.\n",
    "\n",
    "So **price equals marginal revenue** for our price-taking competitive firm.\n",
    "\n",
    "This leads to the following **inverse supply curve** for the competitive firm:\n",
    "\n",
    "$$\n",
    "p = h + H q\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aeca44db",
   "metadata": {},
   "source": [
    "### Competitive equilibrium\n",
    "\n",
    "We equate the inverse supply curve to the inverse demand curve and solve for the equilibrium quantity vector.\n",
    "\n",
    "We then compute the equilibrium price vector from either curve.\n",
    "\n",
    "That quantity vector also solves a planning problem, as we show below."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "809a675b",
   "metadata": {},
   "source": [
    "#### $ \\mu=1 $ warmup\n",
    "\n",
    "As a special case, let’s pin down a demand curve by setting the marginal utility of wealth $ \\mu =1 $.\n",
    "\n",
    "Equating supply price to demand price and letting $ q=c $ we get\n",
    "\n",
    "$$\n",
    "p = h + H c = \\Pi^\\top b - \\Pi^\\top \\Pi c ,\n",
    "$$\n",
    "\n",
    "which implies the equilibrium quantity vector\n",
    "\n",
    "\n",
    "<a id='equation-eq-old5'></a>\n",
    "$$\n",
    "c = (\\Pi^\\top \\Pi + H )^{-1} ( \\Pi^\\top b - h) \\tag{52.8}\n",
    "$$\n",
    "\n",
    "This equation is the counterpart, for the scalar $ n=1 $ model of [Introduction to Supply and Demand](https://intro.quantecon.org/intro_supply_demand.html), of the equilibrium quantity derived there."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "29ef8261",
   "metadata": {},
   "source": [
    "#### General $ \\mu\\neq 1 $ case\n",
    "\n",
    "Now let’s extend the preceding analysis to a more\n",
    "general case by allowing $ \\mu \\neq 1 $.\n",
    "\n",
    "Then the inverse demand curve is\n",
    "\n",
    "\n",
    "<a id='equation-eq-old5pa'></a>\n",
    "$$\n",
    "p = \\mu^{-1} [\\Pi^\\top b - \\Pi^\\top \\Pi c] \\tag{52.9}\n",
    "$$\n",
    "\n",
    "Equating this to the inverse supply curve, letting $ q=c $ and solving\n",
    "for $ c $ gives\n",
    "\n",
    "\n",
    "<a id='equation-eq-old5p'></a>\n",
    "$$\n",
    "c = [\\Pi^\\top \\Pi + \\mu H]^{-1} [ \\Pi^\\top b - \\mu h] \\tag{52.10}\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c8e46b07",
   "metadata": {},
   "source": [
    "### Multi-good welfare maximization problem\n",
    "\n",
    "Our welfare maximization problem – also sometimes called a social planning problem  – is to choose $ c $ to maximize\n",
    "\n",
    "$$\n",
    "- \\frac{1}{2} \\mu^{-1}(\\Pi c -b) ^\\top (\\Pi c -b )\n",
    "$$\n",
    "\n",
    "minus the area under the inverse supply curve, namely,\n",
    "\n",
    "$$\n",
    "h^\\top c +  \\frac{1}{2} c^\\top J c\n",
    "$$\n",
    "\n",
    "So the welfare criterion is\n",
    "\n",
    "$$\n",
    "- \\frac{1}{2} \\mu^{-1}(\\Pi c -b)^\\top (\\Pi c -b ) -h^\\top c \n",
    "        -  \\frac{1}{2} c^\\top J c\n",
    "$$\n",
    "\n",
    "In this formulation, $ \\mu $ is a parameter that describes how the planner weighs interests of outside suppliers and our representative consumer.\n",
    "\n",
    "The first-order condition with respect to $ c $ is\n",
    "\n",
    "$$\n",
    "- \\mu^{-1} \\Pi^\\top \\Pi c + \\mu^{-1}\\Pi^\\top b - h -  H c = 0\n",
    "$$\n",
    "\n",
    "which implies [(52.10)](#equation-eq-old5p).\n",
    "\n",
    "Thus, as for the single-good case, with multiple goods a competitive equilibrium quantity vector solves a planning problem.\n",
    "\n",
    "(This is another version of the first welfare theorem.)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f98cd17b",
   "metadata": {},
   "source": [
    "#### Welfare as consumer surplus plus producer surplus\n",
    "\n",
    "[Introduction to Supply and Demand](https://intro.quantecon.org/intro_supply_demand.html) measured social welfare by consumer surplus plus producer surplus.\n",
    "\n",
    "Our welfare criterion equals that measure up to a constant.\n",
    "\n",
    "Consumer surplus is the area under the inverse demand curve minus expenditure.\n",
    "\n",
    "Producer surplus is revenue minus the area under the inverse supply curve.\n",
    "\n",
    "Adding them cancels revenue against expenditure:\n",
    "\n",
    "$$\n",
    "CS + PS = \\mu^{-1} b^\\top \\Pi c - \\frac{1}{2}\\mu^{-1} c^\\top \\Pi^\\top \\Pi c\n",
    "        - h^\\top c - \\frac{1}{2} c^\\top J c\n",
    "$$\n",
    "\n",
    "Expanding the quadratic form in the welfare criterion gives\n",
    "\n",
    "$$\n",
    "- \\frac{1}{2} \\mu^{-1}(\\Pi c -b)^\\top (\\Pi c -b ) - h^\\top c - \\frac{1}{2} c^\\top J c\n",
    "  = CS + PS - \\frac{1}{2}\\mu^{-1} b^\\top b\n",
    "$$\n",
    "\n",
    "The constant $ \\frac{1}{2}\\mu^{-1} b^\\top b $ does not depend on $ c $.\n",
    "\n",
    "Maximizing the welfare criterion and maximizing total surplus are therefore the same problem, and the competitive equilibrium quantity vector [(52.10)](#equation-eq-old5p) maximizes consumer surplus plus producer surplus.\n",
    "\n",
    "An exercise below computes both for a single good."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c9727bf9",
   "metadata": {},
   "source": [
    "### Implementation\n",
    "\n",
    "A Production Economy will consist of\n",
    "\n",
    "- a single **person** that we’ll interpret as a representative consumer  \n",
    "- a single set of **production costs**  \n",
    "- a multiplier $ \\mu $ that weights “consumers” versus “producers” in the planner’s welfare function described above  \n",
    "- an $ n \\times 1 $ vector $ p $ of competitive equilibrium prices  \n",
    "- an $ n \\times 1 $ vector $ c $ of competitive equilibrium quantities  \n",
    "- **consumer surplus**  \n",
    "- **producer surplus**  \n",
    "\n",
    "\n",
    "Here we define a class `ProductionEconomy`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "493a8bc3",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "class ProductionEconomy:\n",
    "    \n",
    "    def __init__(self, \n",
    "                 Π, \n",
    "                 b, \n",
    "                 h, \n",
    "                 J, \n",
    "                 μ):\n",
    "        \"\"\"\n",
    "        Set up the environment for a production economy\n",
    "\n",
    "        Args:\n",
    "            Π (np.ndarray): matrix of substitution\n",
    "            b (np.array): bliss points\n",
    "            h (np.array): h in cost func\n",
    "            J (np.ndarray): J in cost func\n",
    "            μ (float): welfare weight of the corresponding planning problem\n",
    "        \"\"\"\n",
    "        self.n = len(b)\n",
    "        self.Π, self.b, self.h, self.J, self.μ = Π, b, h, J, μ\n",
    "        \n",
    "    def competitive_equilibrium(self):\n",
    "        \"\"\"\n",
    "        Compute a competitive equilibrium of the production economy\n",
    "        \"\"\"\n",
    "        Π, b, h, μ, J = self.Π, self.b, self.h, self.μ, self.J\n",
    "        H = .5 * (J + J.T)\n",
    "\n",
    "        # allocation\n",
    "        c = inv(Π.T @ Π + μ * H) @ (Π.T @ b - μ * h)\n",
    "\n",
    "        # price\n",
    "        p = 1 / μ * (Π.T @ b - Π.T @ Π @ c)\n",
    "\n",
    "        # check non-satiation\n",
    "        if any(Π @ c - b >= 0):\n",
    "            raise Exception('invalid result: set bliss points further away')\n",
    "\n",
    "        return c, p\n",
    "\n",
    "    def compute_surplus(self):\n",
    "        \"\"\"\n",
    "        Compute consumer and producer surplus for single good case\n",
    "        \"\"\"\n",
    "        if self.n != 1:\n",
    "            raise Exception('not single good')\n",
    "        h, J, Π, b, μ = self.h.item(), self.J.item(), self.Π.item(), self.b.item(), self.μ\n",
    "        H = J\n",
    "\n",
    "        # supply/demand curve coefficients\n",
    "        s0, s1 = h, H\n",
    "        d0, d1 = 1 / μ * Π * b, 1 / μ * Π**2\n",
    "\n",
    "        # competitive equilibrium\n",
    "        c, p = self.competitive_equilibrium()\n",
    "\n",
    "        # calculate surplus\n",
    "        c_surplus = d0 * c - .5 * d1 * c**2 - p * c\n",
    "        p_surplus = p * c - s0 * c - .5 * s1 * c**2\n",
    "\n",
    "        return c_surplus, p_surplus"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8a3917bb",
   "metadata": {},
   "source": [
    "Then define a function that plots demand and supply curves and labels surpluses and equilibrium."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4e97d7e8",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "def plot_competitive_equilibrium(PE):\n",
    "    \"\"\"\n",
    "    Plot demand and supply curves, producer/consumer surpluses, and equilibrium for\n",
    "    a single good production economy\n",
    "\n",
    "    Args:\n",
    "        PE (class): An initialized production economy class\n",
    "    \"\"\"\n",
    "    # get singleton value\n",
    "    J, h, Π, b, μ = PE.J.item(), PE.h.item(), PE.Π.item(), PE.b.item(), PE.μ\n",
    "    H = J\n",
    "\n",
    "    # compute competitive equilibrium\n",
    "    c, p = PE.competitive_equilibrium()\n",
    "    c, p = c.item(), p.item()\n",
    "\n",
    "    # inverse supply/demand curve\n",
    "    supply_inv = lambda x: h + H * x\n",
    "    demand_inv = lambda x: 1 / μ * (Π * b - Π * Π * x)\n",
    "\n",
    "    xs = np.linspace(0, 2 * c, 100)\n",
    "    ps = np.ones(100) * p\n",
    "    supply_curve = supply_inv(xs)\n",
    "    demand_curve = demand_inv(xs)\n",
    "\n",
    "    # plot\n",
    "    plt.figure()\n",
    "    plt.plot(xs, supply_curve, label='Supply', color='#020060')\n",
    "    plt.plot(xs, demand_curve, label='Demand', color='#600001')\n",
    "\n",
    "    plt.fill_between(xs[xs <= c], demand_curve[xs <= c], ps[xs <= c], label='Consumer surplus', color='#EED1CF')\n",
    "    plt.fill_between(xs[xs <= c], supply_curve[xs <= c], ps[xs <= c], label='Producer surplus', color='#E6E6F5')\n",
    "\n",
    "    plt.vlines(c, 0, p, linestyle=\"dashed\", color='black', alpha=0.7)\n",
    "    plt.hlines(p, 0, c, linestyle=\"dashed\", color='black', alpha=0.7)\n",
    "    plt.scatter(c, p, zorder=10, label='Competitive equilibrium', color='#600001')\n",
    "\n",
    "    plt.legend(loc='upper right')\n",
    "    plt.margins(x=0, y=0)\n",
    "    plt.ylim(0)\n",
    "    plt.xlabel('Quantity')\n",
    "    plt.ylabel('Price')\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a88d5fb2",
   "metadata": {},
   "source": [
    "#### Example: single agent with one good and production\n",
    "\n",
    "Now let’s construct an example of a production economy with one good.\n",
    "\n",
    "To do this we\n",
    "\n",
    "- specify a single **person** and a **cost curve** in a way that lets us replicate the simple single-good supply and demand example of [Introduction to Supply and Demand](https://intro.quantecon.org/intro_supply_demand.html)  \n",
    "- compute equilibrium $ p $ and $ c $ and consumer and producer surpluses  \n",
    "- draw graphs of both surpluses  \n",
    "- do experiments in which we shift $ b $ and watch what happens to $ p, c $.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f1b15961",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "Π = np.array([[1]])  # the matrix now is a singleton\n",
    "b = np.array([10])\n",
    "h = np.array([0.5])\n",
    "J = np.array([[1]])\n",
    "μ = 1\n",
    "\n",
    "PE = ProductionEconomy(Π, b, h, J, μ)\n",
    "c, p = PE.competitive_equilibrium()\n",
    "\n",
    "print('Competitive equilibrium price:', p.item())\n",
    "print('Competitive equilibrium allocation:', c.item())\n",
    "\n",
    "# plot\n",
    "plot_competitive_equilibrium(PE)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "07339bfe",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "c_surplus, p_surplus = PE.compute_surplus()\n",
    "\n",
    "print('Consumer surplus:', c_surplus.item())\n",
    "print('Producer surplus:', p_surplus.item())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2bbfd297",
   "metadata": {},
   "source": [
    "Let’s give the consumer a lower welfare weight by raising $ \\mu $."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b89efc70",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "PE.μ = 2\n",
    "c, p = PE.competitive_equilibrium()\n",
    "\n",
    "print('Competitive equilibrium price:', p.item())\n",
    "print('Competitive equilibrium allocation:', c.item())\n",
    "\n",
    "# plot\n",
    "plot_competitive_equilibrium(PE)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "07bb2253",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "c_surplus, p_surplus = PE.compute_surplus()\n",
    "\n",
    "print('Consumer surplus:', c_surplus.item())\n",
    "print('Producer surplus:', p_surplus.item())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b54209e2",
   "metadata": {},
   "source": [
    "Raising $ \\mu $ from $ 1 $ to $ 2 $ halves the consumer’s willingness to pay for each unit, $ \\mu^{-1}(\\Pi b - \\Pi^2 c) $.\n",
    "\n",
    "The equilibrium quantity falls from $ 4.75 $ to $ 3 $ and the price falls from $ 5.25 $ to $ 3.5 $.\n",
    "\n",
    "Both surpluses fall.\n",
    "\n",
    "The two experiments hold $ h $ and $ J $ fixed, so both surpluses are measured in the same units.\n",
    "\n",
    "The two experiments weight the consumer differently, so their surpluses do not rank welfare across them.\n",
    "\n",
    "Within each experiment, consumer surplus plus producer surplus is maximized at the competitive quantity.\n",
    "\n",
    "Now we change the bliss point so that the consumer derives more utility from consumption."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d1208f0a",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "PE.μ = 1\n",
    "PE.b = PE.b * 1.5\n",
    "c, p = PE.competitive_equilibrium()\n",
    "\n",
    "print('Competitive equilibrium price:', p.item())\n",
    "print('Competitive equilibrium allocation:', c.item())\n",
    "\n",
    "# plot\n",
    "plot_competitive_equilibrium(PE)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "71f291a1",
   "metadata": {},
   "source": [
    "This raises both the equilibrium price and quantity."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "120d2aa9",
   "metadata": {},
   "source": [
    "#### Example: single agent two-good economy with production\n",
    "\n",
    "Now we do experiments like those above, but with two goods.\n",
    "\n",
    "We begin with a **diagonal** $ \\Pi $, so that the two goods are independent in preferences, together with a cost matrix $ J $ whose off-diagonal element is positive, so that producing more of one good raises the marginal cost of the other."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "44418113",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "Π = np.array([[1, 0],\n",
    "              [0, 1]])\n",
    "\n",
    "b = np.array([10, 10])\n",
    "\n",
    "h = np.array([0.5, 0.5])\n",
    "\n",
    "J = np.array([[1, 0.5],\n",
    "              [0.5, 1]])\n",
    "μ = 1\n",
    "\n",
    "PE = ProductionEconomy(Π, b, h, J, μ)\n",
    "c, p = PE.competitive_equilibrium()\n",
    "\n",
    "print('Competitive equilibrium price:', p)\n",
    "print('Competitive equilibrium allocation:', c)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e8e0245",
   "metadata": {},
   "source": [
    "Now let’s raise the bliss point for the first good from $ 10 $ to $ 12 $."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d1fb2b3f",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "PE.b = np.array([12, 10])\n",
    "\n",
    "c, p = PE.competitive_equilibrium()\n",
    "\n",
    "print('Competitive equilibrium price:', p)\n",
    "print('Competitive equilibrium allocation:', c)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f55321a5",
   "metadata": {},
   "source": [
    "The quantity of good $ 1 $ rises while the quantity of good $ 2 $ **falls**, even though preferences for good $ 2 $ have not changed.\n",
    "\n",
    "That cross-effect comes entirely from the cost side: producing more of good $ 1 $ raises the marginal cost of good $ 2 $.\n",
    "\n",
    "Next we make $ \\Pi $ **non-diagonal**, so that the two goods interact in preferences as well as in costs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b83b363a",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "PE.Π = np.array([[1, 0.3],\n",
    "                 [0.3, 1]])\n",
    "\n",
    "PE.b = np.array([10, 10])\n",
    "\n",
    "c, p = PE.competitive_equilibrium()\n",
    "\n",
    "print('Competitive equilibrium price:', p)\n",
    "print('Competitive equilibrium allocation:', c)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1d5fbc06",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "PE.b = np.array([12, 10])\n",
    "c, p = PE.competitive_equilibrium()\n",
    "\n",
    "print('Competitive equilibrium price:', p)\n",
    "print('Competitive equilibrium allocation:', c)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d9c5a1ce",
   "metadata": {},
   "source": [
    "The same shift in $ b_1 $ now moves both quantities by more: good $ 1 $ rises by $ 1.11 $ rather than $ 1.07 $, and good $ 2 $ falls by $ 0.30 $ rather than $ 0.27 $.\n",
    "\n",
    "A non-diagonal $ \\Pi $ puts a positive off-diagonal element in $ \\Pi^\\top \\Pi $.\n",
    "\n",
    "The cross-partial derivative of utility becomes $ \\partial^2 u / \\partial c_1 \\partial c_2 = -0.6 $, so the two goods substitute for each other in preferences.\n",
    "\n",
    "Preference substitution reinforces cost substitution and pushes $ c_2 $ down.\n",
    "\n",
    "A non-diagonal $ \\Pi $ also raises both components of $ \\Pi^\\top b $ when $ b_1 $ rises, which pushes $ c_2 $ up.\n",
    "\n",
    "The first effect dominates.\n",
    "\n",
    ">**Note**\n",
    ">\n",
    ">The two effects can be separated in $ \\Delta c = (\\Pi^\\top \\Pi + H)^{-1} \\Pi^\\top \\Delta b $.\n",
    "\n",
    "Holding $ \\Pi^\\top \\Pi $ at $ I $ and letting only $ \\Pi^\\top b $ change gives $ \\Delta c = (0.99, 0.05) $.\n",
    "\n",
    "Holding $ \\Pi^\\top \\Delta b $ at $ (2,0) $ and letting only $ \\Pi^\\top \\Pi $ change gives $ \\Delta c = (1.32, -0.70) $.\n",
    "\n",
    "The two together give $ \\Delta c = (1.11, -0.30) $."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8d47abf0",
   "metadata": {},
   "source": [
    "### A monopolist supplier\n",
    "\n",
    "A competitive firm is a **price-taker** who regards the price and therefore its marginal revenue as being beyond its control.\n",
    "\n",
    "A monopolist knows that it has no competition and can influence the price and its marginal revenue by\n",
    "setting quantity.\n",
    "\n",
    "A monopolist takes a **demand curve** and not the **price** as beyond its control.\n",
    "\n",
    "Thus, instead of being a price-taker, a monopolist chooses a quantity to maximize profits subject to the inverse demand curve\n",
    "[(52.9)](#equation-eq-old5pa).\n",
    "\n",
    "So the monopolist’s total profits as a function of its output $ q $ is\n",
    "\n",
    "\n",
    "<a id='equation-eq-monopprof'></a>\n",
    "$$\n",
    "[\\mu^{-1} \\Pi^\\top (b - \\Pi q)]^\\top  q - h^\\top q -  \\frac{1}{2} q^\\top J q \\tag{52.11}\n",
    "$$\n",
    "\n",
    "After finding\n",
    "first-order necessary conditions for maximizing monopoly profits with respect to $ q $\n",
    "and solving them for $ q $, we find that the monopolist sets\n",
    "\n",
    "\n",
    "<a id='equation-eq-qmonop'></a>\n",
    "$$\n",
    "q = (H + 2 \\mu^{-1} \\Pi^\\top \\Pi)^{-1} (\\mu^{-1} \\Pi^\\top b - h) \\tag{52.12}\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a766f0f7",
   "metadata": {},
   "source": [
    "### Exercise 52.6\n",
    "\n",
    "Please  verify the monopolist’s supply curve [(52.12)](#equation-eq-qmonop)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7c467965",
   "metadata": {},
   "source": [
    "### Solution\n",
    "\n",
    "Write the monopolist’s profits [(52.11)](#equation-eq-monopprof) as\n",
    "\n",
    "$$\n",
    "\\mu^{-1} b^\\top \\Pi q - \\mu^{-1} q^\\top \\Pi^\\top \\Pi q - h^\\top q - \\frac{1}{2} q^\\top J q\n",
    "$$\n",
    "\n",
    "Now apply the formulas for differentiating an inner product and a quadratic form, recalling that $ H = \\frac{1}{2}(J + J^\\top) $:\n",
    "\n",
    "$$\n",
    "\\frac{\\partial}{\\partial q}\\left(\\mu^{-1} b^\\top \\Pi q\\right) = \\mu^{-1}\\Pi^\\top b, \\qquad\n",
    "\\frac{\\partial}{\\partial q}\\left(\\mu^{-1} q^\\top \\Pi^\\top \\Pi q\\right) = 2 \\mu^{-1}\\Pi^\\top \\Pi q\n",
    "$$\n",
    "\n",
    "$$\n",
    "\\frac{\\partial}{\\partial q}\\left(h^\\top q\\right) = h, \\qquad\n",
    "\\frac{\\partial}{\\partial q}\\left(\\frac{1}{2} q^\\top J q\\right) = H q\n",
    "$$\n",
    "\n",
    "The first-order condition is therefore\n",
    "\n",
    "$$\n",
    "\\mu^{-1}\\Pi^\\top b - 2 \\mu^{-1}\\Pi^\\top \\Pi q - h - H q = 0\n",
    "$$\n",
    "\n",
    "Collecting terms in $ q $ gives\n",
    "\n",
    "$$\n",
    "\\left(H + 2\\mu^{-1}\\Pi^\\top\\Pi\\right) q = \\mu^{-1}\\Pi^\\top b - h\n",
    "$$\n",
    "\n",
    "which is [(52.12)](#equation-eq-qmonop).\n",
    "\n",
    "The Hessian of profits with respect to $ q $ is $ -(H + 2\\mu^{-1}\\Pi^\\top \\Pi) $.\n",
    "\n",
    "Because $ H $ and $ \\Pi^\\top \\Pi $ are both positive definite, this Hessian is negative definite, so the first-order condition does indeed describe a maximum.\n",
    "\n",
    "Let’s now compare a monopolist with a competitive supplier.\n",
    "\n",
    "Recall that in a competitive equilibrium, a price-taking supplier equates marginal revenue $ p $ to marginal cost $ h + Hq $.\n",
    "\n",
    "A monopolist’s marginal revenue is not constant but instead is a non-trivial function of the quantity it sets.\n",
    "\n",
    "The monopolist’s marginal revenue is\n",
    "\n",
    "$$\n",
    "MR(q) = -2\\mu^{-1}\\Pi^{\\top}\\Pi q+\\mu^{-1}\\Pi^{\\top}b,\n",
    "$$\n",
    "\n",
    "which the monopolist equates to its marginal cost.\n",
    "\n",
    "Below we define a class `Monopoly` that inherits from `ProductionEconomy` and adds a method that computes an equilibrium price and allocation when the supplier is a monopolist.\n",
    "\n",
    "Since the supplier now has price-setting power\n",
    "\n",
    "- we first compute the optimal quantity that solves the monopolist’s profit maximization problem  \n",
    "- then we back out an equilibrium price from the consumer’s inverse demand curve  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3d6a1468",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "class Monopoly(ProductionEconomy):\n",
    "    \n",
    "    def __init__(self, \n",
    "                 Π, \n",
    "                 b, \n",
    "                 h, \n",
    "                 J, \n",
    "                 μ):\n",
    "        \"\"\"\n",
    "        Inherit all properties and methods from class ProductionEconomy\n",
    "        \"\"\"\n",
    "        super().__init__(Π, b, h, J, μ)\n",
    "        \n",
    "\n",
    "    def equilibrium_with_monopoly(self):\n",
    "        \"\"\"\n",
    "        Compute the equilibrium price and allocation when there is a monopolist supplier\n",
    "        \"\"\"\n",
    "        Π, b, h, μ, J = self.Π, self.b, self.h, self.μ, self.J\n",
    "        H = .5 * (J + J.T)\n",
    "\n",
    "        # allocation\n",
    "        q = inv(μ * H + 2 * Π.T @ Π) @ (Π.T @ b - μ * h)\n",
    "\n",
    "        # price\n",
    "        p = 1 / μ * (Π.T @ b - Π.T @ Π @ q)\n",
    "\n",
    "        if any(Π @ q - b >= 0):\n",
    "            raise Exception('invalid result: set bliss points further away')\n",
    "\n",
    "        return q, p"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "335305ad",
   "metadata": {},
   "source": [
    "Define a function that plots the demand, marginal cost and marginal revenue curves with surpluses and equilibrium labelled."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aa10f090",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "def plot_monopoly(M):\n",
    "    \"\"\"\n",
    "    Plot demand curve, marginal production cost and revenue, surpluses and the\n",
    "    equilibrium in a monopolist supplier economy with a single good\n",
    "\n",
    "    Args:\n",
    "        M (class): An instance of a class that inherits from ProductionEconomy\n",
    "    \"\"\"\n",
    "    # get singleton value\n",
    "    J, h, Π, b, μ = M.J.item(), M.h.item(), M.Π.item(), M.b.item(), M.μ\n",
    "    H = J\n",
    "\n",
    "    # compute competitive equilibrium\n",
    "    c, p = M.competitive_equilibrium()\n",
    "    q, pm = M.equilibrium_with_monopoly()\n",
    "    c, p, q, pm = c.item(), p.item(), q.item(), pm.item()\n",
    "\n",
    "    # inverse supply/demand curve\n",
    "    marg_cost = lambda x: h + H * x\n",
    "    marg_rev = lambda x: -2 * 1 / μ * Π * Π * x + 1 / μ * Π * b\n",
    "    demand_inv = lambda x: 1 / μ * (Π * b - Π * Π * x)\n",
    "\n",
    "    xs = np.linspace(0, 2 * c, 100)\n",
    "    pms = np.ones(100) * pm\n",
    "    marg_cost_curve = marg_cost(xs)\n",
    "    marg_rev_curve = marg_rev(xs)\n",
    "    demand_curve = demand_inv(xs)\n",
    "\n",
    "    # plot\n",
    "    plt.figure()\n",
    "    plt.plot(xs, marg_cost_curve, label='Marginal cost', color='#020060')\n",
    "    plt.plot(xs, marg_rev_curve, label='Marginal revenue', color='#E55B13')\n",
    "    plt.plot(xs, demand_curve, label='Demand', color='#600001')\n",
    "\n",
    "    plt.fill_between(xs[xs <= q], demand_curve[xs <= q], pms[xs <= q], label='Consumer surplus', color='#EED1CF')\n",
    "    plt.fill_between(xs[xs <= q], marg_cost_curve[xs <= q], pms[xs <= q], label='Producer surplus', color='#E6E6F5')\n",
    "\n",
    "    plt.vlines(c, 0, p, linestyle=\"dashed\", color='black', alpha=0.7)\n",
    "    plt.hlines(p, 0, c, linestyle=\"dashed\", color='black', alpha=0.7)\n",
    "    plt.scatter(c, p, zorder=10, label='Competitive equilibrium', color='#600001')\n",
    "\n",
    "    plt.vlines(q, 0, pm, linestyle=\"dashed\", color='black', alpha=0.7)\n",
    "    plt.hlines(pm, 0, q, linestyle=\"dashed\", color='black', alpha=0.7)\n",
    "    plt.scatter(q, pm, zorder=10, label='Equilibrium with monopoly', color='#E55B13')\n",
    "\n",
    "    plt.legend(loc='upper right')\n",
    "    plt.margins(x=0, y=0)\n",
    "    plt.ylim(0)\n",
    "    plt.xlabel('Quantity')\n",
    "    plt.ylabel('Price')\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bc57029a",
   "metadata": {},
   "source": [
    "#### A single-good example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a9f24c3b",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "Π = np.array([[1]])  # the matrix now is a singleton\n",
    "b = np.array([10])\n",
    "h = np.array([0.5])\n",
    "J = np.array([[1]])\n",
    "μ = 1\n",
    "\n",
    "M = Monopoly(Π, b, h, J, μ)\n",
    "c, p = M.competitive_equilibrium()\n",
    "q, pm = M.equilibrium_with_monopoly()\n",
    "\n",
    "print('Competitive equilibrium price:', p.item())\n",
    "print('Competitive equilibrium allocation:', c.item())\n",
    "\n",
    "print('Equilibrium with monopolist supplier price:', pm.item())\n",
    "print('Equilibrium with monopolist supplier allocation:', q.item())\n",
    "\n",
    "# plot\n",
    "plot_monopoly(M)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d47ef6ec",
   "metadata": {},
   "source": [
    "The monopolist sets output below the competitive equilibrium quantity, and in this single-good economy that lower quantity is associated with a higher price."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6540d004",
   "metadata": {},
   "source": [
    "#### Exercise 52.7\n",
    "\n",
    "For the single-good economy just studied, with $ \\Pi = [1] $, $ b = [10] $, $ h = [0.5] $, $ J = [[1]] $ and $ \\mu = 1 $, define **total surplus** at quantity $ x $ as the area under the inverse demand curve minus the area under the marginal cost curve:\n",
    "\n",
    "$$\n",
    "TS(x) = \\mu^{-1}\\left(\\Pi b x - \\frac{1}{2}\\Pi^2 x^2\\right) - \\left(h x + \\frac{1}{2} J x^2\\right)\n",
    "$$\n",
    "\n",
    "a. Compute $ TS $ at the competitive quantity and at the monopoly quantity, and report the **deadweight loss** caused by monopoly.\n",
    "\n",
    "b. Maximize $ TS $ over a fine grid of values of $ x $ and check that the maximizer is the *competitive* quantity rather than the monopoly quantity.\n",
    "\n",
    "Which welfare theorem does this illustrate?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0c3f9d7c",
   "metadata": {},
   "source": [
    "#### Solution"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "92267ff7",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "Π = np.array([[1]])\n",
    "b = np.array([10])\n",
    "h = np.array([0.5])\n",
    "J = np.array([[1]])\n",
    "μ = 1\n",
    "\n",
    "M = Monopoly(Π, b, h, J, μ)\n",
    "c, p = M.competitive_equilibrium()\n",
    "q, pm = M.equilibrium_with_monopoly()\n",
    "c, p, q, pm = c.item(), p.item(), q.item(), pm.item()\n",
    "\n",
    "Π_, b_, h_, J_ = Π.item(), b.item(), h.item(), J.item()\n",
    "\n",
    "def total_surplus(x):\n",
    "    return (Π_ * b_ * x - .5 * Π_**2 * x**2) / μ - (h_ * x + .5 * J_ * x**2)\n",
    "\n",
    "print(f'competitive: q = {c:.4f}, p = {p:.4f}, total surplus = {total_surplus(c):.4f}')\n",
    "print(f'monopoly   : q = {q:.4f}, p = {pm:.4f}, total surplus = {total_surplus(q):.4f}')\n",
    "print(f'deadweight loss = {total_surplus(c) - total_surplus(q):.4f}')\n",
    "\n",
    "xs = np.linspace(0, 2 * c, 100001)\n",
    "print(f'\\nquantity that maximizes total surplus: {xs[np.argmax(total_surplus(xs))]:.4f}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c72ae10a",
   "metadata": {},
   "source": [
    "Let’s draw the deadweight loss as the area between the demand curve and the marginal cost curve, over the output that the monopolist declines to produce."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "57694b9f",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "xs = np.linspace(0, 2 * c, 200)\n",
    "demand_inv = lambda x: (Π_ * b_ - Π_**2 * x) / μ\n",
    "marg_cost = lambda x: h_ + J_ * x\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "ax.plot(xs, demand_inv(xs), label='Demand', color='#600001')\n",
    "ax.plot(xs, marg_cost(xs), label='Marginal cost', color='#020060')\n",
    "\n",
    "mask = (xs >= q) & (xs <= c)\n",
    "ax.fill_between(xs[mask], marg_cost(xs[mask]), demand_inv(xs[mask]),\n",
    "                color='#BBBBBB', label='Deadweight loss')\n",
    "\n",
    "ax.scatter(c, p, zorder=10, label='Competitive equilibrium', color='#600001')\n",
    "ax.scatter(q, pm, zorder=10, label='Equilibrium with monopoly', color='#E55B13')\n",
    "\n",
    "ax.set_xlabel('Quantity')\n",
    "ax.set_ylabel('Price')\n",
    "ax.legend(loc='upper right')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c4f21aee",
   "metadata": {},
   "source": [
    "The competitive quantity $ 4.75 $ maximizes total surplus, while the monopolist restricts output to $ 3.1667 $ and so destroys $ 2.5069 $ of surplus, the shaded triangle between the demand curve and the marginal cost curve.\n",
    "\n",
    "That the competitive quantity solves the planner’s problem is the **first welfare theorem**, here in its single-good form.\n",
    "\n",
    "The monopolist violates the hypothesis of that theorem because it is not a price taker."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "db50d0ba",
   "metadata": {},
   "source": [
    "#### A multiple good example\n",
    "\n",
    "Let’s compare competitive equilibrium and monopoly outcomes in a multiple goods economy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d2365ec4",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "Π = np.array([[1, 0],\n",
    "              [0, 1.2]])\n",
    "\n",
    "b = np.array([10, 10])\n",
    "\n",
    "h = np.array([0.5, 0.5])\n",
    "\n",
    "J = np.array([[1, 0.5],\n",
    "              [0.5, 1]])\n",
    "μ = 1\n",
    "\n",
    "M = Monopoly(Π, b, h, J, μ)\n",
    "c, p = M.competitive_equilibrium()\n",
    "q, pm = M.equilibrium_with_monopoly()\n",
    "\n",
    "print('Competitive equilibrium price:', p)\n",
    "print('Competitive equilibrium allocation:', c)\n",
    "\n",
    "print('Equilibrium with monopolist supplier price:', pm)\n",
    "print('Equilibrium with monopolist supplier allocation:', q)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a265aa76",
   "metadata": {},
   "source": [
    "Here the monopolist restricts output of both goods.\n",
    "\n",
    ">**Note**\n",
    ">\n",
    ">With a single good, a monopolist produces less than a competitive industry does.\n",
    "\n",
    "With several goods, off-diagonal elements of $ \\Pi $ or $ J $ can lead a monopolist to produce more of one good than a competitive industry would.\n",
    "\n",
    "The welfare comparison survives.\n",
    "\n",
    "The monopoly quantity vector does not maximize the planner’s criterion, so total surplus falls under monopoly."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "272d879a",
   "metadata": {},
   "source": [
    "## Concluding remarks\n",
    "\n",
    "This lecture studied competitive equilibria in an economy with many goods, first in pure exchange and then with production.\n",
    "\n",
    "The same mathematical structure describes **dynamics** and **risk**, once we index goods by dates or by states of the world.\n",
    "\n",
    "A competitive equilibrium quantity vector solves a planning problem, a version of the first welfare theorem.\n",
    "\n",
    "A monopolist violates the hypothesis of that theorem and destroys surplus.\n",
    "\n",
    "Our economy contained a single representative consumer, so no question about the distribution of wealth arose.\n",
    "\n",
    "[Market Equilibrium with Heterogeneity](https://intro.quantecon.org/supply_demand_heterogeneity.html) lets consumers differ in their preferences and endowments and studies how a competitive equilibrium distributes goods among them."
   ]
  }
 ],
 "metadata": {
  "date": 1795846200.8230276,
  "filename": "supply_demand_multiple_goods.md",
  "kernelspec": {
   "display_name": "Python",
   "language": "python3",
   "name": "python3"
  },
  "title": "Supply and Demand with Many Goods"
 },
 "nbformat": 4,
 "nbformat_minor": 5
}