{ "cells": [ { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Introduction to Dynamic Programming" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "We have studied the theory of dynamic programming in discrete time under certainty. Let's review what we know so far, so that we can start thinking about how to take to the computer." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "# The Problem" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "We want to find a sequence $\\{x_t\\}_{t=0}^\\infty$ and a function $V^*:X\\to\\mathbb{R}$ such that \n", "\n", "$$V^{\\ast}\\left(x_{0}\\right)=\\sup\\limits _{\\left\\{ x_{t}\\right\\} _{t=0}^{\\infty}}\\sum\\limits _{t=0}^{\\infty}\\beta^{t}U(x_{t},x_{t+1})$$ \n", "\n", "subject to $x_{t+1}\\in G(x_{t})\\subseteq X\\subseteq\\mathbb{R}^K$, for all $t\\geq0$ and $x_0\\in\\mathbb{R}$ given. We assume $\\beta\\in(0,1)$.\n", "\n", "We have seen that we can analyze this problem by solving instead the related problem \n", "\n", "$$V(x)=\\sup\\limits _{y\\in G(x)}\\left\\{ U(x,y)+\\beta V(y)\\right\\} ,\\text{ for all }x\\in X.$$" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "# Basic Results" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "## Assumptions" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "1. $G\\left(x\\right)$ is nonempty for all $x\\in X$ ; and for all $x_{0}\\in X$ and $\\mathbf{x}\\in \\Phi (x_{0})$, $\\lim\\nolimits_{n\\rightarrow\\infty}\\sum_{t=0}^{n}\\beta^{t}U(x_{t},x_{t+1})$ exists and is finite.\n", "\n", "2. $X$ is a compact subset of $\\mathbb{R}^{K}$, $G$ is nonempty, compact-valued and continuous. Moreover, \n", "$U:\\mathbf{X}_{G}\\rightarrow\\mathbb{R}$ is continuous, where $\\mathbf{X}_{G}=\\left\\{ (x,y)\\in X\\times X:y\\in G(x)\\right\\}$\n", "\n", "3. $U$ is strictly concave and $G$ is convex\n", "\n", "4. For each $y\\in X$, $U(\\cdot,y)$ is strictly increasing in each of its first $K$ arguments, and $G$ is monotone in the sense that $x\\leq x^{\\prime}$ implies $G(x)\\subset G(x^{\\prime})$.\n", "\n", "5. $U$ is continuously differentiable on the interior of its domain $\\mathbf{X}_{G}$.\n", "\n", "6. Let $\\Phi (x_{t})=\\{\\{x_{s}\\}_{s=t}^{\\infty}:x_{s+1}\\in G(x_{s})\\text{, for }s=t,t+1,...\\}$ and assume that $\\lim_{t\\rightarrow\\infty}\\beta^{t}V\\left(x_{t}\\right)=0$ for all $\\left(x,x_{1},x_{2},...\\right)\\in \\Phi (x)$.\n", "\n", "If all of these conditions are satisfied, then we have the following" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Theorem" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "*There exists a unique (value) function \n", "$$V^*(x_0)=V(x_0),$$ \n", "which is continuous, strictly increasing, strictly concave, and differentiable. Also, there exists a unique path $\\{x^*_t\\}_{t=0}^\\infty$, which starting from the given $x_0$ attains the value $V^*(x_0)$. The path can be found through a unique continuous policy function $\\pi: X\\to X$ such that $x^*_{t+1}=\\pi(x^*_t)$.*" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Taking it to the computer" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Ok. Now that we know the conditions for the existence and uniqueness (plus other characteristics) of our problem, how do we go about solving it?\n", "\n", "The idea is going to be simple and is based on what we saw when we proved the contraction mapping theorem and the proof of the previous theorem (Yes I know...we split this in various steps and intermediate results, which might have confused you). \n", "\n", "Remember that our Bellman Operator $T: C(X)\\to C(X)$ defined as \n", "\n", "$$T(V(x))\\equiv\\sup\\limits _{y\\in G(x)}\\left\\{ U(x,y)+\\beta V(y)\\right\\}$$\n", "\n", "assigns a continuous, strictly increasing, strictly concave function $T(V)$ to each continuous, increasing, and concave function $V$ defined on $X$. Since $T(V)$ is a contraction mapping, we know that if $V_0$ is any initial continuous, increasing, and concave function defined on $X$, then $T^n(V_0)\\to V^*$. This is precisely what we are going to do using the computer (well we will also do it by hand for a couple of examples)." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Value function iteration" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "So, now that we have a strategy to tackle the problem, and you have learned some basic Python at [Code Academy](http://codeacademy.com) and IPython in our other [notebook](IntroPython.ipynb), we are ready to write some code and do some dynamic economic analysis." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "But before we start, there is one issue I want to highlight. Notice that our state space $X$ is not assumed to be finite, and clearly the fact that our functions are continuous imply that we cannot be in a finite problem. So how do we represent such an infinite object in a computer, which only has finite memory? The solution is to take an approximation to the function, what Stachurski (2009) calls a fitted function. There are various methods to approximate functions (see Judd (1998) for an excellent presentation). The simplest method is a linear interpolation, which is what we will use here. " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "The idea behind linear interpolation is quite simple. Assume we want to approximate the function $V: X\\to X$, $X\\subseteq\\mathbb{R}$. The only thing we need is a finite set $\\{x_i\\}_{i=0}^N\\subseteq X$ for which we compute the value under $V$, i.e. we create the finite set of values $\\{V_i=V(x_i)\\}_{i=0}^N$. Then our approximation to the function $V$, $\\hat V$, will be defined as\n", "\n", "$$\\hat V(x)=V_{i-1}+\\frac{V_i-V_{i-1}}{x_i-x_{i-1}}(x-x_{i-1}) \\quad\\text{ if } x_{i-1}\\le x < x_i.$$\n", "\n", "In principle we could construct our own interpolation function, but [Scipy](http://www.scipy.org/) has already [optimized approximation algorithms](http://docs.scipy.org/doc/scipy/reference/interpolate.html), so let's use that package instead. Let's see what a linear interpolation of $\\sin(x)$ would look like." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "from __future__ import division\n", "%pylab --no-import-all\n", "%matplotlib inline\n", "from numpy import interp" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "interp?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "x = np.linspace(0, np.pi, 100)\n", "plt.figure(1)\n", "plt.plot(x, np.sin(x), label='Actual Function')\n", "for i in np.arange(3,11,2):\n", " fig1 = plt.figure(1)\n", " xp = np.linspace(0, np.pi, i)\n", " yp = np.sin(xp)\n", " y = interp(x, xp, yp)\n", " plt.plot(x, y, label='Interpolation ' + str(i))\n", " fig2 = plt.figure(2)\n", " plt.title('Error with up to ' + str(i) + ' points in interpolation')\n", " plt.ylabel('Error')\n", " plt.plot(y - np.sin(x), label=str(i))\n", " plt.legend(loc=8)\n", "plt.figure(1)\n", "plt.legend(loc=8)\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "fig1" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "fig2" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Clearly the more points we have the better our approximation. But, more points means more computations and more time to get those approximations. Since we will be iterating over approximations, we might not want to use too many points, but be smart about the choice of points or we might want to use less points for a start and then increase the number of points once we have a good candidate solution to our fixed point problem.\n", "\n", "In order to make it easy to define interpolated functions, we define a new class of Python object" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "class LinInterp:\n", " \"Provides linear interpolation in one dimension.\"\n", "\n", " def __init__(self, X, Y):\n", " \"\"\"Parameters: X and Y are sequences or arrays\n", " containing the (x,y) interpolation points.\n", " \"\"\"\n", " self.X, self.Y = X, Y\n", "\n", " def __call__(self, z):\n", " \"\"\"Parameters: z is a number, sequence or array.\n", " This method makes an instance f of LinInterp callable,\n", " so f(z) returns the interpolation value(s) at z.\n", " \"\"\"\n", " if isinstance(z, int) or isinstance(z, float):\n", " return interp ([z], self.X, self.Y)[0] \n", " else:\n", " return interp(z, self.X, self.Y)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "We can now define our interpolated sinus function as follows" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "xp = np.linspace(0, np.pi, 10)\n", "yp = np.sin(xp)\n", "oursin = LinInterp(xp, yp)\n", "plt.plot(oursin(x));" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Optimal Growth" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Let's start by computing the solution to an optimal growth problem, in which a social planner seeks to find paths $\\{c_t,k_t\\}$ such that\n", "\n", "\\begin{align}\n", "\\max_{\\{c_t,k_t\\}}&\\sum_{t=0}^{\\infty}\\beta^{t}u(c_{t})\\\\[.2cm]\n", "\\text{s.t. }&k_{t+1}\\leq f(k_{t})+(1-\\delta)k_{t}-c_{t}\\\\[.2cm]\n", "c_{t}\\geq0,&\\ k_{t}\\geq0,\\ k_{0}\\text{ is given}.\n", "\\end{align}\n", "\n", "As usual we assume that our utility function $u(\\cdot)$ and production function $f(\\cdot)$ are Neoclassical. Under these conditions we have seen that our problem satisfies the conditions of our previous theorem and thus we _know_ a unique solution exists." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### An example with analytical solution" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Let's assume that $u(c)=\\ln(c)$, $f(k)=k^\\alpha$, and $\\delta=1$. For this case we have seen that the solution implies\n", "\n", "\\begin{align}\n", "&\\text{Value Function: } & V(k)=&\\frac{\\ln(1-\\alpha\\beta)}{1-\\beta}+\\frac{\\alpha\\beta\\ln(\\alpha\\beta)}{(1-\\alpha\\beta)(1-\\beta)}+\\frac{\\alpha}{1-\\alpha\\beta}\\ln(k)\\\\[.2cm]\n", "&\\text{Optimal Policy: } & \\pi\\left(k\\right)=&\\beta\\alpha k^{\\alpha} \\\\[.2cm]\n", "&\\text{Optimal Consumption Function: } & c=&\\left(1-\\beta\\alpha\\right)k^{\\alpha}\\\\[.2cm]\n", "\\end{align}\n", "\n", "We will use these to compare the solution found by iteration of the Value function described above. Copy the Python functions you had defined in the previous notebook into the cell below and define Python functions for the actual optimal solutions given above." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "%%file optgrowthfuncs.py\n", "def U(c, sigma=1):\n", " '''This function returns the value of utility when the CRRA\n", " coefficient is sigma. I.e. \n", " u(c,sigma)=(c**(1-sigma)-1)/(1-sigma) if sigma!=1 \n", " and \n", " u(c,sigma)=ln(c) if sigma==1\n", " Usage: u(c,sigma)\n", " '''\n", " if sigma!=1:\n", " u = (c**(1-sigma)-1) / (1-sigma)\n", " else:\n", " u = np.log(c)\n", " return u\n", "\n", "def F(K, L=1, alpha=.3, A=1):\n", " '''\n", " Cobb-Douglas production function\n", " F(K,L)=K^alpha L^(1-alpha)\n", " '''\n", " return A * K**alpha * L**(1-alpha)\n", "\n", "def Va(k, alpha=.3, beta=.9):\n", " ab = alpha*beta\n", " return np.log(1-ab) / (1-beta) + ab * np.log(ab) / ((1-beta) * (1-ab)) + alpha * np.log(k) / (1-ab)\n", "\n", "def opk(k, alpha=.3, beta=.9):\n", " return alpha * beta * k**alpha\n", "\n", "def opc(k, alpha=.3, beta=.9):\n", " return (1-alpha*beta)*k**alpha" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "# %load optgrowthfuncs.py\n", "def U(c, sigma=1):\n", " '''This function returns the value of utility when the CRRA\n", " coefficient is sigma. I.e. \n", " u(c,sigma)=(c**(1-sigma)-1)/(1-sigma) if sigma!=1 \n", " and \n", " u(c,sigma)=ln(c) if sigma==1\n", " Usage: u(c,sigma)\n", " '''\n", " if sigma!=1:\n", " u = (c**(1-sigma)-1) / (1-sigma)\n", " else:\n", " u = np.log(c)\n", " return u\n", "\n", "def F(K, L=1, alpha=.3, A=1):\n", " '''\n", " Cobb-Douglas production function\n", " F(K,L)=K^alpha L^(1-alpha)\n", " '''\n", " return A * K**alpha * L**(1-alpha)\n", "\n", "def Va(k, alpha=.3, beta=.9):\n", " ab = alpha*beta\n", " return np.log(1-ab) / (1-beta) + ab * np.log(ab) / ((1-beta) * (1-ab)) + alpha * np.log(k) / (1-ab)\n", "\n", "def opk(k, alpha=.3, beta=.9):\n", " return alpha * beta * k**alpha\n", "\n", "def opc(k, alpha=.3, beta=.9):\n", " return (1-alpha*beta)*k**alpha\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Let's fix the value of the fundamental parameters so we can realize computations" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "alpha = .3\n", "beta = .9\n", "sigma = 1\n", "delta = 1" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Now let's focus on the Value function iteration:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# Grid of values for state variable over which function will be approximated\n", "gridmin, gridmax, gridsize = 0.1, 5, 300\n", "grid = np.linspace(gridmin, gridmax**1e-1, gridsize)**10" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Here we have created a grid on $[gridmin,gridmax]$ that has a number of points given by gridsize. Since we know that the Value functions is stricly concave, our grid has more points closer to zero than farther away" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "plt.hist(grid, bins=50);\n", "plt.xlabel('State Space');\n", "plt.ylabel('Number of Points');" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "plt.plot(grid, grid,'r.');\n", "plt.title('State Space Grid');" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Now we need a function, which for given $V_0$ solves \n", "\n", "$$\\sup\\limits _{y\\in G(x)}\\left\\{ U(x,y)+\\beta V(y)\\right\\}.$$\n", "\n", "Let's use one of Scipy's optimizing routines" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "from scipy.optimize import fminbound\n", "fminbound?" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Since fminbound returns \n", "\n", "$$\\arg\\min\\limits _{y\\in [\\underline x,\\bar x]}\\left\\{ U(x,y)+\\beta V(y)\\right\\}$$\n", "\n", "we have to either replace our objective function for its negative or, better yet, define a function that uses fminbound and returns the maximum and the maximizer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# Maximize function V on interval [a,b]\n", "def maximum(V, a, b, **kwargs):\n", " return float(V(fminbound(lambda x: -V(x), a, b, **kwargs)))\n", "\n", "# Return Maximizer of function V on interval [a,b]\n", "def maximizer(V, a, b, **kwargs):\n", " return float(fminbound(lambda x: -V(x), a, b, **kwargs))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "### Note\n", "\n", "We could have included other parameters to pass to our maximizer and maximum functions, e.g. to allow us to manipulate the options of fminbound" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### The Bellman Operator" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# The following two functions are used to find the optimal policy and value functions using value function iteration\n", "# Bellman Operator\n", "def bellman(w):\n", " \"\"\"The approximate Bellman operator.\n", " Parameters: w is a LinInterp object (i.e., a \n", " callable object which acts pointwise on arrays).\n", " Returns: An instance of LinInterp that represents the optimal operator.\n", " w is a function defined on the state space.\n", " \"\"\"\n", " vals = []\n", " for k in grid:\n", " kmax = F(k, alpha=alpha) + (1-delta) * k\n", " h = lambda kp: U(kmax - kp, sigma) + beta * w(kp)\n", " vals.append(maximum(h, 0, kmax))\n", " return LinInterp(grid, vals)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "# Optimal policy\n", "def policy(w):\n", " \"\"\"\n", " For each function w, policy(w) returns the function that maximizes the \n", " RHS of the Bellman operator.\n", " Replace w for the Value function to get optimal policy.\n", " The approximate optimal policy operator w-greedy (See Stachurski (2009)). \n", " Parameters: w is a LinInterp object (i.e., a \n", " callable object which acts pointwise on arrays).\n", " Returns: An instance of LinInterp that captures the optimal policy.\n", " \"\"\"\n", " vals = []\n", " for k in grid:\n", " kmax = F(k,alpha=alpha) + (1-delta) * k\n", " h = lambda kp: U(kmax - kp,sigma) + beta * w(kp)\n", " vals.append(maximizer(h, 0, kmax))\n", " return LinInterp(grid, vals)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Given a linear interpolation of our guess for the Value function, $V_0=w$, the first function returns a LinInterp object, which is the linear interpolation of the function generated by the Bellman Operator on the finite set of points on the grid. The second function returns what Stachurski (2009) calls a _w-greedy_ policy, i.e. the function that maximizes the RHS of the Bellman Operator.\n", "\n", "Now we are ready to work on the iteration" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# Parameters for the optimization procedures\n", "count = 0\n", "maxiter = 1000\n", "tol = 1e-6\n", "print('tol=%f' % tol)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Our initial guess $V_0$" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "V0 = LinInterp(grid,U(grid))\n", "plt.figure(1)\n", "plt.plot(grid, V0(grid), label='V'+str(count));\n", "plt.plot(grid, Va(grid), label='Actual');\n", "plt.legend(loc=0);" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "After one interation" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "plt.plot(grid, V0(grid), label='V'+str(count));\n", "count += 1\n", "V0 = bellman(V0)\n", "plt.figure(1)\n", "plt.plot(grid, V0(grid), label='V'+str(count));\n", "plt.plot(grid, Va(grid), label='Actual');\n", "plt.legend(loc=0);\n", "plt.show();" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Doing it by hand is too slow..let's automate this process" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "fig, ax = plt.subplots()\n", "ax.set_xlim(grid.min(), grid.max())\n", "ax.plot(grid, Va(grid), label='Actual', color='k', lw=2, alpha=0.6);\n", "\n", "count=0\n", "maxiter=200\n", "tol=1e-6\n", "while count