{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "
\n", " \n", " \"QuantEcon\"\n", " \n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Default Risk and Income Fluctuations" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Contents\n", "\n", "- [Default Risk and Income Fluctuations](#Default-Risk-and-Income-Fluctuations) \n", " - [Overview](#Overview) \n", " - [Structure](#Structure) \n", " - [Equilibrium](#Equilibrium) \n", " - [Computation](#Computation) \n", " - [Results](#Results) \n", " - [Exercises](#Exercises) \n", " - [Solutions](#Solutions) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Overview\n", "\n", "This lecture computes versions of Arellano’s [[Are08]](zreferences.ipynb#arellano2008default) model of sovereign default\n", "\n", "The model describes interactions among default risk, output, and an equilibrium interest rate that includes a premium for endogenous default risk\n", "\n", "The decision maker is a government of a small open economy that borrows from risk-neutral foreign creditors\n", "\n", "The foreign lenders must be compensated for default risk\n", "\n", "The government borrows and lends abroad in order to smooth the consumption of its citizens\n", "\n", "The government repays its debt only if it wants to, but declining to pay has adverse consequences\n", "\n", "The interest rate on government debt adjusts in response to the state-dependent default probability chosen by government\n", "\n", "The model yields outcomes that help interpret sovereign default experiences, including\n", "\n", "- countercyclical interest rates on sovereign debt \n", "- countercyclical trade balances \n", "- high volatility of consumption relative to output \n", "\n", "\n", "Notably, long recessions caused by bad draws in the income process increase the government’s incentive to default\n", "\n", "This can lead to\n", "\n", "- spikes in interest rates \n", "- temporary losses of access to international credit markets \n", "- large drops in output, consumption, and welfare \n", "- large capital outflows during recessions \n", "\n", "\n", "Such dynamics are consistent with experiences of many countries" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Structure\n", "\n", "In this section we describe the main features of the model" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Output, Consumption and Debt\n", "\n", "A small open economy is endowed with an exogenous stochastically fluctuating potential output stream $ \\{y_t\\} $\n", "\n", "Potential output is realized only in periods in which the government honors its sovereign debt\n", "\n", "The output good can be traded or consumed\n", "\n", "The sequence $ \\{y_t\\} $ is described by a Markov process with stochastic density kernel $ p(y, y') $\n", "\n", "Households within the country are identical and rank stochastic consumption streams according to\n", "\n", "\n", "\n", "$$\n", "\\mathbb E \\sum_{t=0}^{\\infty} \\beta^t u(c_t) \\tag{1}\n", "$$\n", "\n", "Here\n", "\n", "- $ 0 < \\beta < 1 $ is a time discount factor \n", "- $ u $ is an increasing and strictly concave utility function \n", "\n", "\n", "Consumption sequences enjoyed by households are affected by the government’s decision to borrow or lend internationally\n", "\n", "The government is benevolent in the sense that its aim is to maximize [(1)](#equation-utility)\n", "\n", "The government is the only domestic actor with access to foreign credit\n", "\n", "Because household are averse to consumption fluctuations, the government will try to smooth consumption by borrowing from (and lending to) foreign creditors" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Asset Markets\n", "\n", "The only credit instrument available to the government is a one-period bond traded in international credit markets\n", "\n", "The bond market has the following features\n", "\n", "- The bond matures in one period and is not state contingent \n", "- A purchase of a bond with face value $ B' $ is a claim to $ B' $ units of the\n", " consumption good next period \n", "- To purchase $ B' $ next period costs $ q B' $ now, or, what is equivalent \n", "- For selling $ -B' $ units of next period goods the seller earns $ - q B' $ of today’s goods \n", " \n", " - if $ B' < 0 $, then $ -q B' $ units of the good are received in the current period, for a promise to repay $ -B' $ units next period \n", " - there is an equilibrium price function $ q(B', y) $ that makes $ q $ depend on both $ B' $ and $ y $ \n", " \n", "\n", "\n", "Earnings on the government portfolio are distributed (or, if negative, taxed) lump sum to households\n", "\n", "When the government is not excluded from financial markets, the one-period national budget constraint is\n", "\n", "\n", "\n", "$$\n", "c = y + B - q(B', y) B' \\tag{2}\n", "$$\n", "\n", "Here and below, a prime denotes a next period value or a claim maturing next period\n", "\n", "To rule out Ponzi schemes, we also require that $ B \\geq -Z $ in every period\n", "\n", "- $ Z $ is chosen to be sufficiently large that the constraint never binds in equilibrium " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Financial Markets\n", "\n", "Foreign creditors\n", "\n", "- are risk neutral \n", "- know the domestic output stochastic process $ \\{y_t\\} $ and observe $ y_t, y_{t-1}, \\ldots, $ at time $ t $ \n", "- can borrow or lend without limit in an international credit market at a constant international interest rate $ r $ \n", "- receive full payment if the government chooses to pay \n", "- receive zero if the government defaults on its one-period debt due \n", "\n", "\n", "When a government is expected to default next period with probability $ \\delta $, the expected value of a promise to pay one unit of consumption next period is $ 1 - \\delta $.\n", "\n", "Therefore, the discounted expected value of a promise to pay $ B $ next period is\n", "\n", "\n", "\n", "$$\n", "q = \\frac{1 - \\delta}{1 + r} \\tag{3}\n", "$$\n", "\n", "Next we turn to how the government in effect chooses the default probability $ \\delta $" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Government’s decisions\n", "\n", "At each point in time $ t $, the government chooses between\n", "\n", "1. defaulting \n", "1. meeting its current obligations and purchasing or selling an optimal quantity of one-period sovereign debt \n", "\n", "\n", "Defaulting means declining to repay all of its current obligations\n", "\n", "If the government defaults in the current period, then consumption equals current output\n", "\n", "But a sovereign default has two consequences:\n", "\n", "1. Output immediately falls from $ y $ to $ h(y) $, where $ 0 \\leq h(y) \\leq y $ \n", " \n", " - it returns to $ y $ only after the country regains access to international credit markets \n", " \n", "1. The country loses access to foreign credit markets " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Reentering international credit market\n", "\n", "While in a state of default, the economy regains access to\n", "foreign credit in each subsequent period with probability\n", "$ \\theta $" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Equilibrium\n", "\n", "Informally, an equilibrium is a sequence of interest rates on its sovereign debt, a stochastic sequence of government default decisions and an implied flow of household consumption such that\n", "\n", "1. Consumption and assets satisfy the national budget constraint \n", "1. The government maximizes household utility taking into account \n", " - the resource constraint \n", " - the effect of its choices on the price of bonds \n", " - consequences of defaulting now for future net output and future borrowing and lending opportunities \n", "1. The interest rate on the government’s debt includes a risk-premium sufficient to make foreign creditors expect on average to earn the constant risk-free international interest rate \n", "\n", "\n", "To express these ideas more precisely, consider first the choices of the\n", "government, which\n", "\n", "1. enters a period with initial assets $ B $, or what is the same thing, initial debt to be repaid now of $ -B $ \n", "1. observes current output $ y $, and \n", "1. chooses either \n", " \n", " 1. to default, or \n", " 1. to pay $ -B $ and set next period’s debt due to $ -B' $ \n", " \n", "\n", "\n", "In a recursive formulation,\n", "\n", "- state variables for the government comprise the pair $ (B, y) $ \n", "- $ v(B, y) $ is the optimum value of the government’s problem when at the beginning of a period it faces the choice of whether to honor or default \n", "- $ v_c(B, y) $ is the value of choosing to pay obligations falling due \n", "- $ v_d(y) $ is the value of choosing to default \n", "\n", "\n", "$ v_d(y) $ does not depend on $ B $ because, when access to credit is eventually regained, net foreign assets equal $ 0 $\n", "\n", "Expressed recursively, the value of defaulting is\n", "\n", "$$\n", "v_d(y) = u(h(y)) +\n", " \\beta \\int \\left\\{\n", " \\theta v(0, y') + (1 - \\theta) v_d(y')\n", " \\right\\}\n", " p(y, y') dy'\n", "$$\n", "\n", "The value of paying is\n", "\n", "$$\n", "v_c(B, y) = \\max_{B' \\geq -Z}\n", " \\left\\{\n", " u(y - q(B', y) B' + B) +\n", " \\beta \\int v(B', y') p(y, y') dy'\n", " \\right\\}\n", "$$\n", "\n", "The three value functions are linked by\n", "\n", "$$\n", "v(B, y) = \\max\\{ v_c(B, y), v_d(y) \\}\n", "$$\n", "\n", "The government chooses to default when\n", "\n", "$$\n", "v_c(B, y) < v_d(y)\n", "$$\n", "\n", "and hence given $ B' $ the probability of default next period is\n", "\n", "\n", "\n", "$$\n", "\\delta(B', y) := \\int \\mathbb 1\\{v_c(B', y') < v_d(y') \\} p(y, y') dy' \\tag{4}\n", "$$\n", "\n", "Given zero profits for foreign creditors in equilibrium, we can combine [(3)](#equation-epc) and [(4)](#equation-delta) to pin down\n", "the bond price function:\n", "\n", "\n", "\n", "$$\n", "q(B', y) = \\frac{1 - \\delta(B', y)}{1 + r} \\tag{5}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Definition of equilibrium\n", "\n", "An *equilibrium* is\n", "\n", "- a pricing function $ q(B',y) $, \n", "- a triple of value functions $ (v_c(B, y), v_d(y), v(B,y)) $, \n", "- a decision rule telling the government when to default and when to pay as a function of the state $ (B, y) $, and \n", "- an asset accumulation rule that, conditional on choosing not to default, maps $ (B,y) $ into $ B' $ \n", "\n", "\n", "such that\n", "\n", "- The three Bellman equations for $ (v_c(B, y), v_d(y), v(B,y)) $ are satisfied \n", "- Given the price function $ q(B',y) $, the default decision rule and the asset accumulation decision rule attain the optimal value function $ v(B,y) $, and \n", "- The price function $ q(B',y) $ satisfies equation [(5)](#equation-bondprice) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Computation\n", "\n", "Let’s now compute an equilibrium of Arellano’s model\n", "\n", "The equilibrium objects are the value function $ v(B, y) $, the associated default decision rule, and the pricing function $ q(B', y) $\n", "\n", "We’ll use our code to replicate Arellano’s results\n", "\n", "After that we’ll perform some additional simulations\n", "\n", "It uses a slightly modified version of the algorithm recommended by Arellano\n", "\n", "- The appendix to [[Are08]](zreferences.ipynb#arellano2008default) recommends\n", " value function iteration until convergence, updating the price, and then repeating \n", "- Instead, we update the bond price at every value function iteration step \n", "\n", "\n", "The second approach is faster and the two different procedures deliver very similar results\n", "\n", "Here is a more detailed description of our algorithm:\n", "\n", "1. Guess a value function $ v(B, y) $ and price function $ q(B', y) $ \n", "1. At each pair $ (B, y) $, \n", " - update the value of defaulting $ v_d(y) $ \n", " - update the value of continuing $ v_c(B, y) $ \n", "1. Update the value function v(B, y), the default rule, the implied ex ante default probability, and the price function \n", "1. Check for convergence. If converged, stop. If not, go to step 2. \n", "\n", "\n", "We use simple discretization on a grid of asset holdings and income levels\n", "\n", "The output process is discretized using [Tauchen’s quadrature method](https://github.com/QuantEcon/QuantEcon.jl/blob/master/src/markov/markov_approx.jl)\n", "\n", "The code can be found below:\n", "\n", "(Results and discussion follow the code)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Setup" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hide-output": true }, "outputs": [], "source": [ "using InstantiateFromURL\n", "github_project(\"QuantEcon/quantecon-notebooks-julia\", version = \"0.2.0\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hide-output": true }, "outputs": [], "source": [ "using LinearAlgebra, Statistics, Compat\n", "using Parameters, QuantEcon, DataFrames, Plots, Random" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hide-output": false }, "outputs": [], "source": [ "function ArellanoEconomy(;β = .953,\n", " γ = 2.,\n", " r = 0.017,\n", " ρ = 0.945,\n", " η = 0.025,\n", " θ = 0.282,\n", " ny = 21,\n", " nB = 251)\n", "\n", " # create grids\n", " Bgrid = collect(range(-.4, .4, length = nB))\n", " mc = tauchen(ny, ρ, η)\n", " Π = mc.p\n", " ygrid = exp.(mc.state_values)\n", " ydefgrid = min.(.969 * mean(ygrid), ygrid)\n", "\n", " # define value functions\n", " # notice ordered different than Python to take\n", " # advantage of column major layout of Julia)\n", " vf = zeros(nB, ny)\n", " vd = zeros(1, ny)\n", " vc = zeros(nB, ny)\n", " policy = zeros(nB, ny)\n", " q = ones(nB, ny) .* (1 / (1 + r))\n", " defprob = zeros(nB, ny)\n", "\n", " return (β = β, γ = γ, r = r, ρ = ρ, η = η, θ = θ, ny = ny,\n", " nB = nB, ygrid = ygrid, ydefgrid = ydefgrid,\n", " Bgrid = Bgrid, Π = Π, vf = vf, vd = vd, vc = vc,\n", " policy = policy, q = q, defprob = defprob)\n", "end\n", "\n", "u(ae, c) = c^(1 - ae.γ) / (1 - ae.γ)\n", "\n", "function one_step_update!(ae,\n", " EV,\n", " EVd,\n", " EVc)\n", "\n", " # unpack stuff\n", " @unpack β, γ, r, ρ, η, θ, ny, nB = ae\n", " @unpack ygrid, ydefgrid, Bgrid, Π, vf, vd, vc, policy, q, defprob = ae\n", " zero_ind = searchsortedfirst(Bgrid, 0.)\n", "\n", " for iy in 1:ny\n", " y = ae.ygrid[iy]\n", " ydef = ae.ydefgrid[iy]\n", "\n", " # value of being in default with income y\n", " defval = u(ae, ydef) + β * (θ * EVc[zero_ind, iy] + (1-θ) * EVd[1, iy])\n", " ae.vd[1, iy] = defval\n", "\n", " for ib in 1:nB\n", " B = ae.Bgrid[ib]\n", "\n", " current_max = -1e14\n", " pol_ind = 0\n", " for ib_next=1:nB\n", " c = max(y - ae.q[ib_next, iy]*Bgrid[ib_next] + B, 1e-14)\n", " m = u(ae, c) + β * EV[ib_next, iy]\n", "\n", " if m > current_max\n", " current_max = m\n", " pol_ind = ib_next\n", " end\n", "\n", " end\n", "\n", " # update value and policy functions\n", " ae.vc[ib, iy] = current_max\n", " ae.policy[ib, iy] = pol_ind\n", " ae.vf[ib, iy] = defval > current_max ? defval : current_max\n", " end\n", " end\n", "end\n", "\n", "function compute_prices!(ae)\n", " # unpack parameters\n", " @unpack β, γ, r, ρ, η, θ, ny, nB = ae\n", "\n", " # create default values with a matching size\n", " vd_compat = repeat(ae.vd, nB)\n", " default_states = vd_compat .> ae.vc\n", "\n", " # update default probabilities and prices\n", " copyto!(ae.defprob, default_states * ae.Π')\n", " copyto!(ae.q, (1 .- ae.defprob) / (1 + r))\n", " return\n", "end\n", "\n", "function vfi!(ae; tol = 1e-8, maxit = 10000)\n", "\n", " # unpack stuff\n", " @unpack β, γ, r, ρ, η, θ, ny, nB = ae\n", " @unpack ygrid, ydefgrid, Bgrid, Π, vf, vd, vc, policy, q, defprob = ae\n", " Πt = Π'\n", "\n", " # Iteration stuff\n", " it = 0\n", " dist = 10.\n", "\n", " # allocate memory for update\n", " V_upd = similar(ae.vf)\n", "\n", " while dist > tol && it < maxit\n", " it += 1\n", "\n", " # compute expectations for this iterations\n", " # (we need Π' because of order value function dimensions)\n", " copyto!(V_upd, ae.vf)\n", " EV = ae.vf * Πt\n", " EVd = ae.vd * Πt\n", " EVc = ae.vc * Πt\n", "\n", " # update value function\n", " one_step_update!(ae, EV, EVd, EVc)\n", "\n", " # update prices\n", " compute_prices!(ae)\n", "\n", " dist = maximum(abs(x - y) for (x, y) in zip(V_upd, ae.vf))\n", "\n", " if it % 25 == 0\n", " println(\"Finished iteration $(it) with dist of $(dist)\")\n", " end\n", " end\n", "end\n", "\n", "function QuantEcon.simulate(ae,\n", " capT = 5000;\n", " y_init = mean(ae.ygrid),\n", " B_init = mean(ae.Bgrid),\n", " )\n", "\n", " # get initial indices\n", " zero_index = searchsortedfirst(ae.Bgrid, 0.)\n", " y_init_ind = searchsortedfirst(ae.ygrid, y_init)\n", " B_init_ind = searchsortedfirst(ae.Bgrid, B_init)\n", "\n", " # create a QE MarkovChain\n", " mc = MarkovChain(ae.Π)\n", " y_sim_indices = simulate(mc, capT + 1; init = y_init_ind)\n", "\n", " # allocate and fill output\n", " y_sim_val = zeros(capT+1)\n", " B_sim_val, q_sim_val = similar(y_sim_val), similar(y_sim_val)\n", " B_sim_indices = fill(0, capT + 1)\n", " default_status = fill(false, capT + 1)\n", " B_sim_indices[1], default_status[1] = B_init_ind, false\n", " y_sim_val[1], B_sim_val[1] = ae.ygrid[y_init_ind], ae.Bgrid[B_init_ind]\n", "\n", " for t in 1:capT\n", " # get today's indexes\n", " yi, Bi = y_sim_indices[t], B_sim_indices[t]\n", " defstat = default_status[t]\n", "\n", " # if you are not in default\n", " if !defstat\n", " default_today = ae.vc[Bi, yi] < ae.vd[yi]\n", "\n", " if default_today\n", " # default values\n", " default_status[t] = true\n", " default_status[t + 1] = true\n", " y_sim_val[t] = ae.ydefgrid[y_sim_indices[t]]\n", " B_sim_indices[t + 1] = zero_index\n", " B_sim_val[t+1] = 0.\n", " q_sim_val[t] = ae.q[zero_index, y_sim_indices[t]]\n", " else\n", " default_status[t] = false\n", " y_sim_val[t] = ae.ygrid[y_sim_indices[t]]\n", " B_sim_indices[t + 1] = ae.policy[Bi, yi]\n", " B_sim_val[t + 1] = ae.Bgrid[B_sim_indices[t + 1]]\n", " q_sim_val[t] = ae.q[B_sim_indices[t + 1], y_sim_indices[t]]\n", " end\n", "\n", " # if you are in default\n", " else\n", " B_sim_indices[t + 1] = zero_index\n", " B_sim_val[t+1] = 0.\n", " y_sim_val[t] = ae.ydefgrid[y_sim_indices[t]]\n", " q_sim_val[t] = ae.q[zero_index, y_sim_indices[t]]\n", "\n", " # with probability θ exit default status\n", " default_status[t + 1] = rand() ≥ ae.θ\n", " end\n", " end\n", "\n", " return (y_sim_val[1:capT], B_sim_val[1:capT], q_sim_val[1:capT],\n", " default_status[1:capT])\n", "end" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Results\n", "\n", "Let’s start by trying to replicate the results obtained in [[Are08]](zreferences.ipynb#arellano2008default)\n", "\n", "In what follows, all results are computed using Arellano’s parameter values\n", "\n", "The values can be seen in the function ArellanoEconomy shown above\n", "\n", "- For example, r=0.017 matches the average quarterly rate on a 5 year US treasury\n", " over the period 1983–2001 \n", "\n", "\n", "Details on how to compute the figures are reported as solutions to the exercises\n", "\n", "The first figure shows the bond price schedule and replicates Figure 3 of Arellano, where $ y_L $ and $ Y_H $ are particular below average and above average values of output $ y $\n", "\n", "![_static/figures/arellano_bond_prices.png](_static/figures/arellano_bond_prices.png) \n", "- $ y_L $ is 5% below the mean of the $ y $ grid values \n", "- $ y_H $ is 5% above the mean of the $ y $ grid values \n", "\n", "\n", "The grid used to compute this figure was relatively coarse (ny, nB = 21, 251) in order to match Arrelano’s findings\n", "\n", "Here’s the same relationships computed on a finer grid (ny, nB = 51, 551)\n", "\n", "![_static/figures/arellano_bond_prices_2.png](_static/figures/arellano_bond_prices_2.png) \n", "In either case, the figure shows that\n", "\n", "- Higher levels of debt (larger $ -B' $) induce larger discounts on the face value, which correspond to higher interest rates \n", "- Lower income also causes more discounting, as foreign creditors anticipate greater likelihood of default \n", "\n", "\n", "The next figure plots value functions and replicates the right hand panel of Figure 4 of [[Are08]](zreferences.ipynb#arellano2008default)\n", "\n", "![_static/figures/arellano_value_funcs.png](_static/figures/arellano_value_funcs.png) \n", "We can use the results of the computation to study the default probability\n", "$ \\delta(B', y) $ defined in [(4)](#equation-delta)\n", "\n", "The next plot shows these default probabilities over $ (B', y) $ as a heat\n", "map\n", "\n", "![_static/figures/arellano_default_probs.png](_static/figures/arellano_default_probs.png) \n", "As anticipated, the probability that the government chooses to default in the\n", "following period increases with indebtedness and falls with income\n", "\n", "Next let’s run a time series simulation of $ \\{y_t\\} $, $ \\{B_t\\} $ and $ q(B_{t+1}, y_t) $\n", "\n", "The grey vertical bars correspond to periods when the economy is excluded from financial markets because of a past default\n", "\n", "![_static/figures/arellano_time_series.png](_static/figures/arellano_time_series.png) \n", "One notable feature of the simulated data is the nonlinear response of interest rates\n", "\n", "Periods of relative stability are followed by sharp spikes in the discount rate on government debt" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercises\n", "\n", "\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise 1\n", "\n", "To the extent that you can, replicate the figures shown above\n", "\n", "- Use the parameter values listed as defaults in the function ArellanoEconomy \n", "- The time series will of course vary depending on the shock draws " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Solutions" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hide-output": false }, "outputs": [], "source": [ "using DataFrames, Plots\n", "gr(fmt=:png);" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Compute the value function, policy and equilibrium prices" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hide-output": false }, "outputs": [], "source": [ "ae = ArellanoEconomy(β = .953, # time discount rate\n", " γ = 2., # risk aversion\n", " r = 0.017, # international interest rate\n", " ρ = .945, # persistence in output\n", " η = 0.025, # st dev of output shock\n", " θ = 0.282, # prob of regaining access\n", " ny = 21, # number of points in y grid\n", " nB = 251) # number of points in B grid\n", "\n", "# now solve the model on the grid.\n", "vfi!(ae)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Compute the bond price schedule as seen in figure 3 of Arellano (2008)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hide-output": false }, "outputs": [], "source": [ "# create \"Y High\" and \"Y Low\" values as 5% devs from mean\n", "high, low = 1.05 * mean(ae.ygrid), 0.95 * mean(ae.ygrid)\n", "iy_high, iy_low = map(x -> searchsortedfirst(ae.ygrid, x), (high, low))\n", "\n", "# extract a suitable plot grid\n", "x = zeros(0)\n", "q_low = zeros(0)\n", "q_high = zeros(0)\n", "for i in 1:ae.nB\n", " b = ae.Bgrid[i]\n", " if -0.35 ≤ b ≤ 0 # to match fig 3 of Arellano\n", " push!(x, b)\n", " push!(q_low, ae.q[i, iy_low])\n", " push!(q_high, ae.q[i, iy_high])\n", " end\n", "end\n", "\n", "# generate plot\n", "plot(x, q_low, label = \"Low\")\n", "plot!(x, q_high, label = \"High\")\n", "plot!(title = \"Bond price schedule q(y, B')\",\n", " xlabel = \"B'\", ylabel = \"q\", legend_title = \"y\", legend = :topleft)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Draw a plot of the value functions" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hide-output": false }, "outputs": [], "source": [ "plot(ae.Bgrid, ae.vf[:, iy_low], label = \"Low\")\n", "plot!(ae.Bgrid, ae.vf[:, iy_high], label = \"High\")\n", "plot!(xlabel = \"B\", ylabel = \"V(y,B)\", title = \"Value functions\",\n", " legend_title=\"y\", legend = :topleft)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Draw a heat map for default probability" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hide-output": false }, "outputs": [], "source": [ "plot(seriestype = :heatmap, ae.Bgrid[1:end-1],\n", " ae.ygrid[2:end],\n", " clamp.(vec(ae.defprob[1:end - 1, 1:end - 1]), 0, 1))\n", "plot!(xlabel = \"B'\", ylabel = \"y\", title = \"Probability of default\",\n", " legend = :topleft)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Plot a time series of major variables simulated from the model" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hide-output": false }, "outputs": [], "source": [ "using Random\n", "# set random seed for consistent result\n", "Random.seed!(348938)\n", "\n", "# simulate\n", "T = 250\n", "y_vec, B_vec, q_vec, default_vec = simulate(ae, T)\n", "\n", "# find starting and ending periods of recessions\n", "defs = findall(default_vec)\n", "def_breaks = diff(defs) .> 1\n", "def_start = defs[[true; def_breaks]]\n", "def_end = defs[[def_breaks; true]]\n", "\n", "y_vals = [y_vec, B_vec, q_vec]\n", "titles = [\"Output\", \"Foreign assets\", \"Bond price\"]\n", "\n", "plots = plot(layout = (3, 1), size = (700, 800))\n", "\n", "# Plot the three variables, and for each each variable shading the period(s) of default\n", "# in grey\n", "for i in 1:3\n", " plot!(plots[i], 1:T, y_vals[i], title = titles[i], xlabel = \"time\", label = \"\", lw = 2)\n", " for j in 1:length(def_start)\n", " plot!(plots[i], [def_start[j], def_end[j]], fill(maximum(y_vals[i]), 2),\n", " fill_between = extrema(y_vals[i]), fcolor = :grey, falpha = 0.3, label = \"\")\n", " end\n", "end\n", "\n", "plot(plots)" ] } ], "metadata": { "filename": "arellano.rst", "kernelspec": { "display_name": "Julia 1.2", "language": "julia", "name": "julia-1.2" }, "title": "Default Risk and Income Fluctuations" }, "nbformat": 4, "nbformat_minor": 2 }