{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "835c5c68",
   "metadata": {},
   "source": [
    "$$\n",
    "\\newcommand{\\argmax}{arg\\,max}\n",
    "\\newcommand{\\argmin}{arg\\,min}\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ad82ef51",
   "metadata": {},
   "source": [
    "# Monetarist Theory of Price Levels with Adaptive Expectations"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1c38b2a6",
   "metadata": {},
   "source": [
    "## Overview\n",
    "\n",
    "This lecture is a sequel or prequel to [A Monetarist Theory of Price Levels](https://intro.quantecon.org/cagan_ree.html).\n",
    "\n",
    "We’ll use linear algebra to do some experiments with  an alternative “monetarist” or  “fiscal” theory of  price levels.\n",
    "\n",
    "Like the model in [A Monetarist Theory of Price Levels](https://intro.quantecon.org/cagan_ree.html), the model asserts that when a government persistently spends more than it collects in taxes and prints money to finance the shortfall, it puts upward pressure on the price level and generates persistent inflation.\n",
    "\n",
    "Instead of the “perfect foresight” or “rational expectations” version of the model in [A Monetarist Theory of Price Levels](https://intro.quantecon.org/cagan_ree.html), our model in the present lecture is an “adaptive expectations”  version of a model that  [[Cagan, 1956](https://intro.quantecon.org/zreferences.html#id194)] used to study the monetary dynamics of hyperinflations.\n",
    "\n",
    "It combines these components:\n",
    "\n",
    "- a demand function for real money balances that asserts that the logarithm of the quantity of real balances demanded depends inversely on the public’s expected rate of inflation  \n",
    "- an **adaptive expectations** model that describes how the public’s anticipated rate of inflation responds to past values of actual inflation  \n",
    "- an equilibrium condition that equates the demand for money to the supply  \n",
    "- an exogenous sequence of rates of growth of the money supply  \n",
    "\n",
    "\n",
    "Our model stays quite close to Cagan’s original specification.\n",
    "\n",
    "As in [Present Values](https://intro.quantecon.org/pv.html) and [Consumption Smoothing](https://intro.quantecon.org/cons_smooth.html), the only linear algebra operations that we’ll be  using are matrix multiplication and matrix inversion.\n",
    "\n",
    "To facilitate using  linear matrix algebra as our principal mathematical tool, we’ll use a finite horizon version of\n",
    "the model."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f749afa7",
   "metadata": {},
   "source": [
    "## Structure of the model\n",
    "\n",
    "Let\n",
    "\n",
    "- $ m_t $ be the log of the supply of  nominal money balances;  \n",
    "- $ \\mu_t = m_{t+1} - m_t $ be the net rate of growth of  nominal balances;  \n",
    "- $ p_t $ be the log of the price level;  \n",
    "- $ \\pi_t = p_{t+1} - p_t $ be the net rate of inflation  between $ t $ and $ t+1 $;  \n",
    "- $ \\pi_t^* $  be the public’s expected rate of inflation between  $ t $ and $ t+1 $;  \n",
    "- $ T $ the horizon – i.e., the last period for which the model will determine $ p_t $  \n",
    "- $ \\pi_0^* $ public’s initial expected rate of inflation between time $ 0 $ and time $ 1 $.  \n",
    "\n",
    "\n",
    "The demand for real balances $ \\exp\\left(m_t^d-p_t\\right) $ is governed by the following  version of the Cagan demand function\n",
    "\n",
    "\n",
    "<a id='equation-eq-caganmd-ad'></a>\n",
    "$$\n",
    "m_t^d - p_t = -\\alpha \\pi_t^* \\: , \\: \\alpha > 0 ; \\quad t = 0, 1, \\ldots, T . \\tag{33.1}\n",
    "$$\n",
    "\n",
    "This equation  asserts that the demand for real balances\n",
    "is inversely related to the public’s expected rate of inflation with sensitivity $ \\alpha $.\n",
    "\n",
    "Equating the logarithm $ m_t^d $ of the demand for money  to the logarithm  $ m_t $ of the supply of money in equation [(33.1)](#equation-eq-caganmd-ad) and solving for the logarithm $ p_t $\n",
    "of the price level gives\n",
    "\n",
    "\n",
    "<a id='equation-eq-eqfiscth1'></a>\n",
    "$$\n",
    "p_t = m_t + \\alpha \\pi_t^* \\tag{33.2}\n",
    "$$\n",
    "\n",
    "Taking the difference between equation [(33.2)](#equation-eq-eqfiscth1) at time $ t+1 $ and at time\n",
    "$ t $ gives\n",
    "\n",
    "\n",
    "<a id='equation-eq-eqpipi'></a>\n",
    "$$\n",
    "\\pi_t = \\mu_t + \\alpha \\pi_{t+1}^* - \\alpha \\pi_t^* \\tag{33.3}\n",
    "$$\n",
    "\n",
    "We assume that the expected rate of inflation $ \\pi_t^* $ is governed\n",
    "by the following adaptive expectations scheme proposed by [[Friedman, 1956](https://intro.quantecon.org/zreferences.html#id363)] and [[Cagan, 1956](https://intro.quantecon.org/zreferences.html#id194)], where $ \\lambda\\in [0,1] $ denotes the weight on expected inflation.\n",
    "\n",
    "\n",
    "<a id='equation-eq-adaptexpn'></a>\n",
    "$$\n",
    "\\pi_{t+1}^* = \\lambda \\pi_t^* + (1 -\\lambda) \\pi_t \\tag{33.4}\n",
    "$$\n",
    "\n",
    "As exogenous inputs into the model, we take initial conditions $ m_0, \\pi_0^* $\n",
    "and a money growth sequence $ \\mu = \\{\\mu_t\\}_{t=0}^T $.\n",
    "\n",
    "As endogenous outputs of our model we want to find sequences $ \\pi = \\{\\pi_t\\}_{t=0}^T, p = \\{p_t\\}_{t=0}^T $ as functions of the exogenous inputs.\n",
    "\n",
    "We’ll do some mental experiments by studying how the model outputs vary as we vary\n",
    "the model inputs."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a814cc4f",
   "metadata": {},
   "source": [
    "## Representing key equations with linear algebra\n",
    "\n",
    "We begin by writing the equation [(33.4)](#equation-eq-adaptexpn)  adaptive expectations model for $ \\pi_t^* $ for $ t=0, \\ldots, T $ as\n",
    "\n",
    "$$\n",
    "\\begin{bmatrix} 1 & 0 & 0 & \\cdots & 0 & 0 \\cr\n",
    "-\\lambda & 1 & 0 & \\cdots & 0 & 0 \\cr\n",
    "0 & - \\lambda  & 1  & \\cdots & 0 & 0 \\cr\n",
    "\\vdots & \\vdots & \\vdots & \\cdots & \\vdots & \\vdots \\cr\n",
    "0 & 0 & 0 & \\cdots & -\\lambda & 1\n",
    "\\end{bmatrix}\n",
    "\\begin{bmatrix} \\pi_0^* \\cr\n",
    "  \\pi_1^* \\cr\n",
    "  \\pi_2^* \\cr\n",
    "  \\vdots \\cr\n",
    "  \\pi_{T+1}^*\n",
    "  \\end{bmatrix} =\n",
    "  (1-\\lambda) \\begin{bmatrix}\n",
    "  0 & 0 & 0 & \\cdots & 0  \\cr\n",
    "  1 & 0 & 0 & \\cdots & 0   \\cr\n",
    "   0 & 1 & 0 & \\cdots & 0  \\cr\n",
    "    \\vdots &\\vdots & \\vdots & \\cdots & \\vdots  \\cr\n",
    "     0 & 0 & 0 & \\cdots & 1  \\end{bmatrix}\n",
    "     \\begin{bmatrix}\\pi_0 \\cr \\pi_1 \\cr \\pi_2 \\cr \\vdots \\cr \\pi_T\n",
    "  \\end{bmatrix} +\n",
    "  \\begin{bmatrix} \\pi_0^* \\cr 0 \\cr 0 \\cr \\vdots \\cr 0 \\end{bmatrix}\n",
    "$$\n",
    "\n",
    "Write this equation as\n",
    "\n",
    "\n",
    "<a id='equation-eq-eq1'></a>\n",
    "$$\n",
    "A \\pi^* = (1-\\lambda) B \\pi + \\pi_0^* \\tag{33.5}\n",
    "$$\n",
    "\n",
    "where the $ (T+2) \\times (T+2) $matrix $ A $, the $ (T+2)\\times (T+1) $ matrix $ B $, and the vectors $ \\pi^* , \\pi_0, \\pi_0^* $\n",
    "are defined implicitly by aligning these two equations.\n",
    "\n",
    "Next we write the key equation [(33.3)](#equation-eq-eqpipi) in matrix notation as\n",
    "\n",
    "$$\n",
    "\\begin{bmatrix}\n",
    "\\pi_0 \\cr \\pi_1 \\cr \\pi_1 \\cr \\vdots \\cr \\pi_T \\end{bmatrix}\n",
    "= \\begin{bmatrix}\n",
    "\\mu_0 \\cr \\mu_1 \\cr \\mu_2 \\cr  \\vdots \\cr \\mu_T \\end{bmatrix}\n",
    "+ \\begin{bmatrix} - \\alpha &  \\alpha & 0 & \\cdots & 0 & 0 \\cr\n",
    "0 & -\\alpha & \\alpha & \\cdots & 0 & 0 \\cr\n",
    "0 & 0 & -\\alpha & \\cdots & 0 & 0 \\cr\n",
    "\\vdots & \\vdots & \\vdots & \\cdots & \\alpha & 0 \\cr\n",
    "0 & 0 & 0 & \\cdots & -\\alpha  & \\alpha\n",
    "\\end{bmatrix}\n",
    "\\begin{bmatrix} \\pi_0^* \\cr\n",
    "  \\pi_1^* \\cr\n",
    "  \\pi_2^* \\cr\n",
    "  \\vdots \\cr\n",
    "  \\pi_{T+1}^*\n",
    "  \\end{bmatrix}\n",
    "$$\n",
    "\n",
    "Represent the previous equation system in terms of vectors and matrices as\n",
    "\n",
    "\n",
    "<a id='equation-eq-eq2'></a>\n",
    "$$\n",
    "\\pi = \\mu + C \\pi^* \\tag{33.6}\n",
    "$$\n",
    "\n",
    "where the $ (T+1) \\times (T+2) $ matrix $ C $ is defined implicitly to align this equation with the preceding\n",
    "equation system."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b006387b",
   "metadata": {},
   "source": [
    "## Harvesting insights from our matrix formulation\n",
    "\n",
    "We now have all of the ingredients we need to solve for $ \\pi $ as\n",
    "a function of $ \\mu, \\pi_0, \\pi_0^* $.\n",
    "\n",
    "Combine equations [(33.5)](#equation-eq-eq1)and [(33.6)](#equation-eq-eq2)  to get\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "A \\pi^* & = (1-\\lambda) B \\pi + \\pi_0^* \\cr\n",
    " & = (1-\\lambda) B \\left[ \\mu + C \\pi^* \\right] + \\pi_0^*\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "which implies that\n",
    "\n",
    "$$\n",
    "\\left[ A - (1-\\lambda) B C \\right] \\pi^* = (1-\\lambda) B \\mu+ \\pi_0^*\n",
    "$$\n",
    "\n",
    "Multiplying both sides of the above equation by the inverse of the matrix on the left side gives\n",
    "\n",
    "\n",
    "<a id='equation-eq-eq4'></a>\n",
    "$$\n",
    "\\pi^* = \\left[ A - (1-\\lambda) B C \\right]^{-1} \\left[ (1-\\lambda) B \\mu+ \\pi_0^* \\right] \\tag{33.7}\n",
    "$$\n",
    "\n",
    "Having solved equation [(33.7)](#equation-eq-eq4) for $ \\pi^* $, we can use  equation [(33.6)](#equation-eq-eq2)  to solve for $ \\pi $:\n",
    "\n",
    "$$\n",
    "\\pi = \\mu + C \\pi^*\n",
    "$$\n",
    "\n",
    "We have thus solved for two of the key endogenous time series determined by our model, namely, the sequence $ \\pi^* $\n",
    "of expected inflation rates and the sequence $ \\pi $ of actual inflation rates.\n",
    "\n",
    "Knowing these, we can then quickly calculate the associated sequence $ p $  of the logarithm of the  price level\n",
    "from equation [(33.2)](#equation-eq-eqfiscth1).\n",
    "\n",
    "Let’s fill in the details for this step.\n",
    "\n",
    "Since we now know $ \\mu $  it is easy to compute $ m $.\n",
    "\n",
    "Thus, notice that we can represent the equations\n",
    "\n",
    "$$\n",
    "m_{t+1} = m_t + \\mu_t , \\quad t = 0, 1, \\ldots, T\n",
    "$$\n",
    "\n",
    "as the matrix equation\n",
    "\n",
    "\n",
    "<a id='equation-eq-eq101-ad'></a>\n",
    "$$\n",
    "\\begin{bmatrix}\n",
    "1 & 0 & 0 & \\cdots & 0 & 0 \\cr\n",
    "-1 & 1 & 0 & \\cdots & 0 & 0 \\cr\n",
    "0  & -1 & 1 & \\cdots & 0 & 0 \\cr\n",
    "\\vdots  & \\vdots & \\vdots & \\vdots & 0 & 0 \\cr\n",
    "0  & 0 & 0 & \\cdots & 1 & 0 \\cr\n",
    "0  & 0 & 0 & \\cdots & -1 & 1\n",
    "\\end{bmatrix}\n",
    "\\begin{bmatrix}\n",
    "m_1 \\cr m_2 \\cr m_3 \\cr \\vdots \\cr m_T \\cr m_{T+1}\n",
    "\\end{bmatrix}\n",
    "= \\begin{bmatrix}\n",
    "\\mu_0 \\cr \\mu_1 \\cr \\mu_2 \\cr \\vdots \\cr \\mu_{T-1} \\cr \\mu_T\n",
    "\\end{bmatrix}\n",
    "+ \\begin{bmatrix}\n",
    "m_0 \\cr 0 \\cr 0 \\cr \\vdots \\cr 0 \\cr 0\n",
    "\\end{bmatrix} \\tag{33.8}\n",
    "$$\n",
    "\n",
    "Multiplying both sides of equation [(33.8)](#equation-eq-eq101-ad)  with the inverse of the matrix on the left will give\n",
    "\n",
    "\n",
    "<a id='equation-eq-mcum-ad'></a>\n",
    "$$\n",
    "m_t = m_0 + \\sum_{s=0}^{t-1} \\mu_s, \\quad t =1, \\ldots, T+1 \\tag{33.9}\n",
    "$$\n",
    "\n",
    "Equation [(33.9)](#equation-eq-mcum-ad) shows that the log of the money supply at $ t $ equals the log $ m_0 $ of the initial money supply\n",
    "plus accumulation of rates of money growth between times $ 0 $ and $ t $.\n",
    "\n",
    "We can then compute $ p_t $ for each $ t $ from equation [(33.2)](#equation-eq-eqfiscth1).\n",
    "\n",
    "We can write a compact formula for $ p $ as\n",
    "\n",
    "$$\n",
    "p = m + \\alpha \\hat \\pi^*\n",
    "$$\n",
    "\n",
    "where\n",
    "\n",
    "$$\n",
    "\\hat \\pi^* = \\begin{bmatrix} \\pi_0^* \\cr\n",
    "  \\pi_1^* \\cr\n",
    "  \\pi_2^* \\cr\n",
    "  \\vdots \\cr\n",
    "  \\pi_{T}^*\n",
    "  \\end{bmatrix},\n",
    "$$\n",
    "\n",
    "which is just $ \\pi^* $ with the last element dropped."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c04b6de0",
   "metadata": {},
   "source": [
    "## Forecast errors and model computation\n",
    "\n",
    "Our computations will verify that\n",
    "\n",
    "$$\n",
    "\\hat \\pi^* \\neq  \\pi,\n",
    "$$\n",
    "\n",
    "so that in general\n",
    "\n",
    "\n",
    "<a id='equation-eq-notre'></a>\n",
    "$$\n",
    "\\pi_t^* \\neq \\pi_t, \\quad t = 0, 1, \\ldots , T \\tag{33.10}\n",
    "$$\n",
    "\n",
    "This outcome is typical in models in which adaptive expectations hypothesis like equation [(33.4)](#equation-eq-adaptexpn) appear as a\n",
    "component.\n",
    "\n",
    "In [A Monetarist Theory of Price Levels](https://intro.quantecon.org/cagan_ree.html), we studied a version of the model that replaces hypothesis [(33.4)](#equation-eq-adaptexpn) with\n",
    "a “perfect foresight” or “rational expectations” hypothesis.\n",
    "\n",
    "But now, let’s dive in and do some computations with the adaptive expectations version of the model.\n",
    "\n",
    "As usual, we’ll start by importing some Python modules."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1c73d083",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from collections import namedtuple\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a9c6cba9",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "Cagan_Adaptive = namedtuple(\"Cagan_Adaptive\",\n",
    "                        [\"α\", \"m0\", \"Eπ0\", \"T\", \"λ\"])\n",
    "\n",
    "def create_cagan_adaptive_model(α = 5, m0 = 1, Eπ0 = 0.5, T=80, λ = 0.9):\n",
    "    return Cagan_Adaptive(α, m0, Eπ0, T, λ)\n",
    "\n",
    "md = create_cagan_adaptive_model()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "443134d5",
   "metadata": {},
   "source": [
    "We solve the model and plot variables of interests using the following functions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "58f487a8",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "def solve_cagan_adaptive(model, μ_seq):\n",
    "    \" Solve the Cagan model in finite time. \"\n",
    "    α, m0, Eπ0, T, λ = model\n",
    "\n",
    "    A = np.eye(T+2, T+2) - λ*np.eye(T+2, T+2, k=-1)\n",
    "    B = np.eye(T+2, T+1, k=-1)\n",
    "    C = -α*np.eye(T+1, T+2) + α*np.eye(T+1, T+2, k=1)\n",
    "    Eπ0_seq = np.append(Eπ0, np.zeros(T+1))\n",
    "\n",
    "    # Eπ_seq is of length T+2\n",
    "    Eπ_seq = np.linalg.solve(A - (1-λ)*B @ C, (1-λ) * B @ μ_seq + Eπ0_seq)\n",
    "\n",
    "    # π_seq is of length T+1\n",
    "    π_seq = μ_seq + C @ Eπ_seq\n",
    "\n",
    "    D = np.eye(T+1, T+1) - np.eye(T+1, T+1, k=-1) # D is the coefficient matrix in Equation (14.8)\n",
    "    m0_seq = np.append(m0, np.zeros(T))\n",
    "\n",
    "    # m_seq is of length T+2\n",
    "    m_seq = np.linalg.solve(D, μ_seq + m0_seq)\n",
    "    m_seq = np.append(m0, m_seq)\n",
    "\n",
    "    # p_seq is of length T+2\n",
    "    p_seq = m_seq + α * Eπ_seq\n",
    "\n",
    "    return π_seq, Eπ_seq, m_seq, p_seq"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d91af75f",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "def solve_and_plot(model, μ_seq):\n",
    "\n",
    "    π_seq, Eπ_seq, m_seq, p_seq = solve_cagan_adaptive(model, μ_seq)\n",
    "\n",
    "    T_seq = range(model.T+2)\n",
    "\n",
    "    fig, ax = plt.subplots(5, 1, figsize=[5, 12], dpi=200)\n",
    "    ax[0].plot(T_seq[:-1], μ_seq)\n",
    "    ax[1].plot(T_seq[:-1], π_seq, label=r'$\\pi_t$')\n",
    "    ax[1].plot(T_seq, Eπ_seq, label=r'$\\pi^{*}_{t}$')\n",
    "    ax[2].plot(T_seq, m_seq - p_seq)\n",
    "    ax[3].plot(T_seq, m_seq)\n",
    "    ax[4].plot(T_seq, p_seq)\n",
    "\n",
    "    y_labs = [r'$\\mu$', r'$\\pi$', r'$m - p$', r'$m$', r'$p$']\n",
    "    subplot_title = [r'Money supply growth', r'Inflation', r'Real balances', r'Money supply', r'Price level']\n",
    "\n",
    "    for i in range(5):\n",
    "        ax[i].set_xlabel(r'$t$')\n",
    "        ax[i].set_ylabel(y_labs[i])\n",
    "        ax[i].set_title(subplot_title[i])\n",
    "\n",
    "    ax[1].legend()\n",
    "    plt.tight_layout()\n",
    "    plt.show()\n",
    "\n",
    "    return π_seq, Eπ_seq, m_seq, p_seq"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "17bdc4ad",
   "metadata": {},
   "source": [
    "## Technical condition for stability\n",
    "\n",
    "In constructing our examples, we shall assume that $ (\\lambda, \\alpha) $ satisfy\n",
    "\n",
    "\n",
    "<a id='equation-eq-suffcond'></a>\n",
    "$$\n",
    "\\Bigl| \\frac{\\lambda-\\alpha(1-\\lambda)}{1-\\alpha(1-\\lambda)} \\Bigr| < 1 \\tag{33.11}\n",
    "$$\n",
    "\n",
    "The  source of this condition is the following string of deductions:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\pi_{t}&=\\mu_{t}+\\alpha\\pi_{t+1}^{*}-\\alpha\\pi_{t}^{*}\\\\\\pi_{t+1}^{*}&=\\lambda\\pi_{t}^{*}+(1-\\lambda)\\pi_{t}\\\\\\pi_{t}&=\\frac{\\mu_{t}}{1-\\alpha(1-\\lambda)}-\\frac{\\alpha(1-\\lambda)}{1-\\alpha(1-\\lambda)}\\pi_{t}^{*}\\\\\\implies\\pi_{t}^{*}&=\\frac{1}{\\alpha(1-\\lambda)}\\mu_{t}-\\frac{1-\\alpha(1-\\lambda)}{\\alpha(1-\\lambda)}\\pi_{t}\\\\\\pi_{t+1}&=\\frac{\\mu_{t+1}}{1-\\alpha(1-\\lambda)}-\\frac{\\alpha(1-\\lambda)}{1-\\alpha(1-\\lambda)}\\left(\\lambda\\pi_{t}^{*}+(1-\\lambda)\\pi_{t}\\right)\\\\&=\\frac{\\mu_{t+1}}{1-\\alpha(1-\\lambda)}-\\frac{\\lambda}{1-\\alpha(1-\\lambda)}\\mu_{t}+\\frac{\\lambda-\\alpha(1-\\lambda)}{1-\\alpha(1-\\lambda)}\\pi_{t}\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "By assuring that the coefficient on $ \\pi_t $ is less than one in absolute value, condition [(33.11)](#equation-eq-suffcond) assures stability of the dynamics of $ \\{\\pi_t\\} $ described by the last line of our string of deductions.\n",
    "\n",
    "The reader is free to study outcomes in examples that violate condition [(33.11)](#equation-eq-suffcond)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "972b344a",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "print(np.abs((md.λ - md.α*(1-md.λ))/(1 - md.α*(1-md.λ))))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "39f98193",
   "metadata": {},
   "source": [
    "## Experiments\n",
    "\n",
    "Now we’ll turn to some experiments."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8975302a",
   "metadata": {},
   "source": [
    "### Experiment 1\n",
    "\n",
    "We’ll study a situation in which the rate of growth of the money supply is $ \\mu_0 $\n",
    "from $ t=0 $ to $ t= T_1 $ and then permanently falls to $ \\mu^* $ at $ t=T_1 $.\n",
    "\n",
    "Thus, let $ T_1 \\in (0, T) $.\n",
    "\n",
    "So where $ \\mu_0 > \\mu^* $, we assume that\n",
    "\n",
    "$$\n",
    "\\mu_{t} = \\begin{cases}\n",
    "    \\mu_0  , & t = 0, \\ldots, T_1 -1 \\\\\n",
    "     \\mu^* , & t \\geq T_1\n",
    "     \\end{cases}\n",
    "$$\n",
    "\n",
    "Notice that  we studied exactly this experiment  in a rational expectations version of the model in [A Monetarist Theory of Price Levels](https://intro.quantecon.org/cagan_ree.html).\n",
    "\n",
    "So by comparing outcomes across the two lectures, we can learn about consequences of assuming adaptive expectations, as we do here, instead of  rational expectations as we assumed in that other lecture."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "670a329f",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "# Parameters for the experiment 1\n",
    "T1 = 60\n",
    "μ0 = 0.5\n",
    "μ_star = 0\n",
    "\n",
    "μ_seq_1 = np.append(μ0*np.ones(T1), μ_star*np.ones(md.T+1-T1))\n",
    "\n",
    "# solve and plot\n",
    "π_seq_1, Eπ_seq_1, m_seq_1, p_seq_1 = solve_and_plot(md, μ_seq_1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e66ed5a0",
   "metadata": {},
   "source": [
    "We invite the reader to compare outcomes with those under rational expectations studied in [A Monetarist Theory of Price Levels](https://intro.quantecon.org/cagan_ree.html).\n",
    "\n",
    "Please note how the actual inflation rate $ \\pi_t $ “overshoots” its ultimate steady-state value at the time of the sudden reduction in the rate of growth of the money supply at time $ T_1 $.\n",
    "\n",
    "We invite you to explain to  yourself the source of this overshooting and why it does not occur in  the rational expectations version of the model."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "28145e2c",
   "metadata": {},
   "source": [
    "### Experiment 2\n",
    "\n",
    "Now we’ll do a different experiment, namely, a gradual stabilization in which the rate of growth of the money supply smoothly\n",
    "declines from a high value to a persistently low value.\n",
    "\n",
    "While price level inflation eventually falls, it falls more slowly than the driving  force that ultimately causes it to fall, namely, the falling rate of growth of the money supply.\n",
    "\n",
    "The sluggish fall in inflation is explained by how anticipated  inflation $ \\pi_t^* $ persistently exceeds actual inflation $ \\pi_t $ during the transition from a high inflation to a low inflation situation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "116b464a",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "# parameters\n",
    "ϕ = 0.9\n",
    "μ_seq_2 = np.array([ϕ**t * μ0 + (1-ϕ**t)*μ_star for t in range(md.T)])\n",
    "μ_seq_2 = np.append(μ_seq_2, μ_star)\n",
    "\n",
    "\n",
    "# solve and plot\n",
    "π_seq_2, Eπ_seq_2, m_seq_2, p_seq_2 = solve_and_plot(md, μ_seq_2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ce93c7df",
   "metadata": {},
   "source": [
    "## Exercises"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5194d78e",
   "metadata": {},
   "source": [
    "## Exercise 33.1\n",
    "\n",
    "**Sensitivity of overshooting to the learning speed $ \\lambda $.**\n",
    "\n",
    "For Experiment 1 (sudden stabilization at $ T_1 = 60 $ from $ \\mu_0 = 0.5 $ to $ \\mu^* = 0 $), solve the model for $ \\lambda \\in \\{0.86,\\, 0.90,\\, 0.95,\\, 0.98\\} $ and, on a single graph, plot the actual inflation rate $ \\pi_t $ for each value.\n",
    "\n",
    "a. How do the sign and speed of post-stabilization convergence change as $ \\lambda $ varies within the stable region?\n",
    "\n",
    "b. For each $ \\lambda $, print $ \\rho $ and the peak absolute value of $ \\pi_t $ for $ t \\geq T_1 $."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "251e3fba",
   "metadata": {},
   "source": [
    "## Solution"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5a2f1ab7",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "T1 = 60\n",
    "μ0 = 0.5\n",
    "μ_star = 0.0\n",
    "λ_vals = [0.86, 0.90, 0.95, 0.98]\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(9, 4))\n",
    "for λ in λ_vals:\n",
    "    m = create_cagan_adaptive_model(λ=λ)\n",
    "    μ_seq = np.append(μ0 * np.ones(T1), μ_star * np.ones(m.T + 1 - T1))\n",
    "    π_seq, _, _, _ = solve_cagan_adaptive(m, μ_seq)\n",
    "    ax.plot(range(m.T + 1), π_seq, label=f'λ = {λ}')\n",
    "\n",
    "ax.axvline(T1, linestyle='--', color='black', lw=1, label='Stabilization $T_1$')\n",
    "ax.axhline(μ_star, linestyle=':', color='gray', lw=0.8)\n",
    "ax.set_xlabel('$t$')\n",
    "ax.set_ylabel(r'$\\pi_t$')\n",
    "ax.set_title('Inflation paths for different λ (sudden stabilization)')\n",
    "ax.legend()\n",
    "plt.show()\n",
    "\n",
    "print(f'{\"λ\":>6} | {\"ρ\":>10} | {\"|ρ|<1\":>8} | {\"peak |π| after T1\":>20}')\n",
    "print('-' * 56)\n",
    "for λ in λ_vals:\n",
    "    m = create_cagan_adaptive_model(λ=λ)\n",
    "    μ_seq = np.append(μ0 * np.ones(T1), μ_star * np.ones(m.T + 1 - T1))\n",
    "    π_seq, _, _, _ = solve_cagan_adaptive(m, μ_seq)\n",
    "    ρ = (λ - m.α * (1 - λ)) / (1 - m.α * (1 - λ))\n",
    "    peak = np.max(np.abs(π_seq[T1:]))\n",
    "    print(f'{λ:>6.2f} | {ρ:>10.4f} | {str(abs(ρ) < 1):>8} | {peak:>20.4f}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "be169313",
   "metadata": {},
   "source": [
    "All four values satisfy the stability condition $ |\\rho| < 1 $ for the default $ \\alpha = 5 $ and have $ \\rho > 0 $.\n",
    "\n",
    "The case $ \\lambda = 0.86 $ has the largest initial overshoot among these four values and then converges the fastest.\n",
    "\n",
    "As $ \\lambda $ moves closer to one, expectations become more inertial, so the post-stabilization response decays more slowly but starts from a smaller jump.\n",
    "\n",
    "For $ \\alpha = 5 $, an oscillatory stable response would require $ 0.8 < \\lambda < 5/6 $."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d62dc302",
   "metadata": {},
   "source": [
    "## Exercise 33.2\n",
    "\n",
    "**Systematic forecast errors under adaptive expectations.**\n",
    "\n",
    "The lecture notes that $ \\pi_t^* \\neq \\pi_t $ in general under adaptive\n",
    "expectations, in contrast to a rational-expectations equilibrium.\n",
    "\n",
    "For the default model (`md`) and both experiments:\n",
    "\n",
    "a. Compute and plot the forecast error $ e_t = \\pi_t^* - \\pi_t $ for\n",
    "$ t = 0, 1, \\ldots, T $.\n",
    "\n",
    "b. For each experiment, determine whether $ e_t $ is systematically positive or\n",
    "negative during the disinflation and explain why this systematic bias could\n",
    "not survive under rational expectations.\n",
    "\n",
    "(Recall that `Eπ_seq` returned by `solve_cagan_adaptive` has $ T+2 $ elements\n",
    "while `π_seq` has $ T+1 $; use `Eπ_seq[:-1]` to align them.)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "438f21da",
   "metadata": {},
   "source": [
    "## Solution"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8343009e",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "T1  = 60\n",
    "μ0  = 0.5\n",
    "μ_star = 0.0\n",
    "\n",
    "# Experiment 1 sequences\n",
    "μ_seq_1 = np.append(μ0 * np.ones(T1), μ_star * np.ones(md.T + 1 - T1))\n",
    "π1, Eπ1, _, _ = solve_cagan_adaptive(md, μ_seq_1)\n",
    "\n",
    "# Experiment 2 sequences\n",
    "ϕ = 0.9\n",
    "μ_seq_2 = np.array([ϕ**t * μ0 + (1 - ϕ**t) * μ_star for t in range(md.T)])\n",
    "μ_seq_2 = np.append(μ_seq_2, μ_star)\n",
    "π2, Eπ2, _, _ = solve_cagan_adaptive(md, μ_seq_2)\n",
    "\n",
    "t_seq = np.arange(md.T + 1)\n",
    "e1 = Eπ1[:-1] - π1   # forecast error, length T+1\n",
    "e2 = Eπ2[:-1] - π2\n",
    "\n",
    "fig, axes = plt.subplots(1, 2, figsize=(11, 4))\n",
    "axes[0].plot(t_seq, e1)\n",
    "axes[0].axhline(0, color='black', lw=0.8, linestyle='--')\n",
    "axes[0].axvline(T1, color='gray', lw=0.8, linestyle=':')\n",
    "axes[0].set_title('Forecast error: Experiment 1 (sudden)')\n",
    "axes[0].set_xlabel('$t$')\n",
    "axes[0].set_ylabel(r'$\\pi_t^* - \\pi_t$')\n",
    "\n",
    "axes[1].plot(t_seq, e2, color='C1')\n",
    "axes[1].axhline(0, color='black', lw=0.8, linestyle='--')\n",
    "axes[1].set_title('Forecast error: Experiment 2 (gradual)')\n",
    "axes[1].set_xlabel('$t$')\n",
    "axes[1].set_ylabel(r'$\\pi_t^* - \\pi_t$')\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()\n",
    "\n",
    "print(f'Exp 1: mean forecast error t < T1:  {e1[:T1].mean():.4f}')\n",
    "print(f'Exp 1: mean forecast error t >= T1: {e1[T1:].mean():.4f}')\n",
    "print(f'Exp 2: mean forecast error overall: {e2.mean():.4f}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "17900dab",
   "metadata": {},
   "source": [
    "During disinflation, actual inflation falls *below* expected inflation, so\n",
    "$ e_t = \\pi_t^* - \\pi_t > 0 $ throughout the transition, so the public\n",
    "systematically **over-predicts** inflation.\n",
    "\n",
    "Under rational expectations this persistent one-sided bias would be immediately arbitraged away as agents adjust their forecasting rule until $ e_t $ has mean zero."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e28c62e4",
   "metadata": {},
   "source": [
    "## Exercise 33.3\n",
    "\n",
    "**Post-stabilization convergence rate.**\n",
    "\n",
    "The lecture derives that, after the money-growth rate has been permanently set to\n",
    "$ \\mu^* $, the actual inflation rate $ \\pi_t $ decays geometrically:\n",
    "\n",
    "$$\n",
    "\\pi_{t+1} = \\rho\\, \\pi_t, \\qquad\n",
    "\\rho \\equiv \\frac{\\lambda - \\alpha(1-\\lambda)}{1 - \\alpha(1-\\lambda)}.\n",
    "$$\n",
    "\n",
    "Using Experiment 1 and the default model `md`:\n",
    "\n",
    "a. Compute $ \\rho $ analytically from the model parameters and verify that\n",
    "$ |\\rho| < 1 $ (the stability condition [(33.11)](#equation-eq-suffcond)).\n",
    "\n",
    "b. From the solved path `π_seq`, compute the empirical ratios\n",
    "$ \\pi_{t+1}/\\pi_t $ for $ t = T_1 + 1, \\ldots, T_1 + 10 $ and compare them\n",
    "to $ \\rho $.\n",
    "\n",
    "c. Plot $ \\log|\\pi_t| $ against $ t $ for $ t \\geq T_1 $ and verify that it is\n",
    "linear with slope $ \\log|\\rho| $."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1a98ebd9",
   "metadata": {},
   "source": [
    "## Solution"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "87c58fb0",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "T1 = 60\n",
    "μ0 = 0.5\n",
    "μ_star = 0.0\n",
    "\n",
    "α, λ = md.α, md.λ\n",
    "ρ = (λ - α * (1 - λ)) / (1 - α * (1 - λ))\n",
    "print(f'α = {α},  λ = {λ}')\n",
    "print(f'ρ = {ρ:.6f}   (|ρ| < 1: {abs(ρ) < 1})')\n",
    "\n",
    "μ_seq = np.append(μ0 * np.ones(T1), μ_star * np.ones(md.T + 1 - T1))\n",
    "π_seq, _, _, _ = solve_cagan_adaptive(md, μ_seq)\n",
    "\n",
    "# Part b: empirical successive ratios\n",
    "print(f'\\n{\"t\":>5} | {\"π_t\":>12} | {\"π_{t+1}/π_t\":>14} | {\"ρ\":>8}')\n",
    "print('-' * 46)\n",
    "for t in range(T1, T1 + 10):\n",
    "    ratio = π_seq[t + 1] / π_seq[t]\n",
    "    print(f'{t:>5} | {π_seq[t]:>12.6f} | {ratio:>14.6f} | {ρ:>8.6f}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3aa477a1",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "# Part c: log|π_t| is linear after T1\n",
    "t_post = np.arange(T1, md.T + 1)\n",
    "log_π  = np.log(np.abs(π_seq[T1:]))\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "ax.plot(t_post, log_π, label=r'$\\log|\\pi_t|$')\n",
    "# overlay the theoretical slope\n",
    "slope_theory = np.log(abs(ρ))\n",
    "ax.plot(t_post,\n",
    "        log_π[0] + slope_theory * (t_post - T1),\n",
    "        linestyle='--', label=f'slope = log|ρ| = {slope_theory:.4f}')\n",
    "ax.set_xlabel('$t$')\n",
    "ax.set_ylabel(r'$\\log|\\pi_t|$')\n",
    "ax.set_title('Geometric decay of inflation after stabilization')\n",
    "ax.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "247fdf2b",
   "metadata": {},
   "source": [
    "The empirical ratios converge to $ \\rho = 0.8 $ immediately after $ T_1 $, confirming\n",
    "the first-order difference equation derived analytically.\n",
    "\n",
    "The log plot is exactly linear with the theoretical slope, reflecting the exact geometric convergence\n",
    "$ \\pi_t = \\rho^{t-T_1} \\pi_{T_1} $ for $ t \\geq T_1 $."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cd5c30d7",
   "metadata": {},
   "source": [
    "## Exercise 33.4\n",
    "\n",
    "**Fast vs slow learning under gradual stabilization.**\n",
    "\n",
    "Experiment 2 uses a gradual decline in money growth\n",
    "$ \\mu_t = \\phi^t \\mu_0 + (1-\\phi^t)\\mu^* $ with $ \\phi = 0.9 $.\n",
    "\n",
    "a. For the same gradual $ \\mu $ path, compare the inflation $ \\pi_t $ and expected inflation $ \\pi_t^* $ paths for two stable cases:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8192a3e3",
   "metadata": {
    "hide-output": false
   },
   "source": [
    "```text\n",
    "* **Faster adjustment**: $\\lambda = 0.86$\n",
    "* **Slower adjustment**: $\\lambda = 0.95$\n",
    "\n",
    "Plot $\\pi_t$, $\\pi_t^*$, and $\\mu_t$ for each case on side-by-side graphs.\n",
    "```\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5bd9e15e",
   "metadata": {},
   "source": [
    "b. For each case, compute the mean absolute forecast error $ \\bar{e} = \\frac{1}{T+1}\\sum_{t=0}^T |\\pi_t^* - \\pi_t| $.\n",
    "\n",
    "c. Explain why the faster-adjustment case can move below the money-growth path while the slower-adjustment case displays more persistent forecast errors."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e2279808",
   "metadata": {},
   "source": [
    "## Solution"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "955bcd91",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "μ0    = 0.5\n",
    "μ_star = 0.0\n",
    "ϕ     = 0.9\n",
    "\n",
    "λ_cases = {'Faster adjustment (λ=0.86)': 0.86,\n",
    "           'Slower adjustment (λ=0.95)': 0.95}\n",
    "\n",
    "fig, axes = plt.subplots(1, 2, figsize=(12, 4))\n",
    "\n",
    "for ax, (label, λ) in zip(axes, λ_cases.items()):\n",
    "    m = create_cagan_adaptive_model(λ=λ)\n",
    "    μ_seq = np.array([ϕ**t * μ0 + (1 - ϕ**t) * μ_star for t in range(m.T)])\n",
    "    μ_seq = np.append(μ_seq, μ_star)\n",
    "    π_seq, Eπ_seq, _, _ = solve_cagan_adaptive(m, μ_seq)\n",
    "\n",
    "    t_seq = np.arange(m.T + 1)\n",
    "    ax.plot(t_seq, μ_seq,          label=r'$\\mu_t$',   linestyle=':',  color='black')\n",
    "    ax.plot(t_seq, π_seq,          label=r'$\\pi_t$',   lw=1.5)\n",
    "    ax.plot(t_seq, Eπ_seq[:-1],    label=r'$\\pi_t^*$', linestyle='--', lw=1.5)\n",
    "    ax.set_xlabel('$t$')\n",
    "    ax.set_title(label)\n",
    "    ax.legend(fontsize=8)\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()\n",
    "\n",
    "print(f'{\"Case\":>30} | {\"Mean |forecast error|\":>22}')\n",
    "print('-' * 56)\n",
    "for label, λ in λ_cases.items():\n",
    "    m = create_cagan_adaptive_model(λ=λ)\n",
    "    μ_seq = np.array([ϕ**t * μ0 + (1 - ϕ**t) * μ_star for t in range(m.T)])\n",
    "    μ_seq = np.append(μ_seq, μ_star)\n",
    "    π_seq, Eπ_seq, _, _ = solve_cagan_adaptive(m, μ_seq)\n",
    "    mae = np.mean(np.abs(Eπ_seq[:-1] - π_seq))\n",
    "    print(f'{label:>30} | {mae:>22.6f}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1782a0bf",
   "metadata": {},
   "source": [
    "With faster adjustment, expectations revise downward more aggressively and inflation can move below the money-growth path during the transition.\n",
    "\n",
    "With slower adjustment, expectations remain elevated for longer and the forecast errors are larger and slower to disappear."
   ]
  }
 ],
 "metadata": {
  "date": 1795846195.1812081,
  "filename": "cagan_adaptive.md",
  "kernelspec": {
   "display_name": "Python",
   "language": "python3",
   "name": "python3"
  },
  "title": "Monetarist Theory of Price Levels with Adaptive Expectations"
 },
 "nbformat": 4,
 "nbformat_minor": 5
}