├── Dockerfile ├── README.md ├── images ├── SIRElogolweb.jpg ├── SIRElogoweb.jpg └── sgpe-logo.jpg ├── index.ipynb └── labs ├── introduction ├── Introduction to Statistics-Blank.ipynb ├── Introduction to Statistics.ipynb ├── Kerrich.txt ├── clt_graphic.py ├── exercise1.py ├── exercise2.py ├── exercise3.py ├── exercise4.py └── exercise5.py ├── lab-1 ├── .ipynb_checkpoints │ ├── Solow Model (continuous)-checkpoint.ipynb │ ├── Untitled0-checkpoint.ipynb │ ├── lab-1 (blank)-checkpoint.ipynb │ ├── lab-1 HW (answer guide)-checkpoint.ipynb │ ├── lab-1 HW-checkpoint.ipynb │ ├── lab-1-checkpoint.ipynb │ └── working-checkpoint.ipynb ├── depreciation_rates.dta ├── exercise_3a.py ├── exercise_3b.py ├── exercise_3c.py ├── exercise_4a.py ├── exercise_4b.py ├── exercise_4c.py ├── exercise_4d.py ├── exercise_4e.py ├── graphics │ └── Classic-Solow-Diagram.png ├── growth.py ├── growth.pyc ├── hw-assignments │ ├── group-1 lab-1.ipynb │ ├── group-10-lab-1.ipynb │ ├── group-2-lab-1.ipynb │ ├── group-3-lab-1.ipynb │ ├── group-4-lab-1.ipynb │ ├── group-5-lab-1.ipynb │ ├── group-6-lab-1.ipynb │ ├── group-7-lab-1.ipynb │ ├── group-8-lab-1.ipynb │ └── group-9-lab-1.ipynb ├── integrators.py ├── integrators.pyc ├── lab-1 (blank).ipynb ├── lab-1 HW (answer guide).ipynb ├── lab-1 HW.ipynb ├── lab-1.ipynb ├── pwt.py ├── pwt.pyc ├── pwt80.dta ├── solow-analytic-solution.pdf ├── solow.py ├── solvers.py ├── solvers.pyc ├── steady_states.py ├── steady_states.pyc └── working.ipynb ├── lab-2 ├── .ipynb_checkpoints │ ├── Ramsey Model (continuous)-checkpoint.ipynb │ ├── Ramsey Model-checkpoint.ipynb │ ├── lab 2 HW-checkpoint.ipynb │ └── lab-2-checkpoint.ipynb ├── Ramsey Model (continuous).ipynb ├── Ramsey Model.ipynb ├── Ramsey Model.py ├── Ramsey Notes.aux ├── Ramsey Notes.log ├── Ramsey Notes.out ├── Ramsey Notes.pdf ├── Ramsey Notes.synctex.gz ├── Ramsey Notes.tex ├── contour_plots.py ├── diagram.py ├── diagram2.py ├── exercise_4a.py ├── exercise_4b.py ├── exercise_4c.py ├── exercise_5a.py ├── exercise_5b.py ├── graphics │ ├── CRRA Utility.png │ ├── CRRA-Utility-Surface.png │ ├── CRRA-utility.png │ ├── Comparing-marginal-utilities.png │ ├── Contour-plot-for-CRRA-utility-surface.png │ ├── deviations-from-MS-MU.png │ └── ramsey-phase-diagram-with-manifolds.png ├── integrators.py ├── integrators.pyc ├── lab 2 HW.ipynb ├── lab-2.ipynb ├── pwt.py ├── pwt.pyc ├── ramsey.py ├── ramsey.pyc ├── solvers.py ├── solvers.pyc ├── steady_states.py └── steady_states.pyc ├── lab-3 ├── .ipynb_checkpoints │ ├── lab-3 hw-checkpoint.ipynb │ └── lab-3-checkpoint.ipynb ├── Deaton (1991).pdf ├── Pal and Stachurski (2012).pdf ├── hw-assignments │ ├── Gropu 7 or 8 (Jose Viada Galvez) lab-3 hw.ipynb │ ├── Group 1 lab-3 hw.ipynb │ ├── Group 10 lab-3 hw.ipynb │ ├── Group 2 lab-3 hw.ipynb │ ├── Group 3 lab-3 hw.ipynb │ ├── Group 4 lab-3 hw.ipynb │ ├── Group 5 lab-3 hw.ipynb │ ├── Group 6 lab-3 hw.ipynb │ └── Group 9 lab-3 hw.ipynb ├── lab-3 hw.ipynb ├── lab-3 hw.pdf └── lab-3.ipynb ├── lab-4 ├── .ipynb_checkpoints │ ├── lab-4 HW (answers)-checkpoint.ipynb │ ├── lab-4 HW-checkpoint.ipynb │ └── lab-4-checkpoint.ipynb ├── Dynare Reference Manual.pdf ├── Dynare User Guide.pdf ├── Dynare++ Tutorial.pdf ├── assignment-7.ipynb ├── christiano-course │ ├── Solving_and_Simulating.zip │ ├── Solving_and_Simulating │ │ ├── anothertest.m │ │ ├── plott.m │ │ ├── pltt.m │ │ ├── readme.m │ │ ├── run.m │ │ └── second.m │ ├── rbc.zip │ └── rbc │ │ ├── rbc.mod │ │ ├── rbc_steadystate_1.m │ │ └── ssrbc.m ├── graphics │ ├── Consumption for fixed C and l.png │ ├── RBC contour plot for utility surface 1 period decision problem.png │ ├── RBC contour plot for utility surface, 2 period choice problem, t=0.png │ ├── RBC contour plot for utility surface, 2 period choice problem, t=1.png │ ├── RBC contour plot for utility surface.png │ ├── RBC-utility-surface.png │ ├── Taylor-approximation-example.pdf │ ├── Taylor-approximation-example.png │ └── deterministic-taylor-approximation-example.png ├── hw-assignments │ ├── group-1-lab-4.ipynb │ ├── group-10-lab-4.ipynb │ ├── group-2-lab-4.ipynb │ ├── group-3-lab-4.ipynb │ ├── group-4-lab-4.ipynb │ ├── group-5-lab-4.ipynb │ ├── group-6-lab-4.ipynb │ ├── group-7-lab-4.ipynb │ ├── group-9-lab-4.ipynb │ ├── lab-4 HW (answers).ipynb │ └── rbc_benchmark_HW.mod ├── lab-4 HW.ipynb ├── lab-4.ipynb ├── literature │ ├── Aruoba et al. (2006).pdf │ ├── Bernanke, Gertler, and Glichrist (1999).pdf │ ├── Christiano, Eichenbaum and Evans (2005).pdf │ ├── Collard and Juillard (2001a).pdf │ ├── Collard and Juillard (2001b).pdf │ ├── Schmitt-Grohe and Uribe (2004).pdf │ ├── Smets and Wouters (2003).pdf │ └── Smets and Wouters (2007).pdf ├── rbc_benchmark.mod ├── rbc_benchmark_answers.dump ├── rbc_benchmark_answers.jnl ├── rbc_benchmark_answers.mat ├── rbc_benchmark_answers.mod ├── rbc_benchmark_answers_f.m ├── rbc_benchmark_answers_ff.m ├── rbc_benchmark_f.m ├── rbc_benchmark_ff.m └── rbc_example.mod └── lab-5 ├── .ipynb_checkpoints └── lab-5-checkpoint.ipynb ├── Untitled0.ipynb └── lab-5.ipynb /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM andrewosh/binder-base 2 | 3 | MAINTAINER davidrpugh 4 | 5 | USER root 6 | 7 | # Install Dynare 8 | RUN apt-get update && \ 9 | apt-get install -y --no-install-recommends dynare && \ 10 | apt-get clean && \ 11 | rm -rf /var/lib/apt/lists/* 12 | 13 | # Install additional Python dependencies 14 | RUN conda update conda && \ 15 | conda install -y seaborn 16 | 17 | USER main 18 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Binder](http://mybinder.org/badge.svg)](http://mybinder.org/repo/davidrpugh/numerical-methods) 2 | 3 | numerical-methods 4 | ================= 5 | 6 | Graduate level course on numerical methods for economists... 7 | -------------------------------------------------------------------------------- /images/SIRElogolweb.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/images/SIRElogolweb.jpg -------------------------------------------------------------------------------- /images/SIRElogoweb.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/images/SIRElogoweb.jpg -------------------------------------------------------------------------------- /images/sgpe-logo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/images/sgpe-logo.jpg -------------------------------------------------------------------------------- /index.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "

Numerical methods for Economists

\n", 8 | "\n", 9 | "A short, lab-based graduate course on numerical methods for economists. Current materials include:\n", 10 | "
    \n", 11 | "
  1. Lab 1: Solow growth model
  2. \n", 12 | "
  3. Lab 2: Ramsey-Cass-Koopmans optimal savings model
  4. \n", 13 | "
  5. Lab 3: Numerical Dynamic Programming
  6. \n", 14 | "
  7. Lab 4: Real Business Cycle (RBC) models:
  8. \n", 15 | "
" 16 | ] 17 | }, 18 | { 19 | "cell_type": "code", 20 | "execution_count": null, 21 | "metadata": { 22 | "collapsed": true 23 | }, 24 | "outputs": [], 25 | "source": [] 26 | } 27 | ], 28 | "metadata": { 29 | "kernelspec": { 30 | "display_name": "Python 3", 31 | "language": "python", 32 | "name": "python3" 33 | }, 34 | "language_info": { 35 | "codemirror_mode": { 36 | "name": "ipython", 37 | "version": 3 38 | }, 39 | "file_extension": ".py", 40 | "mimetype": "text/x-python", 41 | "name": "python", 42 | "nbconvert_exporter": "python", 43 | "pygments_lexer": "ipython3", 44 | "version": "3.4.4" 45 | } 46 | }, 47 | "nbformat": 4, 48 | "nbformat_minor": 0 49 | } 50 | -------------------------------------------------------------------------------- /labs/introduction/Kerrich.txt: -------------------------------------------------------------------------------- 1 | Tosses,Heads,Difference 2 | 10,4,-1 3 | 20,10,0 4 | 30,17,2 5 | 40,21,1 6 | 50,25,0 7 | 60,29,-1 8 | 70,32,-3 9 | 80,35,-5 10 | 90,40,-5 11 | 100,44,-6 12 | 200,98,-2 13 | 300,146,-4 14 | 400,199,-1 15 | 500,255,5 16 | 600,312,12 17 | 700,368,18 18 | 800,413,13 19 | 900,458,8 20 | 1000,502,2 21 | 2000,1013,13 22 | 3000,1510,10 23 | 4000,2029,29 24 | 5000,2533,33 25 | 6000,3009,9 26 | 7000,3516,16 27 | 8000,4034,34 28 | 9000,4538,38 29 | 10000,5067,67 30 | -------------------------------------------------------------------------------- /labs/introduction/clt_graphic.py: -------------------------------------------------------------------------------- 1 | # create new Figure object 2 | fig = plt.figure(figsize(10, 12)) 3 | 4 | # create the first subplot 5 | ax1 = fig.add_subplot(321) 6 | 7 | # add the histogram of the first row of sample averages. 8 | n, bins, patches = ax1.hist(sample_averages[0,:], bins=np.arange(0.5, 7, 1), 9 | align='mid', normed=True) 10 | 11 | # don't forget to label axes! 12 | ylabel = ax1.set_ylabel('Density') 13 | ylabel.set_family('serif') 14 | 15 | # add a title! 16 | title = ax1.set_title('T=1') 17 | title.set_family('serif') 18 | 19 | # create the second subplot 20 | ax2 = fig.add_subplot(322) 21 | 22 | n, bins, patches = ax2.hist(sample_averages[49,:], bins=25, align='mid', normed=True) 23 | 24 | x = np.linspace(0, 7, 1000) 25 | normal = stats.distributions.norm(loc=mu, scale=sigma / np.sqrt(49)) 26 | ax2.plot(x, normal.pdf(x), 'r--', label=r'$N\left(\mu,\ \frac{\sigma}{\sqrt{T}}\right)$') 27 | 28 | # don't forget to label axes! 29 | ylabel = ax2.set_ylabel('Density') 30 | ylabel.set_family('serif') 31 | 32 | # set the title 33 | ax2.set_title('T=50') 34 | 35 | # create the third subplot 36 | ax3 = fig.add_subplot(323) 37 | 38 | n, bins, patches = ax3.hist(sample_averages[1,:], bins=np.arange(0.5, 7, 1), align='mid', normed=True) 39 | 40 | x = np.linspace(0, 7, 1000) 41 | normal = stats.distributions.norm(loc=mu, scale=sigma / np.sqrt(2)) 42 | ax3.plot(x, normal.pdf(x), 'r--', label=r'$N\left(\mu,\ \frac{\sigma}{\sqrt{T}}\right)$') 43 | 44 | # don't forget to label axes! 45 | ylabel = ax3.set_ylabel('Density') 46 | ylabel.set_family('serif') 47 | 48 | # set the title 49 | ax3.set_title('T=2') 50 | 51 | # create the fourth subplot 52 | ax4 = fig.add_subplot(324, sharex=ax1) 53 | 54 | n, bins, patches = ax4.hist(sample_averages[499,:], bins=25, align='mid', normed=True) 55 | 56 | x = np.linspace(0, 7, 1000) 57 | normal = stats.distributions.norm(loc=mu, scale=sigma / np.sqrt(500)) 58 | ax4.plot(x, normal.pdf(x), 'r--', label=r'$N\left(\mu,\ \frac{\sigma}{\sqrt{T}}\right)$') 59 | 60 | # don't forget to label axes! 61 | ylabel = ax4.set_ylabel('Density') 62 | ylabel.set_family('serif') 63 | 64 | # set the title 65 | ax4.set_title('T=500') 66 | 67 | # create the fifth subplot 68 | ax5 = fig.add_subplot(325, sharex=ax1) 69 | 70 | n, bins, patches = ax5.hist(sample_averages[2,:], bins=np.arange(0.5, 7, 1), align='mid', normed=True) 71 | 72 | x = np.linspace(0, 7, 1000) 73 | normal = stats.distributions.norm(loc=mu, scale=sigma / np.sqrt(3)) 74 | ax5.plot(x, normal.pdf(x), 'r--', label=r'$N\left(\mu,\ \frac{\sigma}{\sqrt{T}}\right)$') 75 | 76 | # don't forget to label axes! 77 | ax5.set_xlabel(r'$\hat{\mu}$') 78 | ylabel = ax5.set_ylabel('Density') 79 | ylabel.set_family('serif') 80 | 81 | # set the title 82 | ax5.set_title('T=3') 83 | 84 | # create the sixth subplot 85 | ax6 = fig.add_subplot(326, sharex=ax1) 86 | 87 | n, bins, patches = ax6.hist(sample_averages[999,:], bins=25, align='mid', normed=True) 88 | 89 | x = np.linspace(0, 7, 1000) 90 | normal = stats.distributions.norm(loc=mu, scale=sigma / np.sqrt(1000)) 91 | ax6.plot(x, normal.pdf(x), 'r--', label=r'$N\left(\mu,\ \frac{\sigma}{\sqrt{T}}\right)$') 92 | 93 | # don't forget to label axes! 94 | ax6.set_xlabel(r'$\hat{\mu}$') 95 | ylabel = ax6.set_ylabel('Density') 96 | ylabel.set_family('serif') 97 | 98 | # set the title 99 | ax6.set_title('T=1000') 100 | 101 | # add a title for the entire set of plots! 102 | plt.figtext(0.5, 1.025, 'CLT in Action!', ha='center', fontsize=20, 103 | family='serif') 104 | 105 | # set the layout 106 | plt.tight_layout() 107 | 108 | plt.savefig('graphics/The-CLT-in-action.png') 109 | plt.show() -------------------------------------------------------------------------------- /labs/introduction/exercise1.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy import stats 3 | import matplotlib.pyplot as plt 4 | 5 | # specify degrees of freedom 6 | df = 3 7 | 8 | # create a random variable object representing the normal distribution 9 | chi_square_rv = stats.distributions.chi2(df) 10 | 11 | # check type of chi_square_rv 12 | type(chi_square_rv) 13 | 14 | # create a grid of values at which to evaluate pdf and cdf 15 | grid = np.linspace(0, 15, 1000) 16 | 17 | # create new Figure object 18 | fig = plt.figure(figsize=(8, 10)) 19 | 20 | # plot the pdf 21 | ax = fig.add_subplot(211) 22 | 23 | ax.plot(grid, chi_square_rv.pdf(grid), 'r-') 24 | ax.axis('tight') 25 | ax.set_ylim(0, 0.5) 26 | 27 | # label the axes... 28 | xlab = ax.set_xlabel('X', fontsize=15) 29 | xlab.set_family('serif') 30 | ylab = ax.set_ylabel('f(x)', fontsize=15, rotation='horizontal') 31 | ylab.set_family('serif') 32 | 33 | # ...and add a title 34 | ax.set_title(r'Probability density function of a $\chi^2$ r.v. with %g d.f.' %df, 35 | family='serif', fontsize=15) 36 | 37 | # plot the cdf 38 | ax1 = fig.add_subplot(212) 39 | 40 | ax1.plot(grid, chi_square_rv.cdf(grid), 'b-') 41 | ax1.axis('tight') 42 | 43 | # label the axes... 44 | xlab = ax1.set_xlabel('X', fontsize=15) 45 | xlab.set_family('serif') 46 | ylab = ax1.set_ylabel('F(x)', fontsize=15, rotation='horizontal') 47 | ylab.set_family('serif') 48 | 49 | # ...and add a title 50 | ax1.set_title(r'Distribution function of a $\chi^2$ r.v. with %g d.f.' %df, 51 | family='serif', fontsize=15) 52 | 53 | # adjust the layout 54 | fig.tight_layout() 55 | 56 | plt.savefig('graphics/exercise-1-1a.png') 57 | plt.show() 58 | 59 | # create new Figure and Axes objects 60 | fig = plt.figure(figsize=(8,6)) 61 | ax = fig.add_subplot(111) 62 | 63 | # plot the survival function 64 | ax.plot(grid, chi_square_rv.sf(grid), 'g-') 65 | ax.set_xscale('log') 66 | ax.set_yscale('log') 67 | 68 | # label the axes... 69 | xlab = ax.set_xlabel('X (log scale)', fontsize=15) 70 | xlab.set_family('serif') 71 | ylab = ax.set_ylabel('Survival function, 1 - F(x) (log scale)', fontsize=15) 72 | ylab.set_family('serif') 73 | 74 | # ...and add a title 75 | ax.set_title(r'Survival function of a $\chi^2$ r.v. with %g d.f.' %df, 76 | family='serif', fontsize=15) 77 | 78 | plt.savefig('graphics/exercise-1-1b.png') 79 | plt.show() -------------------------------------------------------------------------------- /labs/introduction/exercise2.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy import stats 3 | import matplotlib.pyplot as plt 4 | 5 | # specify degrees of freedom 6 | df = 3 7 | 8 | # create a random variable object representing the normal distribution 9 | chi_square_rv = stats.distributions.chi2(df) 10 | 11 | # generate a large sample 12 | T = 10000 13 | sample = chi_square_rv.rvs((T,)) 14 | 15 | # create new Figure and Axes objects 16 | fig = plt.figure(figsize=(8,6)) 17 | ax = fig.add_subplot(111) 18 | 19 | # histogram the sample 20 | n, bins, patches = ax.hist(sample, color='purple', bins = 25, normed=True, alpha = 0.75) 21 | ax.set_xlim(0, 15) 22 | 23 | # overlay the theoretical pdf 24 | grid = np.linspace(0, 15, 1000) 25 | ax.plot(grid, chi_square_rv.pdf(grid), 'r--', label=r'$\chi^2(df)$') 26 | 27 | # label the axes 28 | ax.set_xlabel('X', fontsize=15, family='serif') 29 | ax.set_ylabel('Probability density', fontsize=15, family='serif') 30 | 31 | # add a title 32 | ax.set_title('We can use the rvs() method to check the pdf() method!', 33 | family='serif', fontsize=15) 34 | 35 | # add a legend 36 | ax.legend(loc='best', frameon=False) 37 | 38 | plt.savefig('graphics/exercise-2-1.png') 39 | plt.show() -------------------------------------------------------------------------------- /labs/introduction/exercise3.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy import stats 3 | import matplotlib.pyplot as plt 4 | 5 | #Set degrees of freedom 6 | df = 1 7 | 8 | # create a t-distribution object 9 | students_t_rv = stats.distributions.t(df) 10 | 11 | # set the seed 12 | np.random.seed(12) 13 | 14 | # generate data 15 | T = 1000 16 | sample_path = students_t_rv.rvs((T,)) 17 | 18 | # create new Figure and Axes objects 19 | fig = plt.figure(figsize=(8,6)) 20 | ax = fig.add_subplot(111) 21 | 22 | # plot the sample path 23 | ax.plot(sample_path, 'g-') 24 | 25 | # label axes 26 | xlab = ax.set_xlabel('Index', fontsize=15) 27 | xlab.set_family('serif') 28 | 29 | ylab = ax.set_ylabel('Observation', fontsize=15) 30 | ylab.set_family('serif') 31 | 32 | # set the title 33 | title = ax.set_title("Random sample of data from Student's t with %g d.f." % df, 34 | fontsize=15) 35 | title.set_family('serif') 36 | 37 | plt.savefig('graphics/exercise-2-2.png') 38 | plt.show() -------------------------------------------------------------------------------- /labs/introduction/exercise4.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | import numpy as np 3 | from scipy import stats 4 | import matplotlib.pyplot as plt 5 | 6 | # create a loaded coin 7 | loaded_coin = stats.distributions.bernoulli(0.75) 8 | 9 | # flip the loaded coin 10 | for T in [10, 100, 1000, 10000]: 11 | 12 | # create a loaded coin 13 | loaded_coin_flips = loaded_coin.rvs((T,)) 14 | 15 | # count the fraction of heads... 16 | fraction_heads = np.mean(loaded_coin_flips) 17 | 18 | print 'Fraction of heads with T=%i trials is %.3f' %(T, fraction_heads) -------------------------------------------------------------------------------- /labs/introduction/exercise5.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | import numpy as np 3 | from scipy import stats 4 | import matplotlib.pyplot as plt 5 | 6 | # set params 7 | N = 100 8 | T = 10000 9 | p = 0.75 10 | loaded_coin = stats.distributions.bernoulli(p) 11 | 12 | # generate an array of integers 13 | data = loaded_coin.rvs((T,N)) 14 | 15 | # create an array in which to store our sample averages 16 | loaded_difference = np.zeros(data.shape, dtype=float) 17 | 18 | for j in range(N): 19 | for i in range(T): 20 | loaded_difference[i, j] = 2 * np.sum(data[:i + 1, j]) - (i + 1) 21 | 22 | # create new Figure and Axes objects 23 | fig = plt.figure(figsize=(8,6)) 24 | ax = fig.add_subplot(111) 25 | 26 | # plot each sample path... 27 | for i in range(N): 28 | ax.plot(np.arange(1, T + 1, 1), loaded_difference[:, i], 'k-', alpha=0.05) 29 | 30 | # label axes 31 | xlab = ax.set_xlabel('Index', fontsize=15) 32 | xlab.set_family('serif') 33 | ylab = ax.set_ylabel('Heads - Tails', family='serif', fontsize=15) 34 | 35 | # set the title 36 | title = ax.set_title('Difference really diverges with a loaded coin!') 37 | title.set_family('serif') 38 | title.set_fontsize(15) 39 | 40 | plt.savefig('graphics/exercise-5a.png') 41 | plt.show() 42 | 43 | # set params 44 | N = 100 45 | T = 10000 46 | 47 | # generate an array of integers 48 | data = loaded_coin.rvs((T,N)) 49 | 50 | # create an array in which to store our sample averages 51 | sample_averages = np.zeros(data.shape, dtype=float) 52 | 53 | for j in range(N): 54 | for i in range(T): 55 | sample_averages[i, j] = np.mean(data[:i + 1, j]) 56 | 57 | # create new Figure and Axes objects 58 | fig = plt.figure(figsize=(8,6)) 59 | ax = fig.add_subplot(111) 60 | 61 | # plot each sample path from obs. 10 forward... 62 | for i in range(N): 63 | ax.plot(np.arange(1, T + 1, 1), sample_averages[:, i], 'k-', alpha=0.05) 64 | ax.set_ylim(0, 1) 65 | 66 | # set the x-axis to have log scale 67 | ax.set_xscale('log') 68 | 69 | # demarcate the true mean 70 | ax.axhline(y=p, color='black', linestyle='dashed', label=r'$\mu$') 71 | 72 | # label axes 73 | xlab = ax.set_xlabel('Index') 74 | xlab.set_family('serif') 75 | 76 | ylab = ax.set_ylabel(r'$\hat{\mu}$') 77 | ylab.set_rotation('horizontal') 78 | ylab.set_fontsize(15) 79 | 80 | # set the title 81 | title = ax.set_title(r'Average number of heads converges to $\mu=%g$!' %p) 82 | title.set_family('serif') 83 | title.set_fontsize(15) 84 | 85 | # add the legend 86 | ax.legend(loc='best', frameon=False) 87 | 88 | plt.savefig('graphics/exercise-5b.png') -------------------------------------------------------------------------------- /labs/lab-1/depreciation_rates.dta: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-1/depreciation_rates.dta -------------------------------------------------------------------------------- /labs/lab-1/exercise_3a.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import growth 3 | 4 | def cobb_douglas_output(t, k, params): 5 | """ 6 | Cobb-Douglas production function. 7 | 8 | Arguments: 9 | 10 | t: (array-like) Time. 11 | k: (array-like) Capital (per person/effective person). 12 | params: (dict) Dictionary of parameter values. 13 | 14 | Returns: 15 | 16 | y: (array-like) Output (per person/ effective person) 17 | 18 | """ 19 | # extract params 20 | alpha = params['alpha'] 21 | 22 | # Cobb-Douglas technology 23 | y = k**alpha 24 | 25 | return y 26 | 27 | def marginal_product_capital(t, k, params): 28 | """ 29 | Marginal product of capital with Cobb-Douglas production technology. 30 | 31 | Arguments: 32 | 33 | t: (array-like) Time. 34 | k: (array-like) Capital (per person/effective person). 35 | params: (dict) Dictionary of parameter values. 36 | 37 | Returns: 38 | 39 | y_k: (array-like) Derivative of output with respect to capital, k. 40 | 41 | """ 42 | # extract params 43 | alpha = params['alpha'] 44 | 45 | return alpha * k**(alpha - 1) 46 | 47 | def equation_of_motion_capital(t, k, params): 48 | """ 49 | Equation of motion for capital (per worker/effective worker). 50 | 51 | Arguments: 52 | 53 | t: (array-like) Time. 54 | k: (array-like) Capital (per person/effective person). 55 | params: (dict) Dictionary of parameter values. 56 | 57 | Returns: 58 | 59 | k_dot: (array-like) Time-derivative of capital (per worker/effective 60 | worker). 61 | 62 | """ 63 | # extract params 64 | s = params['s'] 65 | n = params['n'] 66 | g = params['g'] 67 | delta = params['delta'] 68 | 69 | k_dot = s * cobb_douglas_output(t, k, params) - (n + g + delta) * k 70 | 71 | return k_dot 72 | 73 | def solow_jacobian(t, k, params): 74 | """ 75 | The Jacobian of the Solow model. 76 | 77 | Arguments: 78 | 79 | t: (array-like) Time. 80 | k: (array-like) Capital (per person/effective person). 81 | params: (dict) Dictionary of parameter values. 82 | 83 | Returns: 84 | 85 | jac: (array-like) Value of the derivative of the equation of 86 | motion for capital (per worker/effective worker) with 87 | respect to k. 88 | 89 | """ 90 | # extract params 91 | s = params['s'] 92 | n = params['n'] 93 | g = params['g'] 94 | delta = params['delta'] 95 | 96 | k_dot = s * marginal_product_capital(t, k, params) - (n + g + delta) 97 | 98 | return k_dot 99 | 100 | def analytic_k_star(params): 101 | """The steady-state level of capital stock per effective worker, k_bar, 102 | in the Solow model is a function of the 5 exogenous parameters! 103 | 104 | """ 105 | # extract params 106 | s = params['s'] 107 | n = params['n'] 108 | g = params['g'] 109 | alpha = params['alpha'] 110 | delta = params['delta'] 111 | 112 | return (s / (n + g + delta))**(1 / (1 - alpha)) 113 | 114 | # create a new model object 115 | model = growth.SolowModel(cobb_douglas_output, marginal_product_capital, 116 | equation_of_motion_capital, solow_jacobian) 117 | 118 | # create a dictionary of steady state expressions 119 | steady_state_funcs = {'k_star':analytic_k_star} 120 | 121 | # pass it as an argument to the set_steady_state_functions method 122 | model.steady_state.set_functions(steady_state_funcs) 123 | 124 | # calibrate the model and compute steady state values 125 | growth.calibrate_cobb_douglas(model, 'GBR') 126 | 127 | # create a new figure 128 | fig = plt.figure(figsize=(8,6)) 129 | 130 | # plot comparative statics for the solow model using one line of code! 131 | model.plot_solow_diagram(gridmax=15, param='delta', shock=0.9, reset=True) 132 | 133 | # display the figure 134 | plt.show() 135 | 136 | -------------------------------------------------------------------------------- /labs/lab-1/exercise_3b.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import growth 3 | 4 | def cobb_douglas_output(t, k, params): 5 | """ 6 | Cobb-Douglas production function. 7 | 8 | Arguments: 9 | 10 | t: (array-like) Time. 11 | k: (array-like) Capital (per person/effective person). 12 | params: (dict) Dictionary of parameter values. 13 | 14 | Returns: 15 | 16 | y: (array-like) Output (per person/ effective person) 17 | 18 | """ 19 | # extract params 20 | alpha = params['alpha'] 21 | 22 | # Cobb-Douglas technology 23 | y = k**alpha 24 | 25 | return y 26 | 27 | def marginal_product_capital(t, k, params): 28 | """ 29 | Marginal product of capital with Cobb-Douglas production technology. 30 | 31 | Arguments: 32 | 33 | t: (array-like) Time. 34 | k: (array-like) Capital (per person/effective person). 35 | params: (dict) Dictionary of parameter values. 36 | 37 | Returns: 38 | 39 | y_k: (array-like) Derivative of output with respect to capital, k. 40 | 41 | """ 42 | # extract params 43 | alpha = params['alpha'] 44 | 45 | return alpha * k**(alpha - 1) 46 | 47 | def equation_of_motion_capital(t, k, params): 48 | """ 49 | Equation of motion for capital (per worker/effective worker). 50 | 51 | Arguments: 52 | 53 | t: (array-like) Time. 54 | k: (array-like) Capital (per person/effective person). 55 | params: (dict) Dictionary of parameter values. 56 | 57 | Returns: 58 | 59 | k_dot: (array-like) Time-derivative of capital (per worker/effective 60 | worker). 61 | 62 | """ 63 | # extract params 64 | s = params['s'] 65 | n = params['n'] 66 | g = params['g'] 67 | delta = params['delta'] 68 | 69 | k_dot = s * cobb_douglas_output(t, k, params) - (n + g + delta) * k 70 | 71 | return k_dot 72 | 73 | def solow_jacobian(t, k, params): 74 | """ 75 | The Jacobian of the Solow model. 76 | 77 | Arguments: 78 | 79 | t: (array-like) Time. 80 | k: (array-like) Capital (per person/effective person). 81 | params: (dict) Dictionary of parameter values. 82 | 83 | Returns: 84 | 85 | jac: (array-like) Value of the derivative of the equation of 86 | motion for capital (per worker/effective worker) with 87 | respect to k. 88 | 89 | """ 90 | # extract params 91 | s = params['s'] 92 | n = params['n'] 93 | g = params['g'] 94 | delta = params['delta'] 95 | 96 | k_dot = s * marginal_product_capital(t, k, params) - (n + g + delta) 97 | 98 | return k_dot 99 | 100 | def analytic_k_star(params): 101 | """The steady-state level of capital stock per effective worker, k_bar, 102 | in the Solow model is a function of the 5 exogenous parameters! 103 | 104 | """ 105 | # extract params 106 | s = params['s'] 107 | n = params['n'] 108 | g = params['g'] 109 | alpha = params['alpha'] 110 | delta = params['delta'] 111 | 112 | return (s / (n + g + delta))**(1 / (1 - alpha)) 113 | 114 | # create a new model object 115 | model = growth.SolowModel(cobb_douglas_output, marginal_product_capital, 116 | equation_of_motion_capital, solow_jacobian) 117 | 118 | # create a dictionary of steady state expressions 119 | steady_state_funcs = {'k_star':analytic_k_star} 120 | 121 | # pass it as an argument to the set_steady_state_functions method 122 | model.steady_state.set_functions(steady_state_funcs) 123 | 124 | # calibrate the model and compute steady state values 125 | growth.calibrate_cobb_douglas(model, 'GBR') 126 | 127 | # create a new figure 128 | fig = plt.figure(figsize=(8,6)) 129 | 130 | # plot comparative statics for the solow model using one line of code! 131 | model.plot_solow_diagram(gridmax=15, param='g', shock=2.0, reset=True) 132 | 133 | # display the figure 134 | plt.show() 135 | 136 | -------------------------------------------------------------------------------- /labs/lab-1/exercise_3c.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import growth 3 | 4 | def cobb_douglas_output(t, k, params): 5 | """ 6 | Cobb-Douglas production function. 7 | 8 | Arguments: 9 | 10 | t: (array-like) Time. 11 | k: (array-like) Capital (per person/effective person). 12 | params: (dict) Dictionary of parameter values. 13 | 14 | Returns: 15 | 16 | y: (array-like) Output (per person/ effective person) 17 | 18 | """ 19 | # extract params 20 | alpha = params['alpha'] 21 | 22 | # Cobb-Douglas technology 23 | y = k**alpha 24 | 25 | return y 26 | 27 | def marginal_product_capital(t, k, params): 28 | """ 29 | Marginal product of capital with Cobb-Douglas production technology. 30 | 31 | Arguments: 32 | 33 | t: (array-like) Time. 34 | k: (array-like) Capital (per person/effective person). 35 | params: (dict) Dictionary of parameter values. 36 | 37 | Returns: 38 | 39 | y_k: (array-like) Derivative of output with respect to capital, k. 40 | 41 | """ 42 | # extract params 43 | alpha = params['alpha'] 44 | 45 | return alpha * k**(alpha - 1) 46 | 47 | def equation_of_motion_capital(t, k, params): 48 | """ 49 | Equation of motion for capital (per worker/effective worker). 50 | 51 | Arguments: 52 | 53 | t: (array-like) Time. 54 | k: (array-like) Capital (per person/effective person). 55 | params: (dict) Dictionary of parameter values. 56 | 57 | Returns: 58 | 59 | k_dot: (array-like) Time-derivative of capital (per worker/effective 60 | worker). 61 | 62 | """ 63 | # extract params 64 | s = params['s'] 65 | n = params['n'] 66 | g = params['g'] 67 | delta = params['delta'] 68 | 69 | k_dot = s * cobb_douglas_output(t, k, params) - (n + g + delta) * k 70 | 71 | return k_dot 72 | 73 | def solow_jacobian(t, k, params): 74 | """ 75 | The Jacobian of the Solow model. 76 | 77 | Arguments: 78 | 79 | t: (array-like) Time. 80 | k: (array-like) Capital (per person/effective person). 81 | params: (dict) Dictionary of parameter values. 82 | 83 | Returns: 84 | 85 | jac: (array-like) Value of the derivative of the equation of 86 | motion for capital (per worker/effective worker) with 87 | respect to k. 88 | 89 | """ 90 | # extract params 91 | s = params['s'] 92 | n = params['n'] 93 | g = params['g'] 94 | delta = params['delta'] 95 | 96 | k_dot = s * marginal_product_capital(t, k, params) - (n + g + delta) 97 | 98 | return k_dot 99 | 100 | def analytic_k_star(params): 101 | """The steady-state level of capital stock per effective worker, k_bar, 102 | in the Solow model is a function of the 5 exogenous parameters! 103 | 104 | """ 105 | # extract params 106 | s = params['s'] 107 | n = params['n'] 108 | g = params['g'] 109 | alpha = params['alpha'] 110 | delta = params['delta'] 111 | 112 | return (s / (n + g + delta))**(1 / (1 - alpha)) 113 | 114 | # create a new model object 115 | model = growth.SolowModel(cobb_douglas_output, marginal_product_capital, 116 | equation_of_motion_capital, solow_jacobian) 117 | 118 | # create a dictionary of steady state expressions 119 | steady_state_funcs = {'k_star':analytic_k_star} 120 | 121 | # pass it as an argument to the set_steady_state_functions method 122 | model.steady_state.set_functions(steady_state_funcs) 123 | 124 | # calibrate the model and compute steady state values 125 | growth.calibrate_cobb_douglas(model, 'GBR') 126 | 127 | # create a new figure 128 | fig = plt.figure(figsize=(8,6)) 129 | 130 | # plot comparative statics for the solow model using one line of code! 131 | model.plot_solow_diagram(gridmax=15, param='alpha', shock=1.5, reset=True) 132 | 133 | # display the figure 134 | plt.show() 135 | 136 | -------------------------------------------------------------------------------- /labs/lab-1/exercise_4a.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import growth 3 | 4 | def cobb_douglas_output(t, k, params): 5 | """ 6 | Cobb-Douglas production function. 7 | 8 | Arguments: 9 | 10 | t: (array-like) Time. 11 | k: (array-like) Capital (per person/effective person). 12 | params: (dict) Dictionary of parameter values. 13 | 14 | Returns: 15 | 16 | y: (array-like) Output (per person/ effective person) 17 | 18 | """ 19 | # extract params 20 | alpha = params['alpha'] 21 | 22 | # Cobb-Douglas technology 23 | y = k**alpha 24 | 25 | return y 26 | 27 | def marginal_product_capital(t, k, params): 28 | """ 29 | Marginal product of capital with Cobb-Douglas production technology. 30 | 31 | Arguments: 32 | 33 | t: (array-like) Time. 34 | k: (array-like) Capital (per person/effective person). 35 | params: (dict) Dictionary of parameter values. 36 | 37 | Returns: 38 | 39 | y_k: (array-like) Derivative of output with respect to capital, k. 40 | 41 | """ 42 | # extract params 43 | alpha = params['alpha'] 44 | 45 | return alpha * k**(alpha - 1) 46 | 47 | def equation_of_motion_capital(t, k, params): 48 | """ 49 | Equation of motion for capital (per worker/effective worker). 50 | 51 | Arguments: 52 | 53 | t: (array-like) Time. 54 | k: (array-like) Capital (per person/effective person). 55 | params: (dict) Dictionary of parameter values. 56 | 57 | Returns: 58 | 59 | k_dot: (array-like) Time-derivative of capital (per worker/effective 60 | worker). 61 | 62 | """ 63 | # extract params 64 | s = params['s'] 65 | n = params['n'] 66 | g = params['g'] 67 | delta = params['delta'] 68 | 69 | k_dot = s * cobb_douglas_output(t, k, params) - (n + g + delta) * k 70 | 71 | return k_dot 72 | 73 | def solow_jacobian(t, k, params): 74 | """ 75 | The Jacobian of the Solow model. 76 | 77 | Arguments: 78 | 79 | t: (array-like) Time. 80 | k: (array-like) Capital (per person/effective person). 81 | params: (dict) Dictionary of parameter values. 82 | 83 | Returns: 84 | 85 | jac: (array-like) Value of the derivative of the equation of 86 | motion for capital (per worker/effective worker) with 87 | respect to k. 88 | 89 | """ 90 | # extract params 91 | s = params['s'] 92 | n = params['n'] 93 | g = params['g'] 94 | delta = params['delta'] 95 | 96 | k_dot = s * marginal_product_capital(t, k, params) - (n + g + delta) 97 | 98 | return k_dot 99 | 100 | def analytic_k_star(params): 101 | """ 102 | The steady-state level of capital stock per effective worker, k_bar, 103 | in the Solow model is a function of the 5 exogenous parameters! 104 | 105 | """ 106 | # extract params 107 | s = params['s'] 108 | n = params['n'] 109 | g = params['g'] 110 | alpha = params['alpha'] 111 | delta = params['delta'] 112 | 113 | return (s / (n + g + delta))**(1 / (1 - alpha)) 114 | 115 | # create a new model object 116 | model = growth.SolowModel(cobb_douglas_output, marginal_product_capital, 117 | equation_of_motion_capital, solow_jacobian) 118 | 119 | # create a dictionary of steady state expressions 120 | steady_state_funcs = {'k_star':analytic_k_star} 121 | 122 | # pass it as an argument to the set_steady_state_functions method 123 | model.steady_state.set_functions(steady_state_funcs) 124 | 125 | # calibrate the model and compute steady state values 126 | growth.calibrate_cobb_douglas(model, 'GBR') 127 | 128 | # create a new figure 129 | fig_kwargs = {'figsize':(12,8)} 130 | 131 | # irf for shock to alpha 132 | model.plot_impulse_response(variables='all', 133 | param='alpha', 134 | shock=1.5, 135 | T=100, 136 | color='b', 137 | year=2013, 138 | kind='efficiency_units', 139 | log=False, 140 | reset=True, 141 | **fig_kwargs) 142 | # display the figure 143 | plt.show() 144 | 145 | -------------------------------------------------------------------------------- /labs/lab-1/exercise_4b.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import growth 3 | 4 | def cobb_douglas_output(t, k, params): 5 | """ 6 | Cobb-Douglas production function. 7 | 8 | Arguments: 9 | 10 | t: (array-like) Time. 11 | k: (array-like) Capital (per person/effective person). 12 | params: (dict) Dictionary of parameter values. 13 | 14 | Returns: 15 | 16 | y: (array-like) Output (per person/ effective person) 17 | 18 | """ 19 | # extract params 20 | alpha = params['alpha'] 21 | 22 | # Cobb-Douglas technology 23 | y = k**alpha 24 | 25 | return y 26 | 27 | def marginal_product_capital(t, k, params): 28 | """ 29 | Marginal product of capital with Cobb-Douglas production technology. 30 | 31 | Arguments: 32 | 33 | t: (array-like) Time. 34 | k: (array-like) Capital (per person/effective person). 35 | params: (dict) Dictionary of parameter values. 36 | 37 | Returns: 38 | 39 | y_k: (array-like) Derivative of output with respect to capital, k. 40 | 41 | """ 42 | # extract params 43 | alpha = params['alpha'] 44 | 45 | return alpha * k**(alpha - 1) 46 | 47 | def equation_of_motion_capital(t, k, params): 48 | """ 49 | Equation of motion for capital (per worker/effective worker). 50 | 51 | Arguments: 52 | 53 | t: (array-like) Time. 54 | k: (array-like) Capital (per person/effective person). 55 | params: (dict) Dictionary of parameter values. 56 | 57 | Returns: 58 | 59 | k_dot: (array-like) Time-derivative of capital (per worker/effective 60 | worker). 61 | 62 | """ 63 | # extract params 64 | s = params['s'] 65 | n = params['n'] 66 | g = params['g'] 67 | delta = params['delta'] 68 | 69 | k_dot = s * cobb_douglas_output(t, k, params) - (n + g + delta) * k 70 | 71 | return k_dot 72 | 73 | def solow_jacobian(t, k, params): 74 | """ 75 | The Jacobian of the Solow model. 76 | 77 | Arguments: 78 | 79 | t: (array-like) Time. 80 | k: (array-like) Capital (per person/effective person). 81 | params: (dict) Dictionary of parameter values. 82 | 83 | Returns: 84 | 85 | jac: (array-like) Value of the derivative of the equation of 86 | motion for capital (per worker/effective worker) with 87 | respect to k. 88 | 89 | """ 90 | # extract params 91 | s = params['s'] 92 | n = params['n'] 93 | g = params['g'] 94 | delta = params['delta'] 95 | 96 | k_dot = s * marginal_product_capital(t, k, params) - (n + g + delta) 97 | 98 | return k_dot 99 | 100 | def analytic_k_star(params): 101 | """ 102 | The steady-state level of capital stock per effective worker, k_bar, 103 | in the Solow model is a function of the 5 exogenous parameters! 104 | 105 | """ 106 | # extract params 107 | s = params['s'] 108 | n = params['n'] 109 | g = params['g'] 110 | alpha = params['alpha'] 111 | delta = params['delta'] 112 | 113 | return (s / (n + g + delta))**(1 / (1 - alpha)) 114 | 115 | # create a new model object 116 | model = growth.SolowModel(cobb_douglas_output, marginal_product_capital, 117 | equation_of_motion_capital, solow_jacobian) 118 | 119 | # create a dictionary of steady state expressions 120 | steady_state_funcs = {'k_star':analytic_k_star} 121 | 122 | # pass it as an argument to the set_steady_state_functions method 123 | model.steady_state.set_functions(steady_state_funcs) 124 | 125 | # calibrate the model and compute steady state values 126 | growth.calibrate_cobb_douglas(model, 'GBR') 127 | 128 | # create a new figure 129 | fig_kwargs = {'figsize':(12,8)} 130 | 131 | # irf for shock to alpha 132 | model.plot_impulse_response(variables='all', 133 | param='n', 134 | shock=0.5, 135 | T=100, 136 | color='b', 137 | year=2013, 138 | kind='per_capita', 139 | log=True, 140 | reset=True, 141 | **fig_kwargs) 142 | 143 | # display the figure 144 | plt.show() 145 | 146 | -------------------------------------------------------------------------------- /labs/lab-1/exercise_4c.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import growth 3 | 4 | def cobb_douglas_output(t, k, params): 5 | """ 6 | Cobb-Douglas production function. 7 | 8 | Arguments: 9 | 10 | t: (array-like) Time. 11 | k: (array-like) Capital (per person/effective person). 12 | params: (dict) Dictionary of parameter values. 13 | 14 | Returns: 15 | 16 | y: (array-like) Output (per person/ effective person) 17 | 18 | """ 19 | # extract params 20 | alpha = params['alpha'] 21 | 22 | # Cobb-Douglas technology 23 | y = k**alpha 24 | 25 | return y 26 | 27 | def marginal_product_capital(t, k, params): 28 | """ 29 | Marginal product of capital with Cobb-Douglas production technology. 30 | 31 | Arguments: 32 | 33 | t: (array-like) Time. 34 | k: (array-like) Capital (per person/effective person). 35 | params: (dict) Dictionary of parameter values. 36 | 37 | Returns: 38 | 39 | y_k: (array-like) Derivative of output with respect to capital, k. 40 | 41 | """ 42 | # extract params 43 | alpha = params['alpha'] 44 | 45 | return alpha * k**(alpha - 1) 46 | 47 | def equation_of_motion_capital(t, k, params): 48 | """ 49 | Equation of motion for capital (per worker/effective worker). 50 | 51 | Arguments: 52 | 53 | t: (array-like) Time. 54 | k: (array-like) Capital (per person/effective person). 55 | params: (dict) Dictionary of parameter values. 56 | 57 | Returns: 58 | 59 | k_dot: (array-like) Time-derivative of capital (per worker/effective 60 | worker). 61 | 62 | """ 63 | # extract params 64 | s = params['s'] 65 | n = params['n'] 66 | g = params['g'] 67 | delta = params['delta'] 68 | 69 | k_dot = s * cobb_douglas_output(t, k, params) - (n + g + delta) * k 70 | 71 | return k_dot 72 | 73 | def solow_jacobian(t, k, params): 74 | """ 75 | The Jacobian of the Solow model. 76 | 77 | Arguments: 78 | 79 | t: (array-like) Time. 80 | k: (array-like) Capital (per person/effective person). 81 | params: (dict) Dictionary of parameter values. 82 | 83 | Returns: 84 | 85 | jac: (array-like) Value of the derivative of the equation of 86 | motion for capital (per worker/effective worker) with 87 | respect to k. 88 | 89 | """ 90 | # extract params 91 | s = params['s'] 92 | n = params['n'] 93 | g = params['g'] 94 | delta = params['delta'] 95 | 96 | k_dot = s * marginal_product_capital(t, k, params) - (n + g + delta) 97 | 98 | return k_dot 99 | 100 | def analytic_k_star(params): 101 | """ 102 | The steady-state level of capital stock per effective worker, k_bar, 103 | in the Solow model is a function of the 5 exogenous parameters! 104 | 105 | """ 106 | # extract params 107 | s = params['s'] 108 | n = params['n'] 109 | g = params['g'] 110 | alpha = params['alpha'] 111 | delta = params['delta'] 112 | 113 | return (s / (n + g + delta))**(1 / (1 - alpha)) 114 | 115 | # create a new model object 116 | model = growth.SolowModel(cobb_douglas_output, marginal_product_capital, 117 | equation_of_motion_capital, solow_jacobian) 118 | 119 | # create a dictionary of steady state expressions 120 | steady_state_funcs = {'k_star':analytic_k_star} 121 | 122 | # pass it as an argument to the set_steady_state_functions method 123 | model.steady_state.set_functions(steady_state_funcs) 124 | 125 | # calibrate the model and compute steady state values 126 | growth.calibrate_cobb_douglas(model, 'GBR') 127 | 128 | # create a new figure 129 | fig_kwargs = {'figsize':(12,8)} 130 | 131 | # irf for shock to g 132 | model.plot_impulse_response(variables='all', 133 | param='g', 134 | shock=0.5, 135 | T=100, 136 | color='b', 137 | year=2013, 138 | kind='per_capita', 139 | log=True, 140 | reset=True, 141 | **fig_kwargs) 142 | 143 | # display the figure 144 | plt.show() 145 | 146 | -------------------------------------------------------------------------------- /labs/lab-1/exercise_4d.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import growth 3 | 4 | def cobb_douglas_output(t, k, params): 5 | """ 6 | Cobb-Douglas production function. 7 | 8 | Arguments: 9 | 10 | t: (array-like) Time. 11 | k: (array-like) Capital (per person/effective person). 12 | params: (dict) Dictionary of parameter values. 13 | 14 | Returns: 15 | 16 | y: (array-like) Output (per person/ effective person) 17 | 18 | """ 19 | # extract params 20 | alpha = params['alpha'] 21 | 22 | # Cobb-Douglas technology 23 | y = k**alpha 24 | 25 | return y 26 | 27 | def marginal_product_capital(t, k, params): 28 | """ 29 | Marginal product of capital with Cobb-Douglas production technology. 30 | 31 | Arguments: 32 | 33 | t: (array-like) Time. 34 | k: (array-like) Capital (per person/effective person). 35 | params: (dict) Dictionary of parameter values. 36 | 37 | Returns: 38 | 39 | y_k: (array-like) Derivative of output with respect to capital, k. 40 | 41 | """ 42 | # extract params 43 | alpha = params['alpha'] 44 | 45 | return alpha * k**(alpha - 1) 46 | 47 | def equation_of_motion_capital(t, k, params): 48 | """ 49 | Equation of motion for capital (per worker/effective worker). 50 | 51 | Arguments: 52 | 53 | t: (array-like) Time. 54 | k: (array-like) Capital (per person/effective person). 55 | params: (dict) Dictionary of parameter values. 56 | 57 | Returns: 58 | 59 | k_dot: (array-like) Time-derivative of capital (per worker/effective 60 | worker). 61 | 62 | """ 63 | # extract params 64 | s = params['s'] 65 | n = params['n'] 66 | g = params['g'] 67 | delta = params['delta'] 68 | 69 | k_dot = s * cobb_douglas_output(t, k, params) - (n + g + delta) * k 70 | 71 | return k_dot 72 | 73 | def solow_jacobian(t, k, params): 74 | """ 75 | The Jacobian of the Solow model. 76 | 77 | Arguments: 78 | 79 | t: (array-like) Time. 80 | k: (array-like) Capital (per person/effective person). 81 | params: (dict) Dictionary of parameter values. 82 | 83 | Returns: 84 | 85 | jac: (array-like) Value of the derivative of the equation of 86 | motion for capital (per worker/effective worker) with 87 | respect to k. 88 | 89 | """ 90 | # extract params 91 | s = params['s'] 92 | n = params['n'] 93 | g = params['g'] 94 | delta = params['delta'] 95 | 96 | k_dot = s * marginal_product_capital(t, k, params) - (n + g + delta) 97 | 98 | return k_dot 99 | 100 | def analytic_k_star(params): 101 | """ 102 | The steady-state level of capital stock per effective worker, k_bar, 103 | in the Solow model is a function of the 5 exogenous parameters! 104 | 105 | """ 106 | # extract params 107 | s = params['s'] 108 | n = params['n'] 109 | g = params['g'] 110 | alpha = params['alpha'] 111 | delta = params['delta'] 112 | 113 | return (s / (n + g + delta))**(1 / (1 - alpha)) 114 | 115 | # create a new model object 116 | model = growth.SolowModel(cobb_douglas_output, marginal_product_capital, 117 | equation_of_motion_capital, solow_jacobian) 118 | 119 | # create a dictionary of steady state expressions 120 | steady_state_funcs = {'k_star':analytic_k_star} 121 | 122 | # pass it as an argument to the set_steady_state_functions method 123 | model.steady_state.set_functions(steady_state_funcs) 124 | 125 | # calibrate the model and compute steady state values 126 | growth.calibrate_cobb_douglas(model, 'GBR') 127 | 128 | # create a new figure 129 | fig_kwargs = {'figsize':(12,8)} 130 | 131 | # irf for shock to delta 132 | model.plot_impulse_response(variables='all', 133 | param='delta', 134 | shock=1.5, 135 | T=100, 136 | color='b', 137 | year=2013, 138 | kind='efficiency_units', 139 | log=False, 140 | reset=True, 141 | **fig_kwargs) 142 | # display the figure 143 | plt.show() 144 | 145 | -------------------------------------------------------------------------------- /labs/lab-1/exercise_4e.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import growth 3 | 4 | def cobb_douglas_output(t, k, params): 5 | """ 6 | Cobb-Douglas production function. 7 | 8 | Arguments: 9 | 10 | t: (array-like) Time. 11 | k: (array-like) Capital (per person/effective person). 12 | params: (dict) Dictionary of parameter values. 13 | 14 | Returns: 15 | 16 | y: (array-like) Output (per person/ effective person) 17 | 18 | """ 19 | # extract params 20 | alpha = params['alpha'] 21 | 22 | # Cobb-Douglas technology 23 | y = k**alpha 24 | 25 | return y 26 | 27 | def marginal_product_capital(t, k, params): 28 | """ 29 | Marginal product of capital with Cobb-Douglas production technology. 30 | 31 | Arguments: 32 | 33 | t: (array-like) Time. 34 | k: (array-like) Capital (per person/effective person). 35 | params: (dict) Dictionary of parameter values. 36 | 37 | Returns: 38 | 39 | y_k: (array-like) Derivative of output with respect to capital, k. 40 | 41 | """ 42 | # extract params 43 | alpha = params['alpha'] 44 | 45 | return alpha * k**(alpha - 1) 46 | 47 | def equation_of_motion_capital(t, k, params): 48 | """ 49 | Equation of motion for capital (per worker/effective worker). 50 | 51 | Arguments: 52 | 53 | t: (array-like) Time. 54 | k: (array-like) Capital (per person/effective person). 55 | params: (dict) Dictionary of parameter values. 56 | 57 | Returns: 58 | 59 | k_dot: (array-like) Time-derivative of capital (per worker/effective 60 | worker). 61 | 62 | """ 63 | # extract params 64 | s = params['s'] 65 | n = params['n'] 66 | g = params['g'] 67 | delta = params['delta'] 68 | 69 | k_dot = s * cobb_douglas_output(t, k, params) - (n + g + delta) * k 70 | 71 | return k_dot 72 | 73 | def solow_jacobian(t, k, params): 74 | """ 75 | The Jacobian of the Solow model. 76 | 77 | Arguments: 78 | 79 | t: (array-like) Time. 80 | k: (array-like) Capital (per person/effective person). 81 | params: (dict) Dictionary of parameter values. 82 | 83 | Returns: 84 | 85 | jac: (array-like) Value of the derivative of the equation of 86 | motion for capital (per worker/effective worker) with 87 | respect to k. 88 | 89 | """ 90 | # extract params 91 | s = params['s'] 92 | n = params['n'] 93 | g = params['g'] 94 | delta = params['delta'] 95 | 96 | k_dot = s * marginal_product_capital(t, k, params) - (n + g + delta) 97 | 98 | return k_dot 99 | 100 | def analytic_k_star(params): 101 | """ 102 | The steady-state level of capital stock per effective worker, k_bar, 103 | in the Solow model is a function of the 5 exogenous parameters! 104 | 105 | """ 106 | # extract params 107 | s = params['s'] 108 | n = params['n'] 109 | g = params['g'] 110 | alpha = params['alpha'] 111 | delta = params['delta'] 112 | 113 | return (s / (n + g + delta))**(1 / (1 - alpha)) 114 | 115 | # create a new model object 116 | model = growth.SolowModel(cobb_douglas_output, marginal_product_capital, 117 | equation_of_motion_capital, solow_jacobian) 118 | 119 | # create a dictionary of steady state expressions 120 | steady_state_funcs = {'k_star':analytic_k_star} 121 | 122 | # pass it as an argument to the set_steady_state_functions method 123 | model.steady_state.set_functions(steady_state_funcs) 124 | 125 | # calibrate the model and compute steady state values 126 | growth.calibrate_cobb_douglas(model, 'GBR') 127 | 128 | # create a new figure 129 | fig_kwargs = {'figsize':(12,8)} 130 | 131 | # irf for shock to s 132 | model.plot_impulse_response(variables='all', 133 | param='s', 134 | shock=0.75, 135 | T=100, 136 | color='b', 137 | year=2013, 138 | kind='efficiency_units', 139 | log=True, 140 | reset=True, 141 | **fig_kwargs) 142 | # display the figure 143 | plt.show() 144 | 145 | -------------------------------------------------------------------------------- /labs/lab-1/graphics/Classic-Solow-Diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-1/graphics/Classic-Solow-Diagram.png -------------------------------------------------------------------------------- /labs/lab-1/growth.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-1/growth.pyc -------------------------------------------------------------------------------- /labs/lab-1/integrators.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-1/integrators.pyc -------------------------------------------------------------------------------- /labs/lab-1/pwt.py: -------------------------------------------------------------------------------- 1 | """ 2 | Functions for downloading the Penn World Tables (PWT) data from the web and 3 | coercing it into a Pandas Panel object for subsequent analysis. 4 | 5 | """ 6 | from __future__ import division 7 | from StringIO import StringIO 8 | import zipfile 9 | 10 | import pandas as pd 11 | import requests 12 | 13 | def _get_dep_rates_data(base_url, version): 14 | """Downloads the depreciation rate data.""" 15 | tmp_url = base_url + 'v' + str(version) + '/depreciation_rates.zip' 16 | tmp_buffer = requests.get(url=tmp_url) 17 | tmp_zip = zipfile.ZipFile(StringIO(tmp_buffer.content)) 18 | tmp_zip.extract('depreciation_rates.dta') 19 | 20 | def _get_pwt_data(base_url, version): 21 | """Downloads the Penn World Tables (PWT) data.""" 22 | tmp_url = base_url + 'v' + str(version) + '/pwt' + str(version) + '.zip' 23 | tmp_buffer = requests.get(url=tmp_url) 24 | tmp_zip = zipfile.ZipFile(StringIO(tmp_buffer.content)) 25 | tmp_zip.extract('pwt' + str(version) + '.dta') 26 | 27 | def download_pwt_data(base_url='http://www.rug.nl/research/ggdc/data/pwt/', version=80): 28 | """ 29 | Downloads the Penn World Tables (PWT) data. 30 | 31 | Arguments: 32 | 33 | base_url: (str) Base url to use for the download. Current default is: 34 | 35 | 'http://www.rug.nl/research/ggdc/data/pwt/' 36 | 37 | version: (int) Version number for PWT data. Default is 80 (which is the 38 | most recent version). 39 | 40 | """ 41 | _get_dep_rates_data(base_url, version) 42 | _get_pwt_data(base_url, version) 43 | 44 | def load_pwt_data(base_url='http://www.rug.nl/research/ggdc/data/pwt/', version=80): 45 | """ 46 | Load the Penn World Tables (PWT) data as a Pandas Panel object. 47 | 48 | Arguments: 49 | 50 | base_url: (str) Base url to use for the download. Current default is: 51 | 52 | 'http://www.rug.nl/research/ggdc/data/pwt/' 53 | 54 | version: (int) Version number for PWT data. Default is 80 (which is the 55 | most recent version). 56 | 57 | Returns: 58 | 59 | pwt_panel_data: (Panel) A Pandas Panel object containing the Penn World 60 | Tables (PWT) data (including data on depreciation rates). 61 | 62 | """ 63 | try: 64 | pwt_raw_data = pd.read_stata('pwt' + str(version) + '.dta') 65 | dep_rates_raw_data = pd.read_stata('depreciation_rates.dta') 66 | 67 | except IOError: 68 | download_pwt_data(base_url, version) 69 | pwt_raw_data = pd.read_stata('pwt' + str(version) + '.dta') 70 | dep_rates_raw_data = pd.read_stata('depreciation_rates.dta') 71 | 72 | # merge the data 73 | pwt_merged_data = pd.merge(pwt_raw_data, dep_rates_raw_data, how='outer', 74 | on=['countrycode', 'year']) 75 | 76 | # create the hierarchical index 77 | pwt_merged_data.year = pd.to_datetime(pwt_raw_data.year, format='%Y') 78 | pwt_merged_data.set_index(['countrycode', 'year'], inplace=True) 79 | 80 | # coerce into a panel 81 | pwt_panel_data = pwt_merged_data.to_panel() 82 | 83 | return pwt_panel_data 84 | 85 | if __name__ == '__main__': 86 | pwt_panel_data = load_pwt_data(version=80) 87 | print(pwt_panel_data) 88 | -------------------------------------------------------------------------------- /labs/lab-1/pwt.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-1/pwt.pyc -------------------------------------------------------------------------------- /labs/lab-1/pwt80.dta: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-1/pwt80.dta -------------------------------------------------------------------------------- /labs/lab-1/solow-analytic-solution.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-1/solow-analytic-solution.pdf -------------------------------------------------------------------------------- /labs/lab-1/solvers.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-1/solvers.pyc -------------------------------------------------------------------------------- /labs/lab-1/steady_states.py: -------------------------------------------------------------------------------- 1 | from scipy import linalg, optimize 2 | 3 | class SteadyState(object): 4 | """Abstract class representing the deterministic steady state of a model.""" 5 | 6 | def __init__(self, model): 7 | """ 8 | Initializes a SteadyState object with the following attributes: 9 | 10 | model: (object) An instance of the RamseyModel or SolowModel class. 11 | 12 | """ 13 | self.model = model 14 | self.eigenvalues = None 15 | self.eigenvectors = None 16 | 17 | def set_functions(self, func_dict): 18 | """ 19 | Modifies the model's steady_state_functions attribute. 20 | 21 | Arguments: 22 | 23 | func_dict: (dict) Dictionary of analytic function defining the 24 | model's steady state as functions of model parameters. 25 | 26 | """ 27 | self.functions = func_dict 28 | 29 | def set_values(self): 30 | """ 31 | Computes the steady state values using the dictionaries of analytic 32 | functions and model parameters. 33 | 34 | """ 35 | # store steady state values in a dictionary 36 | steady_state_values = {} 37 | 38 | # populate the dictionary of steady state values 39 | for key, func in self.functions.iteritems(): 40 | steady_state_values[key] = func(self.model.params) 41 | 42 | self.values = steady_state_values 43 | 44 | def find_values(self, func, method, **kwargs): 45 | """ 46 | Provides an interface to the various methods for finding the root of 47 | a univariate or multivariate function in scipy.optimize. 48 | 49 | Arguments: 50 | 51 | method: (str) For univariate functions method must be one of: 52 | 'brentq', 'brenth', 'ridder', 'bisect', or 'newton'; for 53 | multivariate function method must be one of: 'hybr', 'lm', 54 | 'broyden1', 'broyden2', 'anderson', 'linearmixing', 55 | 'diagbroyden', 'excitingmixing', 'krylov'. 56 | 57 | **kwargs: (dict) Dictionary of method specific keyword arguments. 58 | 59 | """ 60 | # list of valid multivariate root-finding methods 61 | multivariate_methods = ['hybr', 'lm', 'broyden1', 'broyden2', 62 | 'anderson', 'linearmixing', 'diagbroyden', 63 | 'excitingmixing', 'krylov'] 64 | # univariate methods 65 | if method == 'brentq': 66 | res = optimize.brentq(func, args=self.model.args, **kwargs) 67 | elif method == 'brenth': 68 | res = optimize.brenth(func, args=self.model.args, **kwargs) 69 | elif method == 'ridder': 70 | res = optimize.ridder(func, args=self.model.args, **kwargs) 71 | elif method == 'bisect': 72 | res = optimize.bisect(func, args=self.model.args, **kwargs) 73 | elif method == 'newton': 74 | res = optimize.newton(func, args=self.model.args, **kwargs) 75 | 76 | # multivariate methods are handled by optimize.root 77 | elif method in multivariate_methods: 78 | res = optimize.root(func, args=self.model.args, **kwargs) 79 | else: 80 | raise ValueError, 'Unrecognized method!' 81 | 82 | return res 83 | 84 | def set_eigen_star(self, eval_jacobian): 85 | """ 86 | Computes the eigenvalues and eigenvectors of the Jacobian matrix 87 | evaluated at the deterministic steady state. 88 | 89 | Arguments: 90 | 91 | eval_jacobian: (array-like) Model jacobian evaluated at a point. 92 | 93 | """ 94 | self.eigenvalues, self.eigenvectors = linalg.eig(eval_jacobian) 95 | 96 | def check_stability(self, eval_jacobian): 97 | """ 98 | Checks model stability. 99 | 100 | Arguments: 101 | 102 | eval_jacobian: (array-like) Model jacobian evaluated at the 103 | deterministic steady state. 104 | 105 | Stability conditions differ depending on whether or not the timing of 106 | the model is continuous or discrete. 107 | 108 | In order for the deterministic steady state to be dynamically stable 109 | we need to have: 110 | 111 | 1. same number of stable eigenvalues as pre-determined 112 | variables (i.e., state variables) 113 | 2. same number of unstable eigenvalues as control (i.e., 114 | jump variables). 115 | 116 | Definition of stable (unstable) eigenvalues differs slightly depending 117 | on whether the model is in continuous or discrete time. In continuous 118 | time, a the real part of a stable (unstable) eigenvalue must have 119 | negative (positive). In discrete time a stable (unstable) eigenvalue 120 | has modulus < (>) 1. 121 | 122 | Returns: A list containing... 123 | 124 | eigenvalues: The eigenvalues of the Jacobian matrix. 125 | eigenvectors: The eigenvectors of the Jacobian matrix. 126 | 127 | """ 128 | # compute eigenvalues and eigenvectors 129 | self.set_eigen_star(eval_jacobian) 130 | -------------------------------------------------------------------------------- /labs/lab-1/steady_states.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-1/steady_states.pyc -------------------------------------------------------------------------------- /labs/lab-2/Ramsey Notes.aux: -------------------------------------------------------------------------------- 1 | \relax 2 | \providecommand\HyperFirstAtBeginDocument{\AtBeginDocument} 3 | \HyperFirstAtBeginDocument{\ifx\hyper@anchor\@undefined 4 | \global\let\oldcontentsline\contentsline 5 | \gdef\contentsline#1#2#3#4{\oldcontentsline{#1}{#2}{#3}} 6 | \global\let\oldnewlabel\newlabel 7 | \gdef\newlabel#1#2{\newlabelxx{#1}#2} 8 | \gdef\newlabelxx#1#2#3#4#5#6{\oldnewlabel{#1}{{#2}{#3}}} 9 | \AtEndDocument{\ifx\hyper@anchor\@undefined 10 | \let\contentsline\oldcontentsline 11 | \let\newlabel\oldnewlabel 12 | \fi} 13 | \fi} 14 | \global\let\hyper@last\relax 15 | \gdef\HyperFirstAtBeginDocument#1{#1} 16 | \providecommand\HyField@AuxAddToFields[1]{} 17 | \@writefile{toc}{\contentsline {section}{\numberline {A}The models}{1}{appendix.A}} 18 | \newlabel{eq:popGrowth}{{1}{1}{The models\relax }{equation.A.1}{}} 19 | \newlabel{eq:techProcess}{{2}{1}{The models\relax }{equation.A.2}{}} 20 | \@writefile{toc}{\contentsline {subsection}{\numberline {A.1}Firms}{1}{subsection.A.1}} 21 | \newlabel{eq:prodFunction}{{3}{1}{Firms\relax }{equation.A.3}{}} 22 | \newlabel{eq:realWage}{{5}{2}{Firms\relax }{equation.A.5}{}} 23 | \newlabel{eq:realReturnCapital}{{6}{2}{Firms\relax }{equation.A.6}{}} 24 | \newlabel{eq:inelastic-MPL}{{8}{3}{Firms\relax }{equation.A.8}{}} 25 | \newlabel{eq:inelastic-MPK}{{9}{3}{Firms\relax }{equation.A.9}{}} 26 | \@writefile{toc}{\contentsline {subsection}{\numberline {A.2}Households in a model with inelastic labor}{3}{subsection.A.2}} 27 | \newlabel{eq:HHlifetimeUtility}{{11}{3}{Households in a model with inelastic labor\relax }{equation.A.11}{}} 28 | \newlabel{eq:motionCapital}{{12}{4}{Households in a model with inelastic labor\relax }{equation.A.12}{}} 29 | \newlabel{eq:HHflowBudgetConstraint}{{13}{4}{Households in a model with inelastic labor\relax }{equation.A.13}{}} 30 | \newlabel{eq:HHflowBudgetConstraint}{{A.2}{4}{Households in a model with inelastic labor\relax }{equation.A.13}{}} 31 | \newlabel{eq:intensive-HH-utility}{{15}{4}{Households in a model with inelastic labor\relax }{equation.A.15}{}} 32 | \newlabel{eq:inelastic-euler}{{16}{5}{Households in a model with inelastic labor\relax }{equation.A.16}{}} 33 | \newlabel{eq:inelastic-HH-constraint}{{17}{5}{Households in a model with inelastic labor\relax }{equation.A.17}{}} 34 | \@writefile{toc}{\contentsline {subsection}{\numberline {A.3}Equilibrium}{5}{subsection.A.3}} 35 | \@writefile{toc}{\contentsline {subsection}{\numberline {A.4}Dynamic programming specification}{5}{subsection.A.4}} 36 | \newlabel{eq:inelastic-bellman}{{20}{5}{Dynamic programming specification\relax }{equation.A.20}{}} 37 | \newlabel{eq:inelastic-subproblem1}{{21}{6}{Dynamic programming specification\relax }{equation.A.21}{}} 38 | \newlabel{eq:inelastic-subproblem2}{{22}{6}{Dynamic programming specification\relax }{equation.A.22}{}} 39 | \newlabel{eq:inelastic-subproblem2-FOC}{{23}{6}{Dynamic programming specification\relax }{equation.A.23}{}} 40 | \newlabel{eq:inelastic-subproblem2-combined-FOC}{{25}{6}{Dynamic programming specification\relax }{equation.A.25}{}} 41 | \@writefile{toc}{\contentsline {section}{\numberline {B}Elastic labor supply}{7}{appendix.B}} 42 | \@writefile{toc}{\contentsline {subsection}{\numberline {B.1}Households in a model with elastic labor}{7}{subsection.B.1}} 43 | \newlabel{eq:HHlifetimeUtility}{{31}{7}{Households in a model with elastic labor\relax }{equation.B.31}{}} 44 | \newlabel{eq:popGrowth}{{32}{7}{Households in a model with elastic labor\relax }{equation.B.32}{}} 45 | \newlabel{eq:motionCapital}{{34}{8}{Households in a model with elastic labor\relax }{equation.B.34}{}} 46 | \newlabel{eq:HHflowBudgetConstraint}{{34}{8}{Households in a model with elastic labor\relax }{equation.B.34}{}} 47 | \newlabel{eq:elastic-euler}{{34}{9}{Households in a model with elastic labor\relax }{equation.B.34}{}} 48 | \newlabel{eq:elastic-HH-constraint}{{35}{9}{Households in a model with elastic labor\relax }{equation.B.35}{}} 49 | \@writefile{toc}{\contentsline {section}{\numberline {C}Analytic solutions}{9}{appendix.C}} 50 | \@writefile{toc}{\contentsline {subsection}{\numberline {C.1}Inelastic labor supply}{9}{subsection.C.1}} 51 | \newlabel{eq:reduced-form-Bellman}{{39}{10}{Inelastic labor supply\relax }{equation.C.39}{}} 52 | \newlabel{eq:inelastic-optimal-policy}{{46}{10}{Inelastic labor supply\relax }{equation.C.46}{}} 53 | \bibdata{/Users/clarissasweet/References/RBC.bib} 54 | \bibstyle{chicago} 55 | -------------------------------------------------------------------------------- /labs/lab-2/Ramsey Notes.out: -------------------------------------------------------------------------------- 1 | \BOOKMARK [1][-]{appendix.A}{The models}{}% 1 2 | \BOOKMARK [2][-]{subsection.A.1}{Firms}{appendix.A}% 2 3 | \BOOKMARK [2][-]{subsection.A.2}{Households in a model with inelastic labor}{appendix.A}% 3 4 | \BOOKMARK [2][-]{subsection.A.3}{Equilibrium}{appendix.A}% 4 5 | \BOOKMARK [2][-]{subsection.A.4}{Dynamic programming specification}{appendix.A}% 5 6 | \BOOKMARK [1][-]{appendix.B}{Elastic labor supply}{}% 6 7 | \BOOKMARK [2][-]{subsection.B.1}{Households in a model with elastic labor}{appendix.B}% 7 8 | \BOOKMARK [1][-]{appendix.C}{Analytic solutions}{}% 8 9 | \BOOKMARK [2][-]{subsection.C.1}{Inelastic labor supply}{appendix.C}% 9 10 | -------------------------------------------------------------------------------- /labs/lab-2/Ramsey Notes.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-2/Ramsey Notes.pdf -------------------------------------------------------------------------------- /labs/lab-2/Ramsey Notes.synctex.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-2/Ramsey Notes.synctex.gz -------------------------------------------------------------------------------- /labs/lab-2/contour_plots.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | import numpy as np 3 | from scipy import optimize 4 | import matplotlib as mpl 5 | import matplotlib.pyplot as plt 6 | from mpl_toolkits.mplot3d import Axes3D 7 | 8 | def F(K, L, A=1): 9 | """ 10 | 11 | Classic constant elasticity of substitution (CES) production function. 12 | Output is a function of the capital stock, K, and labor, L. Note that 13 | technology, A, is assumed to be labor-augmenting. 14 | 15 | """ 16 | rho = (sigma - 1) / sigma 17 | 18 | # nest Cobb-Douglas as special case 19 | if rho == 0: 20 | Y = K**alpha * (A * L)**(1 - alpha) 21 | else: 22 | Y = (alpha * K**rho + (1 - alpha) * (A * L)**rho)**(1 / rho) 23 | 24 | return Y 25 | 26 | def real_wage(K, L, A=1): 27 | """ 28 | 29 | Assuming perfect competition, factors are paid there marginal products. Thus 30 | the real wage paid to labor is dF/dL. 31 | 32 | """ 33 | rho = (sigma - 1) / sigma 34 | 35 | # nest Cobb-Douglas as special case 36 | if rho == 0: 37 | MPL = (1 - alpha) * (K / (A * L))**alpha 38 | else: 39 | MPL = ((1 - alpha) * (A * L)**(rho - 1) * 40 | (alpha * K**rho + (1 - alpha) * (A * L)**rho)**((1 / rho) - 1)) 41 | 42 | return MPL 43 | 44 | def return_capital(K, L, A=1): 45 | """ 46 | 47 | Assuming perfect competition, factors are paid there marginal products. Thus 48 | the real return to capital is dF/dK less depreciation. 49 | 50 | """ 51 | rho = (sigma - 1) / sigma 52 | 53 | # nest Cobb-Douglas as special case 54 | if rho == 0: 55 | MPK = alpha * (K / (A * L))**(alpha - 1) 56 | else: 57 | MPK = (alpha * K**(rho - 1) * 58 | (alpha * K**rho + (1 - alpha) * (A * L)**rho)**((1 / rho) - 1)) 59 | 60 | return MPK - delta 61 | 62 | def expansion_path(K, A): 63 | """ 64 | 65 | Set of tangency points between isocost lines and isoquants. 66 | 67 | """ 68 | path = lambda L: (r / w) - (return_capital(K, L, A) / real_wage(K, L, A)) 69 | 70 | res = optimize.root(path, x0=K, method='hybr') 71 | 72 | return res.x 73 | 74 | def C(K, L): 75 | """ 76 | 77 | Two sources of costs: labor costs, wL, and rental costs of capital, rK. 78 | 79 | """ 80 | return w * L + (r + delta) * K 81 | 82 | def Pi(K, L, A): 83 | """ 84 | 85 | Profits function from firm's maximization problem. 86 | 87 | """ 88 | return F(K, L, A) - C(K, L) 89 | 90 | # create a grid of (x,y) values which we will pass to function 91 | capital = np.linspace(0, 50, 100) 92 | labor = np.linspace(0, 50, 100) 93 | K, L = np.meshgrid(capital, labor) 94 | 95 | # Choose parameter values 96 | alpha = 0.33 97 | sigma = 1.0 98 | delta = 0.04 99 | A = 1.0 100 | w, r = real_wage(2, 1, A), return_capital(2, 1, A) 101 | 102 | # we will eventually plot... 103 | output = F(K, L, A) 104 | costs = C(K, L) 105 | profits = Pi(K, L, A) 106 | 107 | ##### Contour plots for output and costs ##### 108 | 109 | # create a new Figure object 110 | fig = plt.figure(figsize=(12,6)) 111 | 112 | # create the contour plot for the second subplot 113 | ax1 = fig.add_subplot(121) 114 | production_surface = ax1.imshow(output, interpolation='gaussian', 115 | origin='lower', cmap=mpl.cm.hot, 116 | vmin=0, vmax=np.max(output), 117 | extent=(0, 50, 0, 50)) 118 | 119 | # demarcate the contours 120 | CS = ax1.contour(K, L, output, np.linspace(0, 50, 10), colors=np.repeat('k', 10), 121 | linewidths=1, linestyles='solid') 122 | ax1.clabel(CS, inline=1, fmt='%1.2f') 123 | 124 | # axes, labels, title, colorbar etc. 125 | ax1.set_xlim(0, 50) 126 | ax1.set_ylim(0, 50) 127 | ax1.set_xlabel(r'Capital, $K$', family='serif', fontsize=15) 128 | ax1.set_ylabel(r'Labor, $L$', family='serif', fontsize=15) 129 | ax1.set_title('Isoquants', family='serif', fontsize=15) 130 | 131 | # create the contour plot for cost function 132 | ax2 = fig.add_subplot(122) 133 | cost_surface = ax2.imshow(costs, interpolation='gaussian', origin='lower', 134 | cmap=mpl.cm.cool, vmin=0, vmax=np.max(costs), 135 | extent=(0, 50, 0, 50)) 136 | 137 | # demarcate the contours 138 | CS = ax2.contour(K, L, costs, np.linspace(0, 50, 10), colors=np.repeat('k', 10), 139 | linewidths=1, linestyles='solid') 140 | ax2.clabel(CS, inline=1, fmt='%1.2f') 141 | 142 | # axes, labels, title, colorbar etc. 143 | ax2.set_xlim(0, 50) 144 | ax2.set_ylim(0, 50) 145 | ax2.set_xlabel(r'Capital, $K$', family='serif', fontsize=15) 146 | ax2.set_ylabel(r'Labor, $L$', family='serif', fontsize=15) 147 | ax2.set_title('Isocosts', family='serif', fontsize=15) 148 | 149 | fig.text(0.5, 0.925, 'Constant returns CES production with $\sigma=%g$' % sigma, 150 | fontsize=20, ha='center', family='serif') 151 | 152 | plt.savefig('graphics/contour-plots-for-output-and-costs.png') 153 | plt.show() 154 | 155 | ##### Firm Size is indeterminate with CRTS ##### 156 | 157 | # create a new Figure object 158 | fig = plt.figure(figsize=(8,8)) 159 | 160 | # create the contour plot for the second subplot 161 | ax1 = fig.add_subplot(111) 162 | 163 | # demarcate the contours 164 | CS_output = ax1.contour(K, L, output, np.linspace(0, 50, 10), cmap=mpl.cm.hot, 165 | vmin=0, vmax=np.max(output), linewidths=1, 166 | linestyles='solid') 167 | ax1.clabel(CS_output, inline=1, fmt='%1.2f') 168 | 169 | CS_costs = ax1.contour(K, L, costs, np.linspace(0, 50, 10), cmap=mpl.cm.cool, 170 | vmin=0, vmax=np.max(costs), linewidths=1, 171 | linestyles='solid') 172 | 173 | # add the expansion path 174 | ax1.plot(capital, np.array([expansion_path(k, A)[0] for k in capital]), 'r', 175 | label=r'$\frac{K}{L}$') 176 | 177 | # axes, labels, title, colorbar etc. 178 | ax1.set_xlim(0, 50) 179 | ax1.set_ylim(0, 50) 180 | ax1.set_xlabel(r'Capital, $K$', family='serif', fontsize=15) 181 | ax1.set_ylabel(r'Labor, $L$', family='serif', fontsize=15) 182 | ax1.set_title(r'With CRTS, firm size is indeterminate!', family='serif', 183 | fontsize=20) 184 | ax1.legend(loc='upper right', bbox_to_anchor=(1.15, 1.0), frameon=False) 185 | 186 | plt.savefig('graphics/firm-size-indeterminate-with-CRTS.png') 187 | plt.show() 188 | 189 | ##### Profits surface and contour plot ##### 190 | 191 | # create a new Figure object 192 | fig = plt.figure(figsize=(12,6)) 193 | 194 | # create a 3D Axes object for the first subplot 195 | ax = fig.add_subplot(121, projection='3d', elev=30, azim=-120) 196 | 197 | # note the use of the new plot command! 198 | profits_surface = ax.plot_surface(K, L, profits, rstride=1, cstride=1, 199 | cmap=mpl.cm.winter_r, linewidth=0, 200 | vmin=np.min(profits), vmax=0, antialiased=False) 201 | 202 | # add the expansion path (i.e., the zero contour!) 203 | zero_contour = ax.plot(capital, 204 | np.array([expansion_path(k, A)[0] for k in capital]), 205 | np.zeros(capital.size), 206 | 'r', label=r'$\frac{K}{L}$') 207 | 208 | # axes, labels, title, colorbar etc. 209 | ax.set_xlim(0, 50) 210 | ax.set_ylim(0, 50) 211 | ax.set_xlabel(r'Capital, $K$') 212 | ax.set_ylabel(r'Labor, $L$') 213 | ax.set_zlabel(r'Profits, $\Pi$') 214 | 215 | # create the contour plot for the second subplot 216 | ax2 = fig.add_subplot(122) 217 | im = ax2.imshow(profits, interpolation='gaussian', origin='lower', cmap=mpl.cm.winter_r, 218 | vmin=np.min(profits), vmax=0, extent=(0, 50, 0, 50)) 219 | 220 | # demarcate the contours 221 | CS = ax2.contour(K, L, profits, np.linspace(np.min(profits), 0, 10), colors=np.repeat('k', 10), 222 | linewidths=1, linestyles='solid') 223 | ax2.clabel(CS, inline=1, fmt='%1.2f') 224 | 225 | # add the expansion path (i.e., the zero contour!) 226 | zero_contour = ax2.plot(capital, 227 | np.array([expansion_path(k, A)[0] for k in capital]), 228 | 'r', label=r'$\frac{K}{L}$') 229 | 230 | # axes, labels, title, colorbar etc. 231 | ax2.set_xlim(0, 50) 232 | ax2.set_ylim(0, 50) 233 | ax2.set_xlabel(r'Capital, $K$') 234 | ax2.set_ylabel(r'Labor, $L$') 235 | 236 | # add a color bar to the figure 237 | fig.colorbar(profits_surface, shrink=0.75, aspect=10) 238 | 239 | # add a title to the figure 240 | fig.text(0.5, 0.95, 'Firms earn zero profits in equilibrium', fontsize=20, ha='center') 241 | 242 | # save the plot! 243 | #plt.savefig('2012-12-22-Zero-profits-with-CRTS.png') 244 | 245 | # display the plot! 246 | plt.show() 247 | -------------------------------------------------------------------------------- /labs/lab-2/diagram.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | 3 | plt.figure(figsize=(10,8)) 4 | ax = model.plot_phase_diagram(70, cmap='winter', arrows=True)[0] 5 | 6 | kstar = model.steady_state.values['k_star'] 7 | cstar = model.steady_state.values['c_star'] 8 | 9 | # plot the unstable manifold 10 | init = [kstar - 1e-5, cstar + 1e-5] 11 | traj = model.integrate(t0=0, y0=init, T=1e3, h=0.5, integrator='lsoda') 12 | ax.plot(traj[:,1], traj[:,2], 'r--', label='$M_U$',) 13 | 14 | ax.hlines(traj[::10,2],traj[::10,1], traj[::10,1] + 0.1 * kstar, colors='r') 15 | ax.vlines(traj[::10,1],traj[::10,2], traj[::10,2] - 0.035 * cstar, colors='r') 16 | 17 | init = [kstar + 1e-5, cstar - 1e-5] 18 | traj = model.integrate(t0=0, y0=init, T=1e3, h=0.5, integrator='lsoda') 19 | ax.plot(traj[:,1], traj[:,2], 'r--') 20 | 21 | ax.hlines(traj[::10,2],traj[::10,1], traj[::10,1] - 0.1 * kstar, colors='r') 22 | ax.vlines(traj[::10,1],traj[::10,2], traj[::10,2] + 0.035 * cstar, colors='r') 23 | 24 | # plot the stable manifold 25 | optimal_traj = model.solve_forward_shooting(0.1 * kstar, h=1.0, tol=1e-5) 26 | ax.plot(optimal_traj[:,1], optimal_traj[:,2], 'r', label='$M_S$') 27 | 28 | ax.hlines(optimal_traj[::10,2],optimal_traj[::10,1] - 0.1 * kstar, 29 | optimal_traj[::10,1], colors='r') 30 | ax.vlines(optimal_traj[::10,1],optimal_traj[::10,2] - 0.035 * cstar, 31 | optimal_traj[::10,2], colors='r') 32 | 33 | optimal_traj = model.solve_forward_shooting(6.0 * kstar, h=1.0, tol=1e-5) 34 | ax.plot(optimal_traj[:,1], optimal_traj[:,2], 'r') 35 | 36 | ax.hlines(optimal_traj[::10,2],optimal_traj[::10,1], 37 | optimal_traj[::10,1] + 0.1 * kstar, colors='r') 38 | ax.vlines(optimal_traj[::10,1],optimal_traj[::10,2], 39 | optimal_traj[::10,2] + 0.035 * cstar, colors='r') 40 | 41 | ax.set_title('Optimal growth model has stable and unstable manifolds', 42 | fontsize=20) 43 | ax.legend(loc='best', frameon=False, prop={'family':'serif'}) 44 | 45 | plt.savefig('graphics/ramsey-phase-diagram-with-manifolds.png') 46 | plt.show() -------------------------------------------------------------------------------- /labs/lab-2/diagram2.py: -------------------------------------------------------------------------------- 1 | # compute the stable manifold using forward shooting 2 | k0 = model.steady_state.values['k_star'] / 10 3 | ms_lower = model.solve_forward_shooting(k0, h=1.0, tol=1e-4, integrator='dopri5') 4 | 5 | k0 = 3.5 * model.steady_state.values['k_star'] 6 | ms_upper = model.solve_forward_shooting(k0, h=1.0, tol=1e-4, integrator='dopri5') 7 | 8 | plt.figure(figsize=(8,6)) 9 | 10 | # plot the phase diagram 11 | model.plot_phase_diagram(gridmax=130, N=1000, arrows=True) 12 | 13 | # plot the stable manifold 14 | model.plot_trajectory(ms_upper, color='r') 15 | model.plot_trajectory(ms_lower, color='r') 16 | 17 | # demarcate the initial condition 18 | plt.axvline(k0, linestyle='dashed', color='k') 19 | plt.xticks([k0], ['$k_0$']) 20 | 21 | # set of initial conditions for c 22 | N = 20 23 | c_lower = 0.99 * ms_upper[0,2] 24 | c_upper = 1.01 * ms_upper[0,2] 25 | init_vals = np.linspace(c_lower, c_upper, N) 26 | 27 | # color scheme 28 | color_map = mpl.cm.cool(np.linspace(0, 1, N)) 29 | 30 | for i, c0 in enumerate(init_vals): 31 | 32 | # simulate the model 33 | traj = model.integrate(t0=0, y0=[k0, c0], h=0.1, T=300, integrator='dopri5') 34 | 35 | # plot the trajectory 36 | model.plot_trajectory(traj, color=color_map[i]) 37 | 38 | # compute the unstable manifold 39 | eps = 1e-5 40 | k_star, c_star = model.steady_state.values['k_star'], model.steady_state.values['c_star'] 41 | 42 | mu_lower = model.integrate(t0=0, y0=[k_star + eps, c_star], h=0.1, T=300, integrator='dopri5') 43 | mu_upper = model.integrate(t0=0, y0=[k_star, c_star + eps], h=0.1, T=300, integrator='dopri5') 44 | 45 | # plot the unstable manifold 46 | model.plot_trajectory(mu_upper, color='r') 47 | model.plot_trajectory(mu_lower, color='r') 48 | 49 | # change the plot title 50 | plt.title('Deviations between $M_S (M_U)$ are magnified (squashed)!', fontsize=20, family='serif') 51 | plt.savefig('graphics/deviations-from-MS-MU.png') 52 | plt.show() -------------------------------------------------------------------------------- /labs/lab-2/exercise_4a.py: -------------------------------------------------------------------------------- 1 | # suppose there is a 100% increase in 1 / theta 2 | plt.figure(figsize=(8,6)) 3 | model.plot_phase_diagram(gridmax=100, N=1000, arrows=True, param='theta', 4 | shock=0.5, reset=True) 5 | plt.show() -------------------------------------------------------------------------------- /labs/lab-2/exercise_4b.py: -------------------------------------------------------------------------------- 1 | # suppose there is a 10% decrease in sigma 2 | plt.figure(figsize=(8,6)) 3 | model.plot_phase_diagram(gridmax=50, N=1000, arrows=True, param='sigma', 4 | shock=0.9, reset=True) 5 | plt.show() -------------------------------------------------------------------------------- /labs/lab-2/exercise_4c.py: -------------------------------------------------------------------------------- 1 | # suppose there is a 50% increase in delta 2 | plt.figure(figsize=(8,6)) 3 | model.plot_phase_diagram(gridmax=100, N=1000, arrows=True, param='delta', 4 | shock=1.5, reset=True) 5 | plt.show() -------------------------------------------------------------------------------- /labs/lab-2/exercise_5a.py: -------------------------------------------------------------------------------- 1 | plt.figure(figsize=(8,6)) 2 | model.plot_phase_diagram(gridmax=100, param='g', shock=0.5) 3 | plt.show() -------------------------------------------------------------------------------- /labs/lab-2/exercise_5b.py: -------------------------------------------------------------------------------- 1 | model.plot_impulse_response(variables='all', method='linearization', 2 | kind='efficiency_units', param='g', shock=0.5, T=50, 3 | figsize=(8,12), log=False) 4 | plt.show() -------------------------------------------------------------------------------- /labs/lab-2/graphics/CRRA Utility.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-2/graphics/CRRA Utility.png -------------------------------------------------------------------------------- /labs/lab-2/graphics/CRRA-Utility-Surface.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-2/graphics/CRRA-Utility-Surface.png -------------------------------------------------------------------------------- /labs/lab-2/graphics/CRRA-utility.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-2/graphics/CRRA-utility.png -------------------------------------------------------------------------------- /labs/lab-2/graphics/Comparing-marginal-utilities.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-2/graphics/Comparing-marginal-utilities.png -------------------------------------------------------------------------------- /labs/lab-2/graphics/Contour-plot-for-CRRA-utility-surface.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-2/graphics/Contour-plot-for-CRRA-utility-surface.png -------------------------------------------------------------------------------- /labs/lab-2/graphics/deviations-from-MS-MU.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-2/graphics/deviations-from-MS-MU.png -------------------------------------------------------------------------------- /labs/lab-2/graphics/ramsey-phase-diagram-with-manifolds.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-2/graphics/ramsey-phase-diagram-with-manifolds.png -------------------------------------------------------------------------------- /labs/lab-2/integrators.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-2/integrators.pyc -------------------------------------------------------------------------------- /labs/lab-2/pwt.py: -------------------------------------------------------------------------------- 1 | """ 2 | Functions for downloading the Penn World Tables (PWT) data from the web and 3 | coercing it into a Pandas Panel object for subsequent analysis. 4 | 5 | """ 6 | from __future__ import division 7 | from StringIO import StringIO 8 | import zipfile 9 | 10 | import pandas as pd 11 | import requests 12 | 13 | def _get_dep_rates_data(base_url, version): 14 | """Downloads the depreciation rate data.""" 15 | tmp_url = base_url + 'v' + str(version) + '/depreciation_rates.zip' 16 | tmp_buffer = requests.get(url=tmp_url) 17 | tmp_zip = zipfile.ZipFile(StringIO(tmp_buffer.content)) 18 | tmp_zip.extract('depreciation_rates.dta') 19 | 20 | def _get_pwt_data(base_url, version): 21 | """Downloads the Penn World Tables (PWT) data.""" 22 | tmp_url = base_url + 'v' + str(version) + '/pwt' + str(version) + '.zip' 23 | tmp_buffer = requests.get(url=tmp_url) 24 | tmp_zip = zipfile.ZipFile(StringIO(tmp_buffer.content)) 25 | tmp_zip.extract('pwt' + str(version) + '.dta') 26 | 27 | def download_pwt_data(base_url='http://www.rug.nl/research/ggdc/data/pwt/', version=80): 28 | """ 29 | Downloads the Penn World Tables (PWT) data. 30 | 31 | Arguments: 32 | 33 | base_url: (str) Base url to use for the download. Current default is: 34 | 35 | 'http://www.rug.nl/research/ggdc/data/pwt/' 36 | 37 | version: (int) Version number for PWT data. Default is 80 (which is the 38 | most recent version). 39 | 40 | """ 41 | _get_dep_rates_data(base_url, version) 42 | _get_pwt_data(base_url, version) 43 | 44 | def load_pwt_data(base_url='http://www.rug.nl/research/ggdc/data/pwt/', version=80): 45 | """ 46 | Load the Penn World Tables (PWT) data as a Pandas Panel object. 47 | 48 | Arguments: 49 | 50 | base_url: (str) Base url to use for the download. Current default is: 51 | 52 | 'http://www.rug.nl/research/ggdc/data/pwt/' 53 | 54 | version: (int) Version number for PWT data. Default is 80 (which is the 55 | most recent version). 56 | 57 | Returns: 58 | 59 | pwt_panel_data: (Panel) A Pandas Panel object containing the Penn World 60 | Tables (PWT) data (including data on depreciation rates). 61 | 62 | """ 63 | try: 64 | pwt_raw_data = pd.read_stata('pwt' + str(version) + '.dta') 65 | dep_rates_raw_data = pd.read_stata('depreciation_rates.dta') 66 | 67 | except IOError: 68 | download_pwt_data(base_url, version) 69 | pwt_raw_data = pd.read_stata('pwt' + str(version) + '.dta') 70 | dep_rates_raw_data = pd.read_stata('depreciation_rates.dta') 71 | 72 | # merge the data 73 | pwt_merged_data = pd.merge(pwt_raw_data, dep_rates_raw_data, how='outer', 74 | on=['countrycode', 'year']) 75 | 76 | # create the hierarchical index 77 | pwt_merged_data.year = pd.to_datetime(pwt_raw_data.year, format='%Y') 78 | pwt_merged_data.set_index(['countrycode', 'year'], inplace=True) 79 | 80 | # coerce into a panel 81 | pwt_panel_data = pwt_merged_data.to_panel() 82 | 83 | return pwt_panel_data 84 | 85 | if __name__ == '__main__': 86 | pwt_panel_data = load_pwt_data(version=80) 87 | print(pwt_panel_data) 88 | -------------------------------------------------------------------------------- /labs/lab-2/pwt.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-2/pwt.pyc -------------------------------------------------------------------------------- /labs/lab-2/ramsey.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-2/ramsey.pyc -------------------------------------------------------------------------------- /labs/lab-2/solvers.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-2/solvers.pyc -------------------------------------------------------------------------------- /labs/lab-2/steady_states.py: -------------------------------------------------------------------------------- 1 | import sympy as sp 2 | from scipy import linalg, optimize 3 | 4 | class SteadyState(object): 5 | """Abstract class representing the deterministic steady state of a model.""" 6 | 7 | def __init__(self, model): 8 | """ 9 | Initializes a SteadyState object with the following attributes: 10 | 11 | model: (object) An instance of some Model class. 12 | 13 | """ 14 | self.model = model 15 | self.eigenvalues = None 16 | self.eigenvectors = None 17 | 18 | def set_functions(self, func_dict): 19 | """ 20 | Modifies the model's steady_state_functions attribute. 21 | 22 | Arguments: 23 | 24 | func_dict: (dict) Dictionary of analytic function defining the 25 | model's steady state as functions of model parameters. 26 | 27 | """ 28 | self.functions = func_dict 29 | 30 | def set_values(self): 31 | """ 32 | Computes the steady state values using the dictionaries of analytic 33 | functions and model parameters. 34 | 35 | """ 36 | # store steady state values in a dictionary 37 | steady_state_values = {} 38 | 39 | # populate the dictionary of steady state values 40 | for key, func in self.functions.iteritems(): 41 | steady_state_values[key] = func(self.model.params) 42 | 43 | self.values = steady_state_values 44 | 45 | def find_values(self, func, method, **kwargs): 46 | """ 47 | Provides an interface to the various methods for finding the root of 48 | a univariate or multivariate function in scipy.optimize. 49 | 50 | Arguments: 51 | 52 | method: (str) For univariate functions method must be one of: 53 | 'brentq', 'brenth', 'ridder', 'bisect', or 'newton'; for 54 | multivariate function method must be one of: 'hybr', 'lm', 55 | 'broyden1', 'broyden2', 'anderson', 'linearmixing', 56 | 'diagbroyden', 'excitingmixing', 'krylov'. 57 | 58 | **kwargs: (dict) Dictionary of method specific keyword arguments. 59 | 60 | """ 61 | # list of valid multivariate root-finding methods 62 | multivariate_methods = ['hybr', 'lm', 'broyden1', 'broyden2', 63 | 'anderson', 'linearmixing', 'diagbroyden', 64 | 'excitingmixing', 'krylov'] 65 | # univariate methods 66 | if method == 'brentq': 67 | res = optimize.brentq(func, args=self.model.args, **kwargs) 68 | elif method == 'brenth': 69 | res = optimize.brenth(func, args=self.model.args, **kwargs) 70 | elif method == 'ridder': 71 | res = optimize.ridder(func, args=self.model.args, **kwargs) 72 | elif method == 'bisect': 73 | res = optimize.bisect(func, args=self.model.args, **kwargs) 74 | elif method == 'newton': 75 | res = optimize.newton(func, args=self.model.args, **kwargs) 76 | 77 | # multivariate methods are handled by optimize.root 78 | elif method in multivariate_methods: 79 | res = optimize.root(func, args=self.model.args, **kwargs) 80 | else: 81 | raise ValueError, 'Unrecognized method!' 82 | 83 | return res 84 | 85 | def set_eigen_star(self, eval_jacobian): 86 | """ 87 | Computes the eigenvalues and left eigenvectors of the Jacobian matrix 88 | evaluated at a point in phase space. 89 | 90 | Arguments: 91 | 92 | eval_jacobian: (array) Model jacobian evaluated at a point. 93 | 94 | """ 95 | # compute the eigenvalues and left eigenvectors 96 | self.eigenvalues, self.eigenvectors = linalg.eig(eval_jacobian, 97 | left=True, 98 | right=False) 99 | 100 | def check_local_stability(self, vec): 101 | """ 102 | Checks whether local stability conditions are satisfied at a given 103 | point. Stability conditions differ depending on whether or not the 104 | timing of the model is continuous or discrete. In order for the 105 | deterministic steady state to be locally stable we need to have: 106 | 107 | 1. same number of stable eigenvalues as pre-determined 108 | variables (i.e., state variables) 109 | 2. same number of unstable eigenvalues as control (i.e., 110 | jump variables). 111 | 112 | Definition of stable (unstable) eigenvalues differs slightly depending 113 | on whether the model is in continuous or discrete time. In continuous 114 | time, a the real part of a stable (unstable) eigenvalue must have 115 | negative (positive). In discrete time a stable (unstable) eigenvalue 116 | has modulus < (>) 1. 117 | 118 | Arguments: 119 | 120 | vec: (array) Point at which to conduct the local stability analysis. 121 | 122 | Returns: A list containing... 123 | 124 | eigenvalues: The eigenvalues of the Jacobian matrix. 125 | eigenvectors: The eigenvectors of the Jacobian matrix. 126 | 127 | """ 128 | # evaluate the Jacobian 129 | eval_jacobian = self.model.evaluate_jacobian(vec) 130 | 131 | # compute eigenvalues and eigenvectors 132 | self.set_eigen_star(eval_jacobian) 133 | -------------------------------------------------------------------------------- /labs/lab-2/steady_states.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-2/steady_states.pyc -------------------------------------------------------------------------------- /labs/lab-3/.ipynb_checkpoints/lab-3 hw-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "metadata": { 3 | "name": "" 4 | }, 5 | "nbformat": 3, 6 | "nbformat_minor": 0, 7 | "worksheets": [ 8 | { 9 | "cells": [ 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "
\n", 15 | "
\n", 16 | "\n", 17 | "# *Numerical Methods for Economists: Precautionary Savings*\n", 18 | "\n", 19 | "In this lab assignment you will analyze a very simple Precautionary Savings problem\n", 20 | "\n", 21 | "* Consider an individual who lives two periods. In the first period he has income $A$, and in the second period his income is stochastic and denoted by $y$\n", 22 | "* His income can only take two values; either $y= x > 0$ (with probability $\\frac{1}{2}$) or $y= -x$ (with probability $\\frac{1}{2}$)\n", 23 | "* The discount rate and interest rate are both exogenous and equal to zero\n", 24 | "* The individual chooses consumption in period 1 $c_1$ knowing $A$, but not the realisation of $y$ [let $c_2$ denote consumption in period 2]\n", 25 | "* It is always the case that $A - x >0$\n", 26 | "* Let $E$ denote the expectations operator\n", 27 | "* The objective function of the individual is $V = u(c_1)+Eu(c_2)$\n", 28 | "* You can assume that $u(.)$ is concave and satisfies the Inada conditions" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "collapsed": false, 34 | "input": [ 35 | "# Import relevant modules\n", 36 | "import numpy as np\n", 37 | "import pandas as pd\n", 38 | "import matplotlib as mpl\n", 39 | "import matplotlib.pyplot as plt" 40 | ], 41 | "language": "python", 42 | "metadata": {}, 43 | "outputs": [], 44 | "prompt_number": 4 45 | }, 46 | { 47 | "cell_type": "markdown", 48 | "metadata": {}, 49 | "source": [ 50 | "### Part a) \n", 51 | "\n", 52 | "Write out the individual's inter-temporal budget constraint." 53 | ] 54 | }, 55 | { 56 | "cell_type": "code", 57 | "collapsed": false, 58 | "input": [], 59 | "language": "python", 60 | "metadata": {}, 61 | "outputs": [] 62 | }, 63 | { 64 | "cell_type": "markdown", 65 | "metadata": {}, 66 | "source": [ 67 | "### Part b)\n", 68 | "Write out the Euler Equation." 69 | ] 70 | }, 71 | { 72 | "cell_type": "code", 73 | "collapsed": false, 74 | "input": [], 75 | "language": "python", 76 | "metadata": {}, 77 | "outputs": [] 78 | }, 79 | { 80 | "cell_type": "markdown", 81 | "metadata": {}, 82 | "source": [ 83 | "### Part c)\n", 84 | "\n", 85 | "If $x = 0$, what is $c_1$?" 86 | ] 87 | }, 88 | { 89 | "cell_type": "code", 90 | "collapsed": false, 91 | "input": [], 92 | "language": "python", 93 | "metadata": {}, 94 | "outputs": [] 95 | }, 96 | { 97 | "cell_type": "markdown", 98 | "metadata": {}, 99 | "source": [ 100 | "### Part d)\n", 101 | "\n", 102 | "If u(c) is a quadratic utility function, how does consumption in the first period respond to setting $x\\neq 0$. Explain your answer.\n" 103 | ] 104 | }, 105 | { 106 | "cell_type": "code", 107 | "collapsed": false, 108 | "input": [], 109 | "language": "python", 110 | "metadata": {}, 111 | "outputs": [] 112 | }, 113 | { 114 | "cell_type": "markdown", 115 | "metadata": {}, 116 | "source": [ 117 | "### Part e)\n", 118 | "\n", 119 | "Now consider the utility function:\n", 120 | "\n", 121 | "\\begin{equation}\n", 122 | "u(c) = 1-e^{-\\theta c}\n", 123 | "\\end{equation} \n", 124 | "\n", 125 | "Using the code for the utility function provided below as a blueprint, define another Python function that returns the marginal utility of consumption." 126 | ] 127 | }, 128 | { 129 | "cell_type": "code", 130 | "collapsed": false, 131 | "input": [ 132 | "def cara_utility(c):\n", 133 | " \"\"\"Constant absolute risk aversion utility function.\"\"\"\n", 134 | " utility = 1 - np.exp(-theta * c)\n", 135 | " return utility\n", 136 | "\n", 137 | "def cara_marginal_utility(c):\n", 138 | " \"\"\"Derivative of the constant absolute risk aversion utility function.\"\"\"\n", 139 | " marginal_utility = # INSERT YOUR CODE HERE!\n", 140 | " return marginal_utility\n" 141 | ], 142 | "language": "python", 143 | "metadata": {}, 144 | "outputs": [], 145 | "prompt_number": 5 146 | }, 147 | { 148 | "cell_type": "markdown", 149 | "metadata": {}, 150 | "source": [ 151 | "### Part f)\n", 152 | "\n", 153 | "Find $u'''(c)$, and the Coefficients of Relative and Absolute Risk Aversion (possibly as functions of c). What type of function is this? " 154 | ] 155 | }, 156 | { 157 | "cell_type": "code", 158 | "collapsed": false, 159 | "input": [], 160 | "language": "python", 161 | "metadata": {}, 162 | "outputs": [] 163 | }, 164 | { 165 | "cell_type": "markdown", 166 | "metadata": {}, 167 | "source": [ 168 | "### Part g)\n", 169 | "\n", 170 | "The code in the cell below plots $u'(c)$ for multiple values of $\\theta$. Using the diagram (and perhaps your answer from part f) explain the relationship between $\\theta$ and the level of precautionary savings." 171 | ] 172 | }, 173 | { 174 | "cell_type": "code", 175 | "collapsed": false, 176 | "input": [ 177 | "plt.figure(figsize=(8,6))\n", 178 | "\n", 179 | "# grid for plotting\n", 180 | "plot_grid = np.linspace(0, 0.5, 1000)\n", 181 | "\n", 182 | "for theta in np.logspace(-1, 1, 5):\n", 183 | " plt.plot(plot_grid, cara_marginal_utility(plot_grid), label=r'$\\theta=%g$' %theta)\n", 184 | " \n", 185 | "plt.xlabel('Consumption, $c$', fontsize=15, family='serif')\n", 186 | "plt.ylabel(\"$u'(c)$\", rotation='horizontal', fontsize=15)\n", 187 | "plt.title(r'Marginal utility of consumption for various $\\theta$', fontsize=20, family='serif')\n", 188 | "plt.legend(loc='best', frameon=False)\n", 189 | " \n", 190 | "plt.show()" 191 | ], 192 | "language": "python", 193 | "metadata": {}, 194 | "outputs": [], 195 | "prompt_number": 6 196 | }, 197 | { 198 | "cell_type": "markdown", 199 | "metadata": {}, 200 | "source": [ 201 | "### Part h)\n", 202 | "For the case where $x\\neq 0$, find $c_1$. " 203 | ] 204 | }, 205 | { 206 | "cell_type": "code", 207 | "collapsed": false, 208 | "input": [], 209 | "language": "python", 210 | "metadata": {}, 211 | "outputs": [] 212 | }, 213 | { 214 | "cell_type": "markdown", 215 | "metadata": {}, 216 | "source": [ 217 | "### Part i)\n", 218 | "\n", 219 | "Now define $D$ as precautionary savings. i.e. Amount of savings made with risky income minus the level of savings made without risk. Analyse how $D$ responds to a change in $\\theta , A$ or $x$, where a rise in $x$ is equivalent to an increase in the variance of income.\n", 220 | "\n", 221 | "**Hint: You could possibly create a function in your ipython notebook called `D(A, x)`, graph this, and anaylse for different values of the inputs/parameters, keeping the other fixed.**" 222 | ] 223 | }, 224 | { 225 | "cell_type": "code", 226 | "collapsed": false, 227 | "input": [ 228 | "# Insert optional code here!" 229 | ], 230 | "language": "python", 231 | "metadata": {}, 232 | "outputs": [] 233 | }, 234 | { 235 | "cell_type": "markdown", 236 | "metadata": {}, 237 | "source": [ 238 | "###Question 2 \n", 239 | "\n", 240 | "### Part a)\n", 241 | "\n", 242 | "Now consider the utility function:\n", 243 | "\n", 244 | "\\begin{equation}\n", 245 | "u(c) = \\frac{c^{1-\\theta}-1}{1-\\theta}\n", 246 | "\\end{equation} \n", 247 | "\n", 248 | "Repeat parts (e) to (i) of question 1 for this new utility function." 249 | ] 250 | }, 251 | { 252 | "cell_type": "code", 253 | "collapsed": false, 254 | "input": [ 255 | "def crra_utility(c):\n", 256 | " \"\"\"Constant absolute risk aversion utility function.\"\"\"\n", 257 | " utility = # INSERT YOUR CODE HERE!\n", 258 | " return utility\n", 259 | "\n", 260 | "def crra_marginal_utility(c):\n", 261 | " \"\"\"Derivative of the constant absolute risk aversion utility function.\"\"\"\n", 262 | " marginal_utility = # INSERT YOUR CODE HERE!\n", 263 | " return marginal_utility\n" 264 | ], 265 | "language": "python", 266 | "metadata": {}, 267 | "outputs": [] 268 | }, 269 | { 270 | "cell_type": "code", 271 | "collapsed": false, 272 | "input": [ 273 | "# INSERT YOUR CODE FOR PLOTTING MARGINAL UTILITY FOR VARIOUS THETA HERE!" 274 | ], 275 | "language": "python", 276 | "metadata": {}, 277 | "outputs": [] 278 | }, 279 | { 280 | "cell_type": "markdown", 281 | "metadata": {}, 282 | "source": [ 283 | "### Part b)\n", 284 | "\n", 285 | "Compare your results to part(i) of question 1 to your equivalent results for the new utility function." 286 | ] 287 | }, 288 | { 289 | "cell_type": "code", 290 | "collapsed": false, 291 | "input": [], 292 | "language": "python", 293 | "metadata": {}, 294 | "outputs": [] 295 | } 296 | ], 297 | "metadata": {} 298 | } 299 | ] 300 | } -------------------------------------------------------------------------------- /labs/lab-3/Deaton (1991).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-3/Deaton (1991).pdf -------------------------------------------------------------------------------- /labs/lab-3/Pal and Stachurski (2012).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-3/Pal and Stachurski (2012).pdf -------------------------------------------------------------------------------- /labs/lab-3/hw-assignments/Group 10 lab-3 hw.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "metadata": { 3 | "name": "" 4 | }, 5 | "nbformat": 3, 6 | "nbformat_minor": 0, 7 | "worksheets": [ 8 | { 9 | "cells": [ 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "
\n", 15 | "
\n", 16 | "\n", 17 | "# *Numerical Methods for Economists: Precautionary Savings*\n", 18 | "\n", 19 | "In this lab assignment you will analyze a very simple Precautionary Savings problem\n", 20 | "\n", 21 | "* Consider an individual who lives two periods. In the first period he has income $A$, and in the second period his income is stochastic and denoted by $y$\n", 22 | "* His income can only take two values; either $y= x > 0$ (with probability $\\frac{1}{2}$) or $y= -x$ (with probability $\\frac{1}{2}$)\n", 23 | "* The discount rate and interest rate are both exogenous and equal to zero\n", 24 | "* The individual chooses consumption in period 1 $c_1$ knowing $A$, but not the realisation of $y$ [let $c_2$ denote consumption in period 2]\n", 25 | "* It is always the case that $A - x >0$\n", 26 | "* Let $E$ denote the expectations operator\n", 27 | "* The objective function of the individual is $V = u(c_1)+Eu(c_2)$\n", 28 | "* You can assume that $u(.)$ is concave and satisfies the Inada conditions" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "collapsed": false, 34 | "input": [ 35 | "# Import relevant modules\n", 36 | "\n", 37 | "import numpy as np\n", 38 | "import pandas as pd\n", 39 | "import matplotlib as mpl\n", 40 | "import matplotlib.pyplot as plt" 41 | ], 42 | "language": "python", 43 | "metadata": {}, 44 | "outputs": [], 45 | "prompt_number": 1 46 | }, 47 | { 48 | "cell_type": "markdown", 49 | "metadata": {}, 50 | "source": [ 51 | "### Part a) \n", 52 | "\n", 53 | "Write out the individual's inter-temporal budget constraint." 54 | ] 55 | }, 56 | { 57 | "cell_type": "code", 58 | "collapsed": false, 59 | "input": [], 60 | "language": "python", 61 | "metadata": {}, 62 | "outputs": [], 63 | "prompt_number": 1 64 | }, 65 | { 66 | "cell_type": "markdown", 67 | "metadata": {}, 68 | "source": [ 69 | "### Part b)\n", 70 | "Write out the Euler Equation." 71 | ] 72 | }, 73 | { 74 | "cell_type": "code", 75 | "collapsed": false, 76 | "input": [], 77 | "language": "python", 78 | "metadata": {}, 79 | "outputs": [], 80 | "prompt_number": 1 81 | }, 82 | { 83 | "cell_type": "markdown", 84 | "metadata": {}, 85 | "source": [ 86 | "### Part c)\n", 87 | "\n", 88 | "If $x = 0$, what is $c_1$?" 89 | ] 90 | }, 91 | { 92 | "cell_type": "code", 93 | "collapsed": false, 94 | "input": [ 95 | "\n" 96 | ], 97 | "language": "python", 98 | "metadata": {}, 99 | "outputs": [], 100 | "prompt_number": 1 101 | }, 102 | { 103 | "cell_type": "markdown", 104 | "metadata": {}, 105 | "source": [ 106 | "### Part d)\n", 107 | "\n", 108 | "If u(c) is a quadratic utility function, how does consumption in the first period respond to setting $x\\neq 0$. Explain your answer.\n" 109 | ] 110 | }, 111 | { 112 | "cell_type": "code", 113 | "collapsed": false, 114 | "input": [], 115 | "language": "python", 116 | "metadata": {}, 117 | "outputs": [], 118 | "prompt_number": 1 119 | }, 120 | { 121 | "cell_type": "markdown", 122 | "metadata": {}, 123 | "source": [ 124 | "### Part e)\n", 125 | "\n", 126 | "Now consider the utility function:\n", 127 | "\n", 128 | "\\begin{equation}\n", 129 | "u(c) = 1-e^{-\\theta c}\n", 130 | "\\end{equation} \n", 131 | "\n", 132 | "Using the code for the utility function provided below as a blueprint, define another Python function that returns the marginal utility of consumption." 133 | ] 134 | }, 135 | { 136 | "cell_type": "code", 137 | "collapsed": false, 138 | "input": [ 139 | "def cara_utility(c):\n", 140 | " \"\"\"Constant absolute risk aversion utility function.\"\"\"\n", 141 | " utility = 1 - np.exp(-theta * c)\n", 142 | " return utility\n", 143 | "\n", 144 | "def cara_marginal_utility(c):\n", 145 | " \"\"\"Derivative of the constant absolute risk aversion utility function.\"\"\"\n", 146 | " marginal_utility = theta * np.exp(-theta * c)\n", 147 | " return marginal_utility\n" 148 | ], 149 | "language": "python", 150 | "metadata": {}, 151 | "outputs": [], 152 | "prompt_number": 2 153 | }, 154 | { 155 | "cell_type": "markdown", 156 | "metadata": {}, 157 | "source": [ 158 | "### Part f)\n", 159 | "\n", 160 | "Find $u'''(c)$, and the Coefficients of Relative and Absolute Risk Aversion (possibly as functions of c). What type of function is this? " 161 | ] 162 | }, 163 | { 164 | "cell_type": "code", 165 | "collapsed": false, 166 | "input": [], 167 | "language": "python", 168 | "metadata": {}, 169 | "outputs": [], 170 | "prompt_number": 2 171 | }, 172 | { 173 | "cell_type": "markdown", 174 | "metadata": {}, 175 | "source": [ 176 | "### Part g)\n", 177 | "\n", 178 | "The code in the cell below plots $u'(c)$ for multiple values of $\\theta$. Using the diagram (and perhaps your answer from part f) explain the relationship between $\\theta$ and the level of precautionary savings." 179 | ] 180 | }, 181 | { 182 | "cell_type": "code", 183 | "collapsed": false, 184 | "input": [ 185 | "plt.figure(figsize=(8,6))\n", 186 | "\n", 187 | "# grid for plotting\n", 188 | "plot_grid = np.linspace(0, 0.5, 1000)\n", 189 | "\n", 190 | "for theta in np.logspace(-1, 1, 5):\n", 191 | " plt.plot(plot_grid, cara_marginal_utility(plot_grid), label=r'$\\theta=%g$' %theta)\n", 192 | " \n", 193 | "plt.xlabel('Consumption, $c$', fontsize=15, family='serif')\n", 194 | "plt.ylabel(\"$u'(c)$\", rotation='horizontal', fontsize=15)\n", 195 | "plt.title(r'Marginal utility of consumption for various $\\theta$', fontsize=20, family='serif')\n", 196 | "plt.legend(loc='best', frameon=False)\n", 197 | " \n", 198 | "plt.show()" 199 | ], 200 | "language": "python", 201 | "metadata": {}, 202 | "outputs": [], 203 | "prompt_number": 3 204 | }, 205 | { 206 | "cell_type": "markdown", 207 | "metadata": {}, 208 | "source": [ 209 | "### Part h)\n", 210 | "For the case where $x\\neq 0$, find $c_1$. " 211 | ] 212 | }, 213 | { 214 | "cell_type": "code", 215 | "collapsed": false, 216 | "input": [], 217 | "language": "python", 218 | "metadata": {}, 219 | "outputs": [], 220 | "prompt_number": 3 221 | }, 222 | { 223 | "cell_type": "markdown", 224 | "metadata": {}, 225 | "source": [ 226 | "### Part i)\n", 227 | "\n", 228 | "Now define $D$ as precautionary savings. i.e. Amount of savings made with risky income minus the level of savings made without risk. Analyse how $D$ responds to a change in $\\theta , A$ or $x$, where a rise in $x$ is equivalent to an increase in the variance of income.\n", 229 | "\n", 230 | "**Hint: You could possibly create a function in your ipython notebook called `D(A, x)`, graph this, and anaylse for different values of the inputs/parameters, keeping the other fixed.**" 231 | ] 232 | }, 233 | { 234 | "cell_type": "code", 235 | "collapsed": false, 236 | "input": [], 237 | "language": "python", 238 | "metadata": {}, 239 | "outputs": [], 240 | "prompt_number": 7 241 | }, 242 | { 243 | "cell_type": "markdown", 244 | "metadata": {}, 245 | "source": [ 246 | "###Question 2 \n", 247 | "\n", 248 | "### Part a)\n", 249 | "\n", 250 | "Now consider the utility function:\n", 251 | "\n", 252 | "\\begin{equation}\n", 253 | "u(c) = \\frac{c^{1-\\theta}-1}{1-\\theta}\n", 254 | "\\end{equation} \n", 255 | "\n", 256 | "Repeat parts (e) to (i) of question 1 for this new utility function." 257 | ] 258 | }, 259 | { 260 | "cell_type": "code", 261 | "collapsed": false, 262 | "input": [ 263 | "def crra_utility(c):\n", 264 | " \"\"\"Constant absolute risk aversion utility function.\"\"\"\n", 265 | " if theta == 1:\n", 266 | " utility = np.log(c) \n", 267 | " else:\n", 268 | " utility = (c**(1-theta) - 1)/(1 - theta)\n", 269 | " return utility\n", 270 | "\n", 271 | "def crra_marginal_utility(c):\n", 272 | " \"\"\"Derivative of the constant absolute risk aversion utility function.\"\"\"\n", 273 | " if theta == 1:\n", 274 | " marginal_utility = 1/c \n", 275 | " else:\n", 276 | " marginal_utility = c**(-theta)\n", 277 | " return marginal_utility" 278 | ], 279 | "language": "python", 280 | "metadata": {}, 281 | "outputs": [], 282 | "prompt_number": 4 283 | }, 284 | { 285 | "cell_type": "code", 286 | "collapsed": false, 287 | "input": [ 288 | "plt.figure(figsize=(14,10))\n", 289 | "\n", 290 | "# grid for plotting\n", 291 | "plot_grid = np.linspace(0.8, 10, 100)\n", 292 | "\n", 293 | "for theta in np.logspace(-1, 1, 5):\n", 294 | " plt.plot(plot_grid, crra_marginal_utility(plot_grid), label=r'$\\theta=%g$' %theta)\n", 295 | " \n", 296 | "plt.xlabel('Consumption, $c$', fontsize=15, family='serif')\n", 297 | "plt.ylabel(\"$u'(c)$\", rotation='horizontal', fontsize=15)\n", 298 | "plt.title(r'Marginal utility of consumption for various $\\theta$', fontsize=20, family='serif')\n", 299 | "plt.legend(loc='best', frameon=False)\n", 300 | " \n", 301 | "plt.show()" 302 | ], 303 | "language": "python", 304 | "metadata": {}, 305 | "outputs": [], 306 | "prompt_number": 30 307 | }, 308 | { 309 | "cell_type": "markdown", 310 | "metadata": {}, 311 | "source": [ 312 | "### Part b)\n", 313 | "\n", 314 | "Compare your results to part(i) of question 1 to your equivalent results for the new utility function." 315 | ] 316 | }, 317 | { 318 | "cell_type": "code", 319 | "collapsed": false, 320 | "input": [], 321 | "language": "python", 322 | "metadata": {}, 323 | "outputs": [] 324 | } 325 | ], 326 | "metadata": {} 327 | } 328 | ] 329 | } -------------------------------------------------------------------------------- /labs/lab-3/lab-3 hw.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "metadata": { 3 | "name": "" 4 | }, 5 | "nbformat": 3, 6 | "nbformat_minor": 0, 7 | "worksheets": [ 8 | { 9 | "cells": [ 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "
\n", 15 | "
\n", 16 | "\n", 17 | "# *Numerical Methods for Economists: Precautionary Savings*\n", 18 | "\n", 19 | "In this lab assignment you will analyze a very simple Precautionary Savings problem\n", 20 | "\n", 21 | "* Consider an individual who lives two periods. In the first period he has income $A$, and in the second period his income is stochastic and denoted by $y$\n", 22 | "* His income can only take two values; either $y= x > 0$ (with probability $\\frac{1}{2}$) or $y= -x$ (with probability $\\frac{1}{2}$)\n", 23 | "* The discount rate and interest rate are both exogenous and equal to zero\n", 24 | "* The individual chooses consumption in period 1 $c_1$ knowing $A$, but not the realisation of $y$ [let $c_2$ denote consumption in period 2]\n", 25 | "* It is always the case that $A - x >0$\n", 26 | "* Let $E$ denote the expectations operator\n", 27 | "* The objective function of the individual is $V = u(c_1)+Eu(c_2)$\n", 28 | "* You can assume that $u(.)$ is concave and satisfies the Inada conditions" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "collapsed": false, 34 | "input": [ 35 | "# Import relevant modules\n", 36 | "import numpy as np\n", 37 | "import pandas as pd\n", 38 | "import matplotlib as mpl\n", 39 | "import matplotlib.pyplot as plt" 40 | ], 41 | "language": "python", 42 | "metadata": {}, 43 | "outputs": [], 44 | "prompt_number": 4 45 | }, 46 | { 47 | "cell_type": "markdown", 48 | "metadata": {}, 49 | "source": [ 50 | "### Part a) \n", 51 | "\n", 52 | "Write out the individual's inter-temporal budget constraint." 53 | ] 54 | }, 55 | { 56 | "cell_type": "code", 57 | "collapsed": false, 58 | "input": [], 59 | "language": "python", 60 | "metadata": {}, 61 | "outputs": [] 62 | }, 63 | { 64 | "cell_type": "markdown", 65 | "metadata": {}, 66 | "source": [ 67 | "### Part b)\n", 68 | "Write out the Euler Equation." 69 | ] 70 | }, 71 | { 72 | "cell_type": "code", 73 | "collapsed": false, 74 | "input": [], 75 | "language": "python", 76 | "metadata": {}, 77 | "outputs": [] 78 | }, 79 | { 80 | "cell_type": "markdown", 81 | "metadata": {}, 82 | "source": [ 83 | "### Part c)\n", 84 | "\n", 85 | "If $x = 0$, what is $c_1$?" 86 | ] 87 | }, 88 | { 89 | "cell_type": "code", 90 | "collapsed": false, 91 | "input": [], 92 | "language": "python", 93 | "metadata": {}, 94 | "outputs": [] 95 | }, 96 | { 97 | "cell_type": "markdown", 98 | "metadata": {}, 99 | "source": [ 100 | "### Part d)\n", 101 | "\n", 102 | "If u(c) is a quadratic utility function, how does consumption in the first period respond to setting $x\\neq 0$. Explain your answer.\n" 103 | ] 104 | }, 105 | { 106 | "cell_type": "code", 107 | "collapsed": false, 108 | "input": [], 109 | "language": "python", 110 | "metadata": {}, 111 | "outputs": [] 112 | }, 113 | { 114 | "cell_type": "markdown", 115 | "metadata": {}, 116 | "source": [ 117 | "### Part e)\n", 118 | "\n", 119 | "Now consider the utility function:\n", 120 | "\n", 121 | "\\begin{equation}\n", 122 | "u(c) = 1-e^{-\\theta c}\n", 123 | "\\end{equation} \n", 124 | "\n", 125 | "Using the code for the utility function provided below as a blueprint, define another Python function that returns the marginal utility of consumption." 126 | ] 127 | }, 128 | { 129 | "cell_type": "code", 130 | "collapsed": false, 131 | "input": [ 132 | "def cara_utility(c):\n", 133 | " \"\"\"Constant absolute risk aversion utility function.\"\"\"\n", 134 | " utility = 1 - np.exp(-theta * c)\n", 135 | " return utility\n", 136 | "\n", 137 | "def cara_marginal_utility(c):\n", 138 | " \"\"\"Derivative of the constant absolute risk aversion utility function.\"\"\"\n", 139 | " marginal_utility = # INSERT YOUR CODE HERE!\n", 140 | " return marginal_utility\n" 141 | ], 142 | "language": "python", 143 | "metadata": {}, 144 | "outputs": [], 145 | "prompt_number": 5 146 | }, 147 | { 148 | "cell_type": "markdown", 149 | "metadata": {}, 150 | "source": [ 151 | "### Part f)\n", 152 | "\n", 153 | "Find $u'''(c)$, and the Coefficients of Relative and Absolute Risk Aversion (possibly as functions of c). What type of function is this? " 154 | ] 155 | }, 156 | { 157 | "cell_type": "code", 158 | "collapsed": false, 159 | "input": [], 160 | "language": "python", 161 | "metadata": {}, 162 | "outputs": [] 163 | }, 164 | { 165 | "cell_type": "markdown", 166 | "metadata": {}, 167 | "source": [ 168 | "### Part g)\n", 169 | "\n", 170 | "The code in the cell below plots $u'(c)$ for multiple values of $\\theta$. Using the diagram (and perhaps your answer from part f) explain the relationship between $\\theta$ and the level of precautionary savings." 171 | ] 172 | }, 173 | { 174 | "cell_type": "code", 175 | "collapsed": false, 176 | "input": [ 177 | "plt.figure(figsize=(8,6))\n", 178 | "\n", 179 | "# grid for plotting\n", 180 | "plot_grid = np.linspace(0, 0.5, 1000)\n", 181 | "\n", 182 | "for theta in np.logspace(-1, 1, 5):\n", 183 | " plt.plot(plot_grid, cara_marginal_utility(plot_grid), label=r'$\\theta=%g$' %theta)\n", 184 | " \n", 185 | "plt.xlabel('Consumption, $c$', fontsize=15, family='serif')\n", 186 | "plt.ylabel(\"$u'(c)$\", rotation='horizontal', fontsize=15)\n", 187 | "plt.title(r'Marginal utility of consumption for various $\\theta$', fontsize=20, family='serif')\n", 188 | "plt.legend(loc='best', frameon=False)\n", 189 | " \n", 190 | "plt.show()" 191 | ], 192 | "language": "python", 193 | "metadata": {}, 194 | "outputs": [], 195 | "prompt_number": 6 196 | }, 197 | { 198 | "cell_type": "markdown", 199 | "metadata": {}, 200 | "source": [ 201 | "### Part h)\n", 202 | "For the case where $x\\neq 0$, find $c_1$. " 203 | ] 204 | }, 205 | { 206 | "cell_type": "code", 207 | "collapsed": false, 208 | "input": [], 209 | "language": "python", 210 | "metadata": {}, 211 | "outputs": [] 212 | }, 213 | { 214 | "cell_type": "markdown", 215 | "metadata": {}, 216 | "source": [ 217 | "### Part i)\n", 218 | "\n", 219 | "Now define $D$ as precautionary savings. i.e. Amount of savings made with risky income minus the level of savings made without risk. Analyse how $D$ responds to a change in $\\theta , A$ or $x$, where a rise in $x$ is equivalent to an increase in the variance of income.\n", 220 | "\n", 221 | "**Hint: You could possibly create a function in your ipython notebook called `D(A, x)`, graph this, and anaylse for different values of the inputs/parameters, keeping the other fixed.**" 222 | ] 223 | }, 224 | { 225 | "cell_type": "code", 226 | "collapsed": false, 227 | "input": [ 228 | "# Insert optional code here!" 229 | ], 230 | "language": "python", 231 | "metadata": {}, 232 | "outputs": [] 233 | }, 234 | { 235 | "cell_type": "markdown", 236 | "metadata": {}, 237 | "source": [ 238 | "###Question 2 \n", 239 | "\n", 240 | "### Part a)\n", 241 | "\n", 242 | "Now consider the utility function:\n", 243 | "\n", 244 | "\\begin{equation}\n", 245 | "u(c) = \\frac{c^{1-\\theta}-1}{1-\\theta}\n", 246 | "\\end{equation} \n", 247 | "\n", 248 | "Repeat parts (e) to (i) of question 1 for this new utility function." 249 | ] 250 | }, 251 | { 252 | "cell_type": "code", 253 | "collapsed": false, 254 | "input": [ 255 | "def crra_utility(c):\n", 256 | " \"\"\"Constant absolute risk aversion utility function.\"\"\"\n", 257 | " utility = # INSERT YOUR CODE HERE!\n", 258 | " return utility\n", 259 | "\n", 260 | "def crra_marginal_utility(c):\n", 261 | " \"\"\"Derivative of the constant absolute risk aversion utility function.\"\"\"\n", 262 | " marginal_utility = # INSERT YOUR CODE HERE!\n", 263 | " return marginal_utility\n" 264 | ], 265 | "language": "python", 266 | "metadata": {}, 267 | "outputs": [] 268 | }, 269 | { 270 | "cell_type": "code", 271 | "collapsed": false, 272 | "input": [ 273 | "# INSERT YOUR CODE FOR PLOTTING MARGINAL UTILITY FOR VARIOUS THETA HERE!" 274 | ], 275 | "language": "python", 276 | "metadata": {}, 277 | "outputs": [] 278 | }, 279 | { 280 | "cell_type": "markdown", 281 | "metadata": {}, 282 | "source": [ 283 | "### Part b)\n", 284 | "\n", 285 | "Compare your results to part(i) of question 1 to your equivalent results for the new utility function." 286 | ] 287 | }, 288 | { 289 | "cell_type": "code", 290 | "collapsed": false, 291 | "input": [], 292 | "language": "python", 293 | "metadata": {}, 294 | "outputs": [] 295 | } 296 | ], 297 | "metadata": {} 298 | } 299 | ] 300 | } -------------------------------------------------------------------------------- /labs/lab-3/lab-3 hw.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-3/lab-3 hw.pdf -------------------------------------------------------------------------------- /labs/lab-4/.ipynb_checkpoints/lab-4 HW-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "metadata": { 3 | "name": "" 4 | }, 5 | "nbformat": 3, 6 | "nbformat_minor": 0, 7 | "worksheets": [ 8 | { 9 | "cells": [ 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "
\n", 15 | "
" 16 | ] 17 | }, 18 | { 19 | "cell_type": "markdown", 20 | "metadata": {}, 21 | "source": [ 22 | "# Lab 4 HW: Playing around with the RBC model\n", 23 | "These questions should be answered using the `rbc_benchmark_HW.mod` file included with your lab materials." 24 | ] 25 | }, 26 | { 27 | "cell_type": "code", 28 | "collapsed": false, 29 | "input": [ 30 | "import numpy as np\n", 31 | "import matplotlib.pyplot as plt\n", 32 | "import matplotlib as mpl\n", 33 | "from mpl_toolkits.mplot3d import Axes3D\n", 34 | "from scipy import linalg, interpolate, io" 35 | ], 36 | "language": "python", 37 | "metadata": {}, 38 | "outputs": [], 39 | "prompt_number": 1 40 | }, 41 | { 42 | "cell_type": "markdown", 43 | "metadata": {}, 44 | "source": [ 45 | "# Question 1:" 46 | ] 47 | }, 48 | { 49 | "cell_type": "markdown", 50 | "metadata": {}, 51 | "source": [ 52 | "## Part a) (5 points)\n", 53 | "\n", 54 | "The only difference between the `rbc_benchmark_HW.mod` file and the `rbc_benchmark.mod` file that we used in the lab is that in `rbc_benchmark_HW.mod` I have set $\\theta = 1.0$ and $\\gamma=1.0$. What does this parameterization imply about the preferences of the representative household?" 55 | ] 56 | }, 57 | { 58 | "cell_type": "code", 59 | "collapsed": false, 60 | "input": [], 61 | "language": "python", 62 | "metadata": {}, 63 | "outputs": [] 64 | }, 65 | { 66 | "cell_type": "markdown", 67 | "metadata": {}, 68 | "source": [ 69 | "## Part b) (10 points)\n", 70 | "\n", 71 | "Using `Dynare++` solve for a first-order approximation of the household decision rules (you should also specify the same command line options that we used in the lab) and load the resulting `rbc_benchmark_HW.mat` file in a Python." 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "collapsed": false, 77 | "input": [ 78 | "# insert your code here!" 79 | ], 80 | "language": "python", 81 | "metadata": {}, 82 | "outputs": [] 83 | }, 84 | { 85 | "cell_type": "markdown", 86 | "metadata": {}, 87 | "source": [ 88 | "## Part c) (15 points)\n", 89 | "Using code provided in the lab, plot impulse response functions (IRFs) for output, consumption, and investment in response to a negative productivity shock. Discuss the economic mechanisms at work. You may wish to refer to the discussion of IRFs in Romer Chapter 5 and/or your lecture notes." 90 | ] 91 | }, 92 | { 93 | "cell_type": "code", 94 | "collapsed": false, 95 | "input": [ 96 | "# insert your code here!" 97 | ], 98 | "language": "python", 99 | "metadata": {}, 100 | "outputs": [] 101 | }, 102 | { 103 | "cell_type": "markdown", 104 | "metadata": {}, 105 | "source": [ 106 | "## Part d) (10 points)\n", 107 | "Using code provided in the lab, plot IRFs for labor supply and the real wage for the model in response to a positive productivity shock. Discuss the economic mechanisms at work. You may wish to refer to the discussion of IRFs in Romer Chapter 5 and/or your lecture notes." 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "collapsed": false, 113 | "input": [ 114 | "# insert your code here!" 115 | ], 116 | "language": "python", 117 | "metadata": {}, 118 | "outputs": [] 119 | }, 120 | { 121 | "cell_type": "markdown", 122 | "metadata": {}, 123 | "source": [ 124 | "## Part e) (10 points)\n", 125 | "\n", 126 | "Using code provided in the lab, construct the correlation matrix for the model's endogenous variables. What is the correlation between the real wage and the labor supply? How does your result compare to results reported in Romer and discussed in your lecture notes?" 127 | ] 128 | }, 129 | { 130 | "cell_type": "code", 131 | "collapsed": false, 132 | "input": [ 133 | "# insert your code here!" 134 | ], 135 | "language": "python", 136 | "metadata": {}, 137 | "outputs": [] 138 | }, 139 | { 140 | "cell_type": "markdown", 141 | "metadata": {}, 142 | "source": [ 143 | "# Question 2" 144 | ] 145 | }, 146 | { 147 | "cell_type": "markdown", 148 | "metadata": {}, 149 | "source": [ 150 | "## Part a) (5 points)\n", 151 | "\n", 152 | "Open the `rbc_benchmark_HW.mod` file and change the value of $\\theta$ to $\\theta = 2.5$. Discuss the impact of this change on household preferences." 153 | ] 154 | }, 155 | { 156 | "cell_type": "code", 157 | "collapsed": false, 158 | "input": [], 159 | "language": "python", 160 | "metadata": {}, 161 | "outputs": [] 162 | }, 163 | { 164 | "cell_type": "markdown", 165 | "metadata": {}, 166 | "source": [ 167 | "## Part b) (10 points)\n", 168 | "\n", 169 | "Using `Dynare++` solve for a first-order approximation of the household decision rules (you should also specify the same command line options that we used in the lab) and load the resulting `rbc_benchmark_HW.mat` file into Python." 170 | ] 171 | }, 172 | { 173 | "cell_type": "code", 174 | "collapsed": false, 175 | "input": [ 176 | "# insert your code here!" 177 | ], 178 | "language": "python", 179 | "metadata": {}, 180 | "outputs": [] 181 | }, 182 | { 183 | "cell_type": "markdown", 184 | "metadata": {}, 185 | "source": [ 186 | "## Part c) (15 points)\n", 187 | "Using code provided in the lab, plot IRFs for labor supply and the real wage for the model in response to a positive productivity shock. Discuss. Discuss the economic mechanisms at work. You may wish to refer to the discussion of IRFs in Romer Chapter 5 and/or your lecture notes." 188 | ] 189 | }, 190 | { 191 | "cell_type": "code", 192 | "collapsed": false, 193 | "input": [ 194 | "# insert your code here!" 195 | ], 196 | "language": "python", 197 | "metadata": {}, 198 | "outputs": [] 199 | }, 200 | { 201 | "cell_type": "markdown", 202 | "metadata": {}, 203 | "source": [ 204 | "## Part d) (20 points)\n", 205 | "\n", 206 | "Using code provided in the lab, construct the correlation matrix for the model's endogenous variables. What is the correlation between the real wage and the labor supply? How does your result compare to results reported in Romer and discussed in your lecture notes? Compare/contrast this result with your result from Question 1, Part e." 207 | ] 208 | }, 209 | { 210 | "cell_type": "code", 211 | "collapsed": false, 212 | "input": [ 213 | "# insert your code here!" 214 | ], 215 | "language": "python", 216 | "metadata": {}, 217 | "outputs": [] 218 | } 219 | ], 220 | "metadata": {} 221 | } 222 | ] 223 | } -------------------------------------------------------------------------------- /labs/lab-4/Dynare Reference Manual.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-4/Dynare Reference Manual.pdf -------------------------------------------------------------------------------- /labs/lab-4/Dynare User Guide.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-4/Dynare User Guide.pdf -------------------------------------------------------------------------------- /labs/lab-4/Dynare++ Tutorial.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-4/Dynare++ Tutorial.pdf -------------------------------------------------------------------------------- /labs/lab-4/christiano-course/Solving_and_Simulating.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-4/christiano-course/Solving_and_Simulating.zip -------------------------------------------------------------------------------- /labs/lab-4/christiano-course/Solving_and_Simulating/anothertest.m: -------------------------------------------------------------------------------- 1 | % This studies the simple nonlinear expression, 2 | % y(t) = rho*y(t-1) + alph*y(t-1)^2 + epsilon(t) 3 | %this is a stylized representation of the 2nd order approximation 4 | %to the neoclassical model. 5 | clear all 6 | close all 7 | randn('seed',1); 8 | T=500; 9 | sig=0.1; 10 | epsilon=randn(T,1)*sig; 11 | y(1)=epsilon(1); 12 | y1(1)=epsilon(1); 13 | y2(1)=epsilon(1); 14 | rho=.8; 15 | alph=.5; 16 | yy=-.6:.0001:.9; 17 | for ii = 1:length(yy) 18 | yp(ii)=rho*yy(ii)+alph*yy(ii)^2; 19 | yph(ii)=rho*yy(ii)+alph*yy(ii)^2+2*sig; 20 | ypl(ii)=rho*yy(ii)+alph*yy(ii)^2-2*sig; 21 | end 22 | figure 23 | plot(yy,yp,yy,yy,yy,yph,yy,ypl) 24 | axis tight 25 | 26 | figure 27 | for ii = 2:T 28 | y(ii)=rho*y(ii-1)+alph*y(ii-1)^2+epsilon(ii); 29 | y1(ii)=rho*y1(ii-1)+epsilon(ii); 30 | y2(ii)=rho*y2(ii-1)+alph*y1(ii-1)^2+epsilon(ii); 31 | end 32 | 33 | tt=1:T; 34 | plot(tt,y(tt),tt,y1(tt),'*-') 35 | legend('second order difference equation','simulations ignoring quadratic term, (\alpha = 0)') 36 | %axis([tt(1) tt(end) -1 2]); 37 | axis tight 38 | 39 | figure 40 | 41 | tt=1:T; 42 | plot(tt,y2(tt),tt,y1(tt),'*-') 43 | legend('pruned solution to second order difference equation','simulations ignoring quadratic term, (\alpha = 0)') 44 | %axis([tt(1) tt(end) -1 2]); 45 | axis tight 46 | 47 | break 48 | 49 | subplot(211) 50 | plot(tt,y(tt),tt,y2(tt),'*') 51 | legend('actual','pruned') 52 | axis([tt(1) tt(end) -1 2]); 53 | subplot(212) 54 | plot(tt,y1(tt),tt,y2(tt),'*') 55 | legend('linear','pruned') 56 | axis([tt(1) tt(end) -1 1]); 57 | 58 | -------------------------------------------------------------------------------- /labs/lab-4/christiano-course/Solving_and_Simulating/plott.m: -------------------------------------------------------------------------------- 1 | load C:\sw20\docs\ECB\paper2005\AER_revision\johannsen\cmrfiles\Second_order\cee\linear outp infl cons inv 2 | outplin=outp; 3 | infllin=infl; 4 | conslin=cons; 5 | invlin=inv; 6 | 7 | load C:\sw20\docs\ECB\paper2005\AER_revision\johannsen\cmrfiles\Second_order\cee\nopruning outp infl cons inv 8 | outpnoprune=outp; 9 | inflnoprune=infl; 10 | consnoprune=cons; 11 | invnoprune=inv; 12 | 13 | load C:\sw20\docs\ECB\paper2005\AER_revision\johannsen\cmrfiles\Second_order\cee\pruning outp infl cons inv 14 | outpprune=outp; 15 | inflprune=infl; 16 | consprune=cons; 17 | invprune=inv; 18 | 19 | tt=1:length(outp); 20 | 21 | subplot(221) 22 | plot(tt,outplin,tt,outpnoprune,'*-',tt,outpprune,'o-') 23 | legend('linear','no pruning','pruning') 24 | title('output') 25 | axis tight 26 | 27 | subplot(222) 28 | plot(tt,infllin,tt,inflnoprune,'*-',tt,inflprune,'o-') 29 | title('inflation') 30 | axis tight 31 | 32 | subplot(223) 33 | plot(tt,conslin,tt,consnoprune,'*-',tt,consprune,'o-') 34 | title('consumption') 35 | axis tight 36 | 37 | subplot(224) 38 | plot(tt,invlin,tt,invnoprune,'*-',tt,invprune,'o-') 39 | title('investment') 40 | axis tight 41 | -------------------------------------------------------------------------------- /labs/lab-4/christiano-course/Solving_and_Simulating/pltt.m: -------------------------------------------------------------------------------- 1 | function pltt(gkk,gsigsig,gkk2,gsigsig2,gee,gee2) 2 | kk=-.2:.01:.2; 3 | z=0.5*gkk*kk.^2+.5*gsigsig; 4 | z2=0.5*gkk2*kk.^2+.5*gsigsig2; 5 | subplot(121) 6 | plot(100*kk,100*z,100*kk,100*z2,'*-') 7 | legend('\gamma = 2','\gamma = 20') 8 | ylabel('100*( k_{t+1} (2^{nd} order) - k_t+1 (1^{st} order) )','FontSize',18) 9 | xlabel('100*( k_t - k^* ), percent deviation of initial capital from steady state','FontSize',18) 10 | axis([100*kk(1) 100*kk(end) 0 max(100*z2)*1.2]) 11 | 12 | z2=[]; 13 | z1=[]; 14 | aa=-.2:.01:.2; 15 | z=0.5*gee*aa.^2+.5*gsigsig; 16 | z2=0.5*gee2*aa.^2+.5*gsigsig2; 17 | subplot(122) 18 | plot(100*aa,100*z,100*aa,100*z2,'*-') 19 | xlabel('100*a_t, percent deviation of initial shock from steady state','FontSize',18) 20 | ylabel('100*( k_{t+1} (2^{nd} order) - k_t+1 (1^{st} order) )','FontSize',18) 21 | axis([100*aa(1) 100*aa(end) 0 max(100*z2)]) 22 | -------------------------------------------------------------------------------- /labs/lab-4/christiano-course/Solving_and_Simulating/readme.m: -------------------------------------------------------------------------------- 1 | anothertest.m - simulates the process, y(t) = rho*y(t-1) + alph* y(t-1)^2 + epsilon 2 | 3 | run.m - generates lots of graphs some of which are in the handout. 4 | 5 | second.m - computes 2nd order approximation for neoclassical model. -------------------------------------------------------------------------------- /labs/lab-4/christiano-course/Solving_and_Simulating/run.m: -------------------------------------------------------------------------------- 1 | %this computes and studies the 2nd order approximation to the policy rule 2 | %for capital in the neoclassical model. 3 | 4 | close all 5 | clear all 6 | 7 | figure 8 | k=0:.001:1.5; 9 | KK=1.5:.001:2.5; 10 | kk=[k KK]; 11 | %y=a+b*x+c*x^2 12 | %KK(1)^.36=a+b*KK(1)+c*KK(1)^2 13 | %derivative: b+2*c*x 14 | %.36*KK(1)^(.36-1) 15 | %.36*KK(1)^(.36-1)=b+2*c*KK(1) 16 | 17 | c=2; 18 | %fix c and then 19 | b=0.36*KK(1)^(0.36-1)-2*c*KK(1); 20 | a = KK(1)^.36-b*KK(1)-c*KK(1)^2; 21 | tt=1:length(k); 22 | plot(k,k.^.36,kk,kk,KK,a+b*KK+c*KK.^2) 23 | axis tight 24 | xlabel('\it K_{t}','Fontsize',28) 25 | ylabel('\it K_{t+1}','Fontsize',28) 26 | 27 | 28 | alpha=0.36; 29 | beta=0.99; 30 | delta=.02; 31 | rho=0.95; 32 | Ve=.01^2; 33 | lg=0; 34 | 35 | gamma=2; 36 | [gklin, galin, gelin, gsiglin, gkklin, gaalin, geelin, gsigsiglin, gkalin, gkelin, gksiglin, gaelin, ... 37 | gasiglin, gesiglin, ksslin] = second(alpha,beta,delta,gamma,rho,Ve,lg); 38 | 39 | lg=1; 40 | gamma=2; 41 | [gk, ga, ge, gsig, gkk, gaa, gee, gsigsig, gka, gke, gksig, gae, ... 42 | gasig, gesig, kss] = second(alpha,beta,delta,gamma,rho,Ve,lg); 43 | 44 | yy=[]; 45 | yp=[]; 46 | yplin=[]; 47 | yy=-500:.1:5; 48 | for ii = 1:length(yy) 49 | yplin(ii) = gklin*yy(ii) + gsiglin + (1/2)*gkklin*(yy(ii))^2 + gsigsiglin ... 50 | + gksiglin*yy(ii) ; 51 | end 52 | figure 53 | plot(yy,yplin-yy,yy,yy-yy) 54 | axis tight 55 | 56 | figure 57 | 58 | yy=[]; 59 | yp=[]; 60 | yplin=[]; 61 | yy=-7:.001:.1; 62 | yy=-5:.001:.1; 63 | for ii = 1:length(yy) 64 | yp(ii) = gk*yy(ii) + gsig + (1/2)*(gkk*yy(ii)^2 + gsigsig) + gksig*yy(ii) ; 65 | yplin(ii) = gklin*(exp(yy(ii)+kss)-ksslin) + gsiglin + (1/2)*gkklin*(exp(yy(ii)+kss)-ksslin)^2 + gsigsiglin ... 66 | + gksiglin*(exp(yy(ii)+kss)-ksslin) ; 67 | end 68 | 69 | 70 | figure 71 | plot(exp(yy+kss),exp(yp+kss),exp(yy+kss),yplin+ksslin,exp(yy+kss),exp(yy+kss),'--') 72 | legend('log linear','linear','45 degree') 73 | title('Comparing Two Second Order Approximations','Fontsize',28) 74 | ylabel('actual capital stock, K'', next period','Fontsize',28) 75 | xlabel('actual K','Fontsize',28) 76 | axis tight 77 | 78 | yy=[]; 79 | yp=[]; 80 | yplin=[]; 81 | yy=2:.001:3.01; 82 | for ii = 1:length(yy) 83 | yp(ii) = gk*yy(ii) + gsig + (1/2)*(gkk*yy(ii)^2 + gsigsig) + gksig*yy(ii) ; 84 | yplin(ii) = gklin*(exp(yy(ii)+kss)-ksslin) + gsiglin + (1/2)*gkklin*(exp(yy(ii)+kss)-ksslin)^2 + gsigsiglin ... 85 | + gksiglin*(exp(yy(ii)+kss)-ksslin) ; 86 | end 87 | 88 | figure 89 | plot(exp(yy+kss),exp(yp+kss),exp(yy+kss),yplin+ksslin,exp(yy+kss),exp(yy+kss),'--') 90 | legend('log linear','linear','45 degree') 91 | title('Comparing Two Second Order Approximations','Fontsize',28) 92 | ylabel('actual capital stock, K'', next period','Fontsize',28) 93 | xlabel('actual K','Fontsize',28) 94 | axis tight 95 | 96 | yy=[]; 97 | yp=[]; 98 | yplin=[]; 99 | yy=-.1:.001:3; 100 | a=2*sqrt(Ve/(1-rho^2)); 101 | aa=4*sqrt(Ve/(1-rho^2)); 102 | for ii = 1:length(yy) 103 | ypa(ii) = gk*yy(ii) + ge*a + (1/2)*(gkk*yy(ii)^2 + gee*a^2 + gsigsig) + gksig*yy(ii) ; 104 | ypaa(ii) = gk*yy(ii) + ge*aa + (1/2)*(gkk*yy(ii)^2 + gee*aa^2 + gsigsig) + gksig*yy(ii) ; 105 | yp(ii) = gk*yy(ii) + (1/2)*(gkk*yy(ii)^2 + gsigsig) + gksig*yy(ii) ; 106 | yplin(ii) = gklin*(exp(yy(ii)+kss)-ksslin) + gsiglin + (1/2)*(gkklin*(exp(yy(ii)+kss)-ksslin)^2 + gsigsiglin) ... 107 | + gksiglin*(exp(yy(ii)+kss)-ksslin) ; 108 | end 109 | 110 | [Ylin,Ilin]=min(abs(yplin-(exp(yy+kss)-ksslin))); 111 | [Y,II]=min(abs((yp-yy)./yy)); 112 | ix=0; 113 | ixa=0; 114 | ixaa=0; 115 | IF=[]; 116 | IFa=[]; 117 | IFaa=[]; 118 | for ii = 2:length(yp) 119 | if (yp(ii)-yy(ii))*(yp(ii-1)-yy(ii-1))<0 120 | ix=ix+1; 121 | IF(ix)=ii; 122 | end 123 | if (ypa(ii)-yy(ii))*(ypa(ii-1)-yy(ii-1))<0 124 | ixa=ixa+1; 125 | IFa(ixa)=ii; 126 | end 127 | if (ypaa(ii)-yy(ii))*(ypaa(ii-1)-yy(ii-1))<0 128 | ixaa=ixaa+1; 129 | IFaa(ixaa)=ii; 130 | end 131 | end 132 | 133 | if ix > 2 134 | error('fatal (run): something very wrong') 135 | end 136 | 137 | figure 138 | tt=1:length(yp); 139 | plot(yy,ypa-yy,yy,ypaa-yy,yy,yp-yy,yy,zeros(length(yy),1),yy(IF),yp(IF)-yy(IF),'*',yy(IFa),ypa(IFa)-yy(IFa),'*',yy(IFaa),ypaa(IFaa)-yy(IFaa),'*') 140 | axis tight 141 | title('Second order approximation of policy rule for log-linear capital','Fontsize',28) 142 | ylabel('\it k_{t+1} - k_{t}','Fontsize',28) 143 | xlabel('\it k_{t} - k*','Fontsize',28) 144 | 145 | figure 146 | ts=1:20; 147 | numsim=30; 148 | 149 | e=zeros(length(ts),1); 150 | ys=zeros(length(ts),numsim); 151 | yf=zeros(length(ts),numsim); 152 | a=zeros(length(ts),numsim); 153 | ct=6; 154 | plt=0; 155 | for jj = 1:numsim 156 | a(1,jj)=ct*sqrt(Ve); 157 | ys(1,jj) = ge*a(1,jj) + (1/2)*(gee*a(1,jj)^2 + gsigsig) ; 158 | yf(1,jj) = ge*a(1,jj) ; 159 | for ii = 2:length(ts) 160 | a(ii,jj)=rho*a(ii-1,jj)+ct*randn*sqrt(Ve); 161 | ys(ii,jj) = gk*ys(ii-1,jj) + ge*a(ii,jj) + (1/2)*(gkk*ys(ii-1,jj)^2 + gee*a(ii,jj)^2 + gsigsig) + gksig*ys(ii-1,jj) ; 162 | yf(ii,jj) = gk*yf(ii-1,jj) + ge*a(ii,jj) ; 163 | end 164 | if plt == 1 165 | plot(ts,ys(:,jj),ts,yf(:,jj),'*') 166 | legend('second order','first order') 167 | axis tight 168 | pause(1) 169 | end 170 | end 171 | 172 | mys=mean(ys'); 173 | myf=mean(yf'); 174 | 175 | plot(exp(yy+kss),exp(yp+kss),exp(yy+kss),yplin+ksslin,exp(yy+kss),exp(yy+kss),'--') 176 | legend('log linear','linear','45 degree') 177 | title('Comparing Two Second Order Approximations','Fontsize',28) 178 | ylabel('actual capital stock, K'', next period','Fontsize',28) 179 | xlabel('actual K','Fontsize',28) 180 | axis tight 181 | 182 | 183 | gamma=20; 184 | [gk2, ga2, ge2, gsig2, gkk2, gaa2, gee2, gsigsig2, gka2, gke2, gksig2, gae2, ... 185 | gasig2, gesig2, kss2] = second(alpha,beta,delta,gamma,rho,Ve,lg); 186 | 187 | fprintf('gk = %6.2f, ga = %6.2f, ge = %6.2f, gsig = %6.2f\n',gk,ga,ge,gsig) 188 | fprintf('gkk = %6.2f, gaa = %6.2f, gee = %6.2f, gsigsig = %6.2f, gka = %6.2f\n',gkk,gaa,gee,gsigsig,gka) 189 | fprintf('gke = %6.2f, gksig = %6.2f, gae = %6.2f, gasig = %6.2f, gesig = %6.2f, kss = %6.2f\n',gke,gksig ... 190 | ,gae,gasig,gesig,kss) 191 | 192 | %The solution is of this form: 193 | % 194 | % g = kss + gk*(k - kss) + ga*a_1 + ge*epsilon + gsig*sig ... 195 | % + (1/2)*(gkk*(k - kss)^2 + gaa*a_1^2 + gee*epsilon^2 + gsigsig*sig^2) ... 196 | % + gka*(k - kss)*a_1 + gke*(k - kss)*epsilon + gksig*(k - kss)*sig ... 197 | % + gae*a_1*epsilon + gasig*a_1*sig + gesig*epsilon*sig ; 198 | % 199 | % Under this arrangement, the state includes epsilon and a_1. 200 | % However, intuition suggests that only current a needs to be in the state. 201 | % We now show how to confirm this. 202 | % 203 | % Here, a=rho*a_1 + epsilon. 204 | % 205 | % if ga=rho*ge, then ga*a_1 + ge*epsilon = ge*(rho*a_1 + epsilon)=ge*a, 206 | % so we check this condition across ga, ge, rho. 207 | % 208 | % Consider: 209 | % 210 | % gee*a^2 = gee*(rho*a_1+epsilon)^2 = gee*(rho^2*a_1^2 + epsilon^2 + 211 | % 2*rho*a_1*epsilon) 212 | % = gee*rho^2*a_1^2 + gee*epsilon^2 + 2*gee*rho*a_1*epsilon. 213 | % so, 214 | % (1/2)*gee*a^2 = (1/2)*gee*rho^2*a_1^2 + (1/2)*gee*epsilon^2 + gee*rho*a_1*epsilon. 215 | % 216 | % Thus, we expect gee*rho^2=gaa, gae=gee*rho 217 | % Also, suppose gka=rho*gke. Then, 218 | % gka*(k - kss)*a_1 + gke*(k - kss)*epsilon = rho*gke*(k - kss)*a_1 + gke*(k - kss)*epsilon = gke*((k - kss)*rho*a_1 + (k - kss)*epsilon) 219 | % = gke*(k - kss)*a 220 | % Finally, suppose gasig=rho*gesig. Then, 221 | % gasig*a_1*sig + gesig*epsilon*sig = gesig*(rho*a_1*sig + epsilon*sig)=gesig*a*sig 222 | 223 | 224 | if abs(ga/ge-rho) > .1e-10 || abs(gee*rho^2-gaa) > .1e-10 || abs(gae-gee*rho) > .1e-10 || abs(gka-rho*gke) > .1e-10 || abs(gasig-rho*gesig) > .1e-10 225 | error('fatal (run) policy rule parameters do not satisfy expected conditions') 226 | end 227 | 228 | % thus, we can write: 229 | % 230 | % g = kss + gk*(k - kss) + ge*a + gsig*sig ... 231 | % + (1/2)*(gkk*(k - kss)^2 + gee*a^2 + gsigsig*sig^2) ... 232 | % + gke*(k - kss)*a + gksig*(k - kss)*sig + gesig*a*sig 233 | % 234 | % or, setting y=k-kss, yp = y in next period: 235 | % 236 | % yp = gk*y + ge*a + gsig*sig + (1/2)*(gkk*y^2 + gee*a^2 + gsigsig*sig^2) + gke*y*a + gksig*y*sig + gesig*a*sig 237 | 238 | figure 239 | yy=[]; 240 | yp=[]; 241 | yy=-.00007:.000001:.001; 242 | for ii = 1:length(yy) 243 | yp(ii) = gk*yy(ii) + gsig + (1/2)*(gkk*yy(ii)^2 + gsigsig) + gksig*yy(ii) ; 244 | end 245 | 246 | [Y,I]=min(abs(yy)); 247 | [YY,II]=min(abs(yy-yp)); 248 | 249 | tt=[]; 250 | tt=I-5:I+5; 251 | tt=1:length(yy); 252 | plot(exp(yy(tt)+kss),exp(yp(tt)+kss),exp(yy(tt)+kss),exp(yy(tt)+kss),'--',exp(yy(I)+kss),exp(yp(I)+kss),'*',exp(yy(II)+kss),exp(yp(II)+kss),'*') 253 | legend('policy rule','45 degree line') 254 | title(' Policy Rule in Neighborhood of Steady State','Fontsize',28) 255 | ylabel('{exp(k'')} ','Fontsize',28) 256 | xlabel('{exp(k)}','Fontsize',28) 257 | axis tight 258 | 259 | figure 260 | yy=[]; 261 | yp=[]; 262 | yy=-.00007:.00001:.001; 263 | yy=-10:.01:2.8; 264 | for ii = 1:length(yy) 265 | yp(ii) = gk*yy(ii) + gsig + (1/2)*(gkk*yy(ii)^2 + gsigsig) + gksig*yy(ii) ; 266 | end 267 | 268 | [Y,I]=min(abs(yy)); 269 | [YY,II]=min(abs(yy-yp)); 270 | tt=[]; 271 | tt=I-5:I+5; 272 | tt=1:length(yy); 273 | %plot(exp(yy(tt)+kss),exp(yp(tt)+kss),exp(yy(I)+kss),exp(yp(I)+kss),'*',exp(yy(tt)+kss),exp(yy(tt)+kss)) 274 | plot(exp(yy(tt)+kss),exp(yp(tt)+kss)-exp(yy(tt)+kss),exp(yy(I)+kss),exp(yp(I)+kss)-exp(yy(I)+kss),'*',exp(yy(tt)+kss),zeros(length(tt),1)) 275 | ylabel('exp(k'') - exp(k)','Fontsize',28) 276 | xlabel('exp(k)','Fontsize',28) 277 | title(' exp(k'') - exp(k) against exp(k)','Fontsize',28) 278 | axis tight 279 | 280 | figure 281 | subplot(211) 282 | yy=[]; 283 | yp=[]; 284 | yy=-.00007:.00001:.001; 285 | yy=-5:.001:3; 286 | yy=-.5:.001:3; 287 | yy=-48:.001:1; 288 | for ii = 1:length(yy) 289 | yp(ii) = gk*yy(ii) + gsig + (1/2)*(gkk*yy(ii)^2 + gsigsig) + gksig*yy(ii) ; 290 | end 291 | plot(yy+kss,yp+kss,yy+kss,yy+kss) 292 | ylabel('\it k_{t+1} - \it k_{t}','Fontsize',28) 293 | xlabel('\it k_{t}','Fontsize',28) 294 | title('Policy rule, holding {\it a_t = 0}, for capital stock, exp({\it k_t}), and log, capital stock, {\it k_t}','Fontsize',28) 295 | axis tight 296 | subplot(212) 297 | plot(exp(yy+kss),exp(yp)-exp(yy),exp(yy+kss),yy-yy) 298 | ylabel('exp(\it k_{t+1})-exp(\it k_{t})','Fontsize',28) 299 | xlabel('exp(\it k_{t})','Fontsize',28) 300 | axis tight 301 | 302 | pltt(gkk,gsigsig,gkk2,gsigsig2,gee,gee2); 303 | 304 | Ve=.10^2; 305 | 306 | [gk, ga, ge, gsig, gkk, gaa, gee, gsigsig, gka, gke, gksig, gae, ... 307 | gasig, gesig, kss] = second(alpha,beta,delta,gamma,rho,Ve,lg); 308 | 309 | fprintf('gk = %6.2f, ga = %6.2f, ge = %6.2f, gsig = %6.2f\n',gk,ga,ge,gsig) 310 | fprintf('gkk = %6.2f, gaa = %6.2f, gee = %6.2f, gsigsig = %6.2f, gka = %6.2f\n',gkk,gaa,gee,gsigsig,gka) 311 | fprintf('gke = %6.2f, gksig = %6.2f, gae = %6.2f, gasig = %6.2f, gesig = %6.2f, kss = %6.2f\n',gke,gksig ... 312 | ,gae,gasig,gesig,kss) 313 | 314 | 315 | 316 | -------------------------------------------------------------------------------- /labs/lab-4/christiano-course/Solving_and_Simulating/second.m: -------------------------------------------------------------------------------- 1 | function [ggk, gga, gge, ggsig, ggkk, ggaa, ggee, ggsigsig, ggka, ggke, ggksig, ggae, ggasig, ggesig, kss] = ... 2 | second(alpha,beta,delta,gamma,rho,Ve,lg) 3 | 4 | %This finds the second order expansion of the policy rule which solves the 5 | %model, max(sum, t=0,...,infinity) beta^t * u(c), subject to 6 | %c+kp-(1-delta)*k=k^alpha*exp((1-alpha)*a(t)), where a(t) = rho*a(t-1) + 7 | %epsilon(t), where Eepsilon(t)^2 = Ve. Also, u(c)=c^(1-gamma)/(1-gamma). 8 | % 9 | %The policy rule is: 10 | % 11 | % kp = g(k,a,epsilon;sig) 12 | % 13 | % where 14 | % 15 | % g = kss + gk*(k - kss) + ga*a + ge*epsilon + gsig*sig ... 16 | % + (1/2)*(gkk*(k - kss)^2 + gaa*a^2 + gee*epsilon^2 + gsigsig*sig^2) ... 17 | % + gka*(k - kss)*a + gke*(k - kss)*epsilon + gksig*(k - kss)*sig ... 18 | % + gae*a*epsilon + gasig*a*sig + gesig*epsilon*sig ; 19 | % 20 | %In the above expression, 21 | % kss is steady state capital 22 | % k is beginning of time t capital 23 | % kp is the beginning of time t+1 capital, chosen in time t 24 | % a is a(t-1) 25 | % epsilon is epsilon(t) 26 | % sig is a constant, which should be set to unity 27 | % 28 | %If lg = 1, then kss, k and kp are the log of the capital stock. Otherwise, 29 | %they are the level. 30 | % 31 | %The strategy used here follows the one described in Swanson, Anderson, Levin, 32 | %'Higher-Order Perturbation Solutions to Dynamic, Discrete-Time Rational 33 | %Expectations Models', manuscript, Federal Reserve Board, July 8, 2005. 34 | %This code is meant for class purposes only, and is very very slow (the code below 35 | %would be substantially faster if subs were replaced by eval). For superior code, 36 | %which is much, much faster and much, much 37 | %more general, see Swanson-Anderson-Levin's PerturbationAIM software. 38 | 39 | %steady state: 40 | kss=(alpha*beta/(1-(1-delta)*beta))^(1/(1-alpha)); 41 | if lg == 1;kss=log(kss);end 42 | 43 | ge=4;%this is undone by the subsequent line, and is present to deal with an incomprehensible quirk in Matlab 44 | 45 | syms c k a epsilon x n kp g gk ga ge gsig 46 | syms gkk gaa gee gsigsig gka gke gksig gae gasig gesig sig epsilonp 47 | 48 | %this is the Taylor series expansion of the policy rule about nonstochastic steady state, whose coefficients 49 | %we will compute using the implicit function theorem 50 | g = kss + gk*(k - kss) + ga*a + ge*epsilon + gsig*sig ... 51 | + (1/2)*(gkk*(k - kss)^2 + gaa*a^2 + gee*epsilon^2 + gsigsig*sig^2) ... 52 | + gka*(k - kss)*a + gke*(k - kss)*epsilon + gksig*(k - kss)*sig ... 53 | + gae*a*epsilon + gasig*a*sig + gesig*epsilon*sig ; 54 | 55 | %g=g(k,a,epsilon,sig), k=k at time t; a = a at time t-1; epsilon = eps at time t, sig = constant 56 | 57 | %here, f is the time t production function and fk is the time t marginal product of capital 58 | if lg == 1 59 | f= exp(alpha*k) * exp(rho*a + epsilon) + (1-delta) * exp(k) ; 60 | fk = alpha * exp(k*(alpha-1)) * exp(rho*a + epsilon) + (1-delta); 61 | else 62 | f= k^alpha * exp(rho*a + epsilon) + (1-delta) * k ; 63 | fk = alpha * k^(alpha-1) * exp(rho*a + epsilon) + (1-delta); 64 | end 65 | 66 | %c is time t consumption, obtained from the resource constraint, with t+1 capital left as a variable, kp 67 | if lg == 1 68 | c = f - exp(kp); 69 | else 70 | c = f - kp; 71 | end 72 | 73 | %u is the time t level of the utility function, and uc is the time t marginal utility 74 | u = (c^(1-gamma))/(1-gamma); 75 | up= c^(-gamma);%this is a function of a, epsilon, k, kp 76 | uc = subs(up,kp,g);%replace k at time t+1 (i.e., kp) with the policy rule, g 77 | 78 | % 79 | %now go for the time t+1 marginal utility of consumption, ucp 80 | ucp = subs(up,[epsilon],[sig*epsilonp]);%replace epsilon in up by sig*epsilonp (epsilonp is t+1 epsilon) 81 | ucp = subs(ucp,[a],[rho*a+epsilon]);%replace a by rho*a+epsilon 82 | ucp = subs(ucp,k,g);%replace period t capital by t+1 capital, g 83 | 84 | % 85 | %go for the period t+1 capital decision 86 | gp = subs(g,[epsilon],[sig*epsilonp]); 87 | gp = subs(gp,[a],[rho*a+epsilon]); 88 | gp = subs(gp,k,g); 89 | 90 | % 91 | %the final step in obtaining t+1 marginal utility of consumption: replace period t+1 92 | %capital with period t+1 capital decision 93 | ucp = subs(ucp,kp,gp); 94 | 95 | % 96 | %go after the period t+1 marginal product of capital 97 | fkp = subs(fk,[epsilon],[sig*epsilonp]); 98 | fkp = subs(fkp,[a],[rho*a+epsilon]); 99 | fkp = subs(fkp,k,g); 100 | 101 | % 102 | %construct the period t intertemporal error function. Applying the implicit 103 | %function theorem to this will allow us to solve for the coefficients in g 104 | R = uc - beta*ucp*fkp; 105 | 106 | Rk=diff(R,k);%differentiate R with respect to k 107 | RRk=subs(Rk,[k a epsilon sig epsilonp ],[kss 0 0 0 0]);%evaluate derivative in steady state and replace 108 | %epsilonp by 0. This is because the only way 109 | %epsilonp enters in Rk is linearly, and so this 110 | %goes to zero upon application of the expectation operator. 111 | gg=roots(sym2poly(RRk));%RRk is now a polynomial in gk, and sym2poly recovers the coefficients of this polynomial 112 | %roots then finds the roots of this polynomial. 113 | %Save the root that is less than unity in absolute 114 | %value 115 | ggk=gg(1);%the notation used here is that gij denotes a variable name and ggij is the corresponding value 116 | if abs(ggk) > 1 117 | ggk=gg(2); 118 | end 119 | if abs(ggk) > 1 120 | error('fatal(second) too many explosive eigenvalues') 121 | end 122 | 123 | %the following operations are the analog of the ones used to obtain ggk 124 | Ra = diff(R,a); 125 | RRa = subs(Ra,[k a epsilon sig epsilonp gk],[kss 0 0 0 0 ggk]); 126 | gga = roots(sym2poly(RRa)); 127 | 128 | Re = diff(R,epsilon); 129 | RRe = subs(Re,[k a epsilon sig epsilonp gk ga],[kss 0 0 0 0 ggk gga]); 130 | gge = roots(sym2poly(RRe)); 131 | 132 | Rsig=diff(R,sig); 133 | RRsig = subs(Rsig,[k a epsilon sig epsilonp gk],[kss 0 0 0 0 ggk]); 134 | ggsig = roots(sym2poly(RRsig)); 135 | 136 | sprintf('Following are the terms in the first-order expansion:\n') 137 | sprintf('gk = %8.7f, ga = %8.7f, ge = %8.7f, gsig = %8.7f \n',ggk,gga,gge,ggsig) 138 | 139 | Rkk=diff(Rk,k); 140 | Rkk = subs(Rkk,[k a epsilon sig epsilonp gk ga ge gsig],[kss 0 0 0 0 ggk gga gge ggsig]); 141 | ggkk=roots(sym2poly(Rkk)); 142 | 143 | Rka=diff(Rk,a); 144 | Rka = subs(Rka,[k a epsilon sig epsilonp gk ga ge gsig gkk],[kss 0 0 0 0 ggk gga gge ggsig ggkk]); 145 | ggka=roots(sym2poly(Rka)); 146 | 147 | Rke=diff(Rk,epsilon); 148 | Rke = subs(Rke,[k a epsilon sig epsilonp gk ga ge gsig gkk gka],[kss 0 0 0 0 ggk gga gge ggsig ggkk ggka]); 149 | ggke = roots(sym2poly(Rke)); 150 | 151 | Rksig=diff(Rk,sig); 152 | Rksig = subs(Rksig,[k a epsilon sig epsilonp gk ga ge gsig],[kss 0 0 0 0 ggk gga gge ggsig]); 153 | ggksig = roots(sym2poly(Rksig)); 154 | 155 | Raa=diff(Ra,a); 156 | Raa = subs(Raa,[k a epsilon sig epsilonp gk ga ge gsig gka gkk],[kss 0 0 0 0 ggk gga gge ggsig ggka ggkk]); 157 | ggaa = roots(sym2poly(Raa)); 158 | 159 | Rae=diff(Ra,epsilon); 160 | Rae = subs(Rae,[k a epsilon sig epsilonp gk ga ge gsig gaa gka gkk],[kss 0 0 0 0 ggk gga gge ggsig ggaa ggka ggkk]); 161 | ggae = roots(sym2poly(Rae)); 162 | 163 | Rasig=diff(Ra,sig); 164 | Rasig = subs(Rasig,[k a epsilon sig epsilonp gk ga ge gsig gksig],[kss 0 0 0 0 ggk gga gge ggsig ggksig]); 165 | ggasig = roots(sym2poly(Rasig)); 166 | 167 | 168 | Ree=diff(Re,epsilon); 169 | Ree = subs(Ree,[k a epsilon sig epsilonp gk ga ge gsig gaa gka gkk],[kss 0 0 0 0 ggk gga gge ggsig ggaa ggka ggkk]); 170 | ggee = roots(sym2poly(Ree)); 171 | 172 | Resig=diff(Re,sig); 173 | Resig = subs(Resig,[k a epsilon sig epsilonp gk ga ge gsig gasig gksig],[kss 0 0 0 0 ggk gga gge ggsig ggasig ggksig]); 174 | ggesig = roots(sym2poly(Resig)); 175 | 176 | Rsigsig=diff(Rsig,sig); 177 | Rsigsig2=diff(Rsigsig,epsilonp,2);%take the second derivative of Rsigsig w.r.t epsilonp, 178 | %to isolate coefficient on epsilonp^2 179 | Rsigsig2= subs(Rsigsig2,[k a epsilon sig epsilonp gk ga ge gsig gee],[kss 0 0 0 0 ggk gga gge ggsig ggee]);%evaluate the second derivative in ss 180 | Rsigsig = subs(Rsigsig,[k a epsilon sig epsilonp gk ga ge gsig gee],[kss 0 0 0 0 ggk gga gge ggsig ggee]); 181 | Rsigsignew = Rsigsig +(1/2)*Rsigsig2*Ve;%make sure that E[epsilonp^2] is replaced by Ve 182 | ggsigsig = roots(sym2poly(Rsigsignew)); 183 | 184 | % 185 | sprintf('Following are the second-order terms in the expansion \n') 186 | sprintf('gkk = %8.7f, gka = %8.7f, gke = %8.7f, gksig = %8.7f, gaa = %8.7f \n',ggkk,ggka,ggke,ggksig,ggaa) 187 | sprintf('gae = %8.7f, gasig = %8.7f, gee = %8.7f, gesig = %8.7f, gsigsig = %8.7f \n',ggae, ggasig, ggee, ggesig,ggsigsig) 188 | -------------------------------------------------------------------------------- /labs/lab-4/christiano-course/rbc.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-4/christiano-course/rbc.zip -------------------------------------------------------------------------------- /labs/lab-4/christiano-course/rbc/rbc.mod: -------------------------------------------------------------------------------- 1 | // following are the 'endogenous' variables: 2 | var lc, lk, ly, a; 3 | // following are the shocks 4 | varexo e; 5 | 6 | parameters beta, alpha, gamma, rho, delta; 7 | 8 | alpha = 0.36; 9 | gamma = 2; 10 | rho = 0.95; 11 | beta = 0.99; 12 | delta = .02; 13 | 14 | [css,kss,yss,zss] = ssrbc(alpha, beta, delta); 15 | 16 | model; 17 | 1/exp(gamma*(lc)) = beta/exp(gamma*(lc(+1)))*(alpha*exp(ly(+1)-lk) + 1 - delta); 18 | exp(ly) = exp(alpha*lk(-1))*exp(a); 19 | a = rho*a(-1) + e; 20 | exp(ly) = exp(lc) + exp(lk)-(1-delta)*exp(lk(-1)); 21 | end; 22 | 23 | initval; 24 | lc=log(css); 25 | lk=log(kss); 26 | ly=log(css+delta*kss); 27 | a=0; 28 | end; 29 | 30 | %verifies that the steady state computed by rbc_steadystate.m is correct 31 | steady; 32 | 33 | shocks; 34 | var e; 35 | stderr 0.01; 36 | end; 37 | 38 | stoch_simul(order=2,irf=20,nograph) lc lk ly a; -------------------------------------------------------------------------------- /labs/lab-4/christiano-course/rbc/rbc_steadystate_1.m: -------------------------------------------------------------------------------- 1 | function [ys,check] = rbc_steadystate(ys,exe) 2 | %input vectors, ys and exe not used. Still, they must be included because 3 | %the call to rbc_steadystate has these vectors as arguments. 4 | 5 | %notes on the steady state 6 | %suppose your mod file is called fname.mod. 7 | %if you supply a file called fname_steadystate.mod, dynare uses this file to 8 | %compute the steady state of the model. 9 | %if you include the steady; command, dynare will get the steady state 10 | %supplied by fname_steadystate and verify that the equations in 11 | %fname_static.m are satisfied. If they are not satisfied then Dynare 12 | %crashes, with a report of which equations are not satisfied. For this 13 | %purpose, the equations are in the order that they appear in the model 14 | %statements. 15 | %if steady; is not invoked, then the steady state in fname_steadystate.mod 16 | %is used without any check. 17 | 18 | %if you only know how to approximately compute the steady state and you 19 | %want dynare to refine your calculation, then don't include 20 | %fname_steadystate.m in the directory and instead enter your guess of the 21 | %steady state in the initval command. If the guess is good enough, dynare 22 | %will be able to refine it. Otherwise, Dynare will give you a message 23 | %saying that it cannot find the steady state. 24 | 25 | global M_ 26 | 27 | check = 0; 28 | 29 | % because some of the parameter names in this example can be confused with function values, 30 | % it is a good idea to preset the names of the parameters to ensure they 31 | % are not confused for functions: 32 | alpha=0;beta=0;delta=0; 33 | 34 | %now, read in the values of the parameters: 35 | Np = M_.param_nbr; % Number of objects in the parameter statement 36 | for i = 1:Np % 37 | paramname = deblank(M_.param_names(i,:)); % Get the name of parameter i. 38 | eval([ paramname ' = M_.params(' int2str(i) ');']); % assign the value to the parameter 39 | end % 40 | 41 | %compute the model steady state: 42 | k = (1/alpha*(1/beta - (1-delta)))^(1/(alpha-1)); 43 | c = k^alpha - delta*k; 44 | y = k^alpha; 45 | z = 1; 46 | 47 | err(1) = 1/c - beta/c*(alpha*y(+1)/k + 1 - delta); 48 | err(2) = y - (c + k - (1-delta)*k); 49 | err(3) = y - (k^alpha)*(z^(1-alpha)); 50 | 51 | 52 | if max(abs(err))>1e-9 53 | error('fatal (ssrbc1) failed to compute steady state') 54 | end 55 | 56 | %assign values to all the variables in the var command in the mod file 57 | lc=log(c); 58 | lk=log(k); 59 | ly=log(y); 60 | a=log(z); 61 | a=10; 62 | %put the steady states in the vector ys, making sure to get everything in 63 | %the right order (i.e., the order in which they appear in the var command) 64 | Ne=M_.orig_endo_nbr; 65 | ys = zeros(Ne,1); 66 | for i = 1:Ne 67 | varname = deblank(M_.endo_names(i,:)); 68 | eval(['ys(' int2str(i) ') = ' varname ';']); % Get the steady state value of this variable. 69 | end 70 | -------------------------------------------------------------------------------- /labs/lab-4/christiano-course/rbc/ssrbc.m: -------------------------------------------------------------------------------- 1 | function [c,k,y,z] = ssrbc(alpha, beta, delta) 2 | 3 | 4 | 5 | check = 0; 6 | k = (1/alpha*(1/beta - (1-delta)))^(1/(alpha-1)); 7 | c = k^alpha - delta*k; 8 | y = k^alpha; 9 | z = 1; 10 | 11 | err(1) = 1/c - beta/c*(alpha*y(+1)/k + 1 - delta); 12 | err(2) = y - (c + k - (1-delta)*k); 13 | err(3) = y - (k^alpha)*(z^(1-alpha)); 14 | 15 | 16 | if max(abs(err))>1e-9 17 | error('fatal (ssrbc1) failed to compute steady state') 18 | end 19 | -------------------------------------------------------------------------------- /labs/lab-4/graphics/Consumption for fixed C and l.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-4/graphics/Consumption for fixed C and l.png -------------------------------------------------------------------------------- /labs/lab-4/graphics/RBC contour plot for utility surface 1 period decision problem.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-4/graphics/RBC contour plot for utility surface 1 period decision problem.png -------------------------------------------------------------------------------- /labs/lab-4/graphics/RBC contour plot for utility surface, 2 period choice problem, t=0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-4/graphics/RBC contour plot for utility surface, 2 period choice problem, t=0.png -------------------------------------------------------------------------------- /labs/lab-4/graphics/RBC contour plot for utility surface, 2 period choice problem, t=1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-4/graphics/RBC contour plot for utility surface, 2 period choice problem, t=1.png -------------------------------------------------------------------------------- /labs/lab-4/graphics/RBC contour plot for utility surface.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-4/graphics/RBC contour plot for utility surface.png -------------------------------------------------------------------------------- /labs/lab-4/graphics/RBC-utility-surface.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-4/graphics/RBC-utility-surface.png -------------------------------------------------------------------------------- /labs/lab-4/graphics/Taylor-approximation-example.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-4/graphics/Taylor-approximation-example.pdf -------------------------------------------------------------------------------- /labs/lab-4/graphics/Taylor-approximation-example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-4/graphics/Taylor-approximation-example.png -------------------------------------------------------------------------------- /labs/lab-4/graphics/deterministic-taylor-approximation-example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-4/graphics/deterministic-taylor-approximation-example.png -------------------------------------------------------------------------------- /labs/lab-4/hw-assignments/rbc_benchmark_HW.mod: -------------------------------------------------------------------------------- 1 | ////////// Declare variables ////////// 2 | 3 | /* ///// Endogenous variables ///// 4 | 5 | K: capital 6 | C: consumption 7 | Z: productivity 8 | Y: output 9 | I: investment 10 | W: real wage 11 | r: net interest rate 12 | L: labor supply 13 | zero_profit: zero profit condition 14 | 15 | */ 16 | var K, C, Z, Y, I, W, r, L, zero_profit; 17 | 18 | ///// Exogenous variables ///// 19 | 20 | // eps_z: productivity shock 21 | varexo eps_z; 22 | 23 | ////////// Declare parameters ////////// 24 | parameters b, alpha, beta, delta, sigma, theta, omega, rho_z, KSS, LSS, YSS; 25 | 26 | // discount factor 27 | beta = 0.9896; 28 | 29 | // coefficient of relative risk aversion 30 | theta = 1.0; 31 | 32 | // inverse elasticity of substitution for leisure 33 | omega = 1.0; 34 | 35 | // weight for leisure in utility 36 | b = 2.0; 37 | 38 | // elasticity of substitution between capital and labor 39 | sigma = 0.75; 40 | 41 | // relative weight of capital in production 42 | alpha = 0.40; 43 | 44 | // depreciation rate of capital 45 | delta = 0.025; 46 | 47 | // persistence of productivity process 48 | rho_z = 0.95; 49 | 50 | // steady state labor supply (computed for theta=omega=delta=sigma=1) 51 | LSS = (1 - alpha) / (1 - alpha + b * (1 - alpha * beta)); 52 | 53 | // steady state capital (computed for theta=omega=delta=sigma=1) 54 | KSS = (alpha * beta)^(1 / (1 - alpha)) * LSS; 55 | 56 | // steady state output (computed for theta=omega=delta=sigma=1) 57 | YSS = KSS^alpha * LSS^(1 - alpha); 58 | 59 | ////////// Model equations ////////// 60 | 61 | model; 62 | 63 | // production (i.e., equation 3.1) 64 | Y = exp(Z) * (alpha * K(-1)^((sigma - 1) / sigma) + (1 - alpha) * L^((sigma - 1) / sigma))^(sigma / (sigma - 1)); 65 | 66 | // productivity process (i.e., equation 3.2) 67 | Z = rho_z * Z(-1) + eps_z; 68 | 69 | // real wage (i.e., equation 3.3) 70 | W = (((1 - alpha) * L^(-1 / sigma)) / (alpha * K(-1)^((sigma - 1) / sigma) + (1 - alpha) * L^((sigma - 1) / sigma))) * Y; 71 | 72 | // rental rate (i.e., equation 3.4) 73 | r = ((alpha *K(-1)^(-1 / sigma)) / (alpha * K(-1)^((sigma - 1) / sigma) + (1 - alpha) * L^((sigma - 1) / sigma))) * Y; 74 | 75 | // check that zero profit condition holds (i.e., equation 3.5) 76 | zero_profit = Y - W * L - r * K(-1); 77 | 78 | // household budget constraint (i.e., equation 3.6a) 79 | C + I = W * L + r * K(-1); 80 | 81 | // household evolution of capital (i.e., equation 3.6b) 82 | K = (1 - delta) * K(-1) + I; 83 | 84 | // consumption Euler equation (i.e., equation 3.7) 85 | C^(-theta) = beta * C(+1)^(-theta) * (1 + r(+1) - delta); 86 | 87 | // intra-temporal consumption/labor trade-off (i.e., equation 3.8) 88 | b * (1 - L)^(-omega) = W * C^(-theta); 89 | 90 | end; 91 | 92 | ////////// Initial values for computing steady state ////////// 93 | 94 | initval; 95 | K = KSS; 96 | L = LSS; 97 | Y = YSS; 98 | C = YSS - KSS; 99 | Z = 0.0; 100 | I = KSS; 101 | W = (1 - alpha) * (YSS / LSS); 102 | r = (1 / beta); 103 | zero_profit = 0.0; 104 | end; 105 | 106 | ////////// Variance covariance matrix ////////// 107 | vcov = [0.007]; 108 | -------------------------------------------------------------------------------- /labs/lab-4/lab-4 HW.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "metadata": { 3 | "name": "" 4 | }, 5 | "nbformat": 3, 6 | "nbformat_minor": 0, 7 | "worksheets": [ 8 | { 9 | "cells": [ 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "
\n", 15 | "
" 16 | ] 17 | }, 18 | { 19 | "cell_type": "markdown", 20 | "metadata": {}, 21 | "source": [ 22 | "# Lab 4 HW: Playing around with the RBC model\n", 23 | "These questions should be answered using the `rbc_benchmark_HW.mod` file included with your lab materials." 24 | ] 25 | }, 26 | { 27 | "cell_type": "code", 28 | "collapsed": false, 29 | "input": [ 30 | "import numpy as np\n", 31 | "import matplotlib.pyplot as plt\n", 32 | "import matplotlib as mpl\n", 33 | "from mpl_toolkits.mplot3d import Axes3D\n", 34 | "from scipy import linalg, interpolate, io" 35 | ], 36 | "language": "python", 37 | "metadata": {}, 38 | "outputs": [], 39 | "prompt_number": 1 40 | }, 41 | { 42 | "cell_type": "markdown", 43 | "metadata": {}, 44 | "source": [ 45 | "# Question 1:" 46 | ] 47 | }, 48 | { 49 | "cell_type": "markdown", 50 | "metadata": {}, 51 | "source": [ 52 | "## Part a) (5 points)\n", 53 | "\n", 54 | "The only difference between the `rbc_benchmark_HW.mod` file and the `rbc_benchmark.mod` file that we used in the lab is that in `rbc_benchmark_HW.mod` I have set $\\theta = 1.0$ and $\\gamma=1.0$. What does this parameterization imply about the preferences of the representative household?" 55 | ] 56 | }, 57 | { 58 | "cell_type": "code", 59 | "collapsed": false, 60 | "input": [], 61 | "language": "python", 62 | "metadata": {}, 63 | "outputs": [] 64 | }, 65 | { 66 | "cell_type": "markdown", 67 | "metadata": {}, 68 | "source": [ 69 | "## Part b) (10 points)\n", 70 | "\n", 71 | "Using `Dynare++` solve for a first-order approximation of the household decision rules (you should also specify the same command line options that we used in the lab) and load the resulting `rbc_benchmark_HW.mat` file in a Python." 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "collapsed": false, 77 | "input": [ 78 | "# insert your code here!" 79 | ], 80 | "language": "python", 81 | "metadata": {}, 82 | "outputs": [] 83 | }, 84 | { 85 | "cell_type": "markdown", 86 | "metadata": {}, 87 | "source": [ 88 | "## Part c) (15 points)\n", 89 | "Using code provided in the lab, plot impulse response functions (IRFs) for output, consumption, and investment in response to a negative productivity shock. Discuss the economic mechanisms at work. You may wish to refer to the discussion of IRFs in Romer Chapter 5 and/or your lecture notes." 90 | ] 91 | }, 92 | { 93 | "cell_type": "code", 94 | "collapsed": false, 95 | "input": [ 96 | "# insert your code here!" 97 | ], 98 | "language": "python", 99 | "metadata": {}, 100 | "outputs": [] 101 | }, 102 | { 103 | "cell_type": "markdown", 104 | "metadata": {}, 105 | "source": [ 106 | "## Part d) (10 points)\n", 107 | "Using code provided in the lab, plot IRFs for labor supply and the real wage for the model in response to a positive productivity shock. Discuss the economic mechanisms at work. You may wish to refer to the discussion of IRFs in Romer Chapter 5 and/or your lecture notes." 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "collapsed": false, 113 | "input": [ 114 | "# insert your code here!" 115 | ], 116 | "language": "python", 117 | "metadata": {}, 118 | "outputs": [] 119 | }, 120 | { 121 | "cell_type": "markdown", 122 | "metadata": {}, 123 | "source": [ 124 | "## Part e) (10 points)\n", 125 | "\n", 126 | "Using code provided in the lab, construct the correlation matrix for the model's endogenous variables. What is the correlation between the real wage and the labor supply? How does your result compare to results reported in Romer and discussed in your lecture notes?" 127 | ] 128 | }, 129 | { 130 | "cell_type": "code", 131 | "collapsed": false, 132 | "input": [ 133 | "# insert your code here!" 134 | ], 135 | "language": "python", 136 | "metadata": {}, 137 | "outputs": [] 138 | }, 139 | { 140 | "cell_type": "markdown", 141 | "metadata": {}, 142 | "source": [ 143 | "# Question 2" 144 | ] 145 | }, 146 | { 147 | "cell_type": "markdown", 148 | "metadata": {}, 149 | "source": [ 150 | "## Part a) (5 points)\n", 151 | "\n", 152 | "Open the `rbc_benchmark_HW.mod` file and change the value of $\\theta$ to $\\theta = 2.5$. Discuss the impact of this change on household preferences." 153 | ] 154 | }, 155 | { 156 | "cell_type": "code", 157 | "collapsed": false, 158 | "input": [], 159 | "language": "python", 160 | "metadata": {}, 161 | "outputs": [] 162 | }, 163 | { 164 | "cell_type": "markdown", 165 | "metadata": {}, 166 | "source": [ 167 | "## Part b) (10 points)\n", 168 | "\n", 169 | "Using `Dynare++` solve for a first-order approximation of the household decision rules (you should also specify the same command line options that we used in the lab) and load the resulting `rbc_benchmark_HW.mat` file into Python." 170 | ] 171 | }, 172 | { 173 | "cell_type": "code", 174 | "collapsed": false, 175 | "input": [ 176 | "# insert your code here!" 177 | ], 178 | "language": "python", 179 | "metadata": {}, 180 | "outputs": [] 181 | }, 182 | { 183 | "cell_type": "markdown", 184 | "metadata": {}, 185 | "source": [ 186 | "## Part c) (15 points)\n", 187 | "Using code provided in the lab, plot IRFs for labor supply and the real wage for the model in response to a positive productivity shock. Discuss. Discuss the economic mechanisms at work. You may wish to refer to the discussion of IRFs in Romer Chapter 5 and/or your lecture notes." 188 | ] 189 | }, 190 | { 191 | "cell_type": "code", 192 | "collapsed": false, 193 | "input": [ 194 | "# insert your code here!" 195 | ], 196 | "language": "python", 197 | "metadata": {}, 198 | "outputs": [] 199 | }, 200 | { 201 | "cell_type": "markdown", 202 | "metadata": {}, 203 | "source": [ 204 | "## Part d) (20 points)\n", 205 | "\n", 206 | "Using code provided in the lab, construct the correlation matrix for the model's endogenous variables. What is the correlation between the real wage and the labor supply? How does your result compare to results reported in Romer and discussed in your lecture notes? Compare/contrast this result with your result from Question 1, Part e." 207 | ] 208 | }, 209 | { 210 | "cell_type": "code", 211 | "collapsed": false, 212 | "input": [ 213 | "# insert your code here!" 214 | ], 215 | "language": "python", 216 | "metadata": {}, 217 | "outputs": [] 218 | } 219 | ], 220 | "metadata": {} 221 | } 222 | ] 223 | } -------------------------------------------------------------------------------- /labs/lab-4/literature/Aruoba et al. (2006).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-4/literature/Aruoba et al. (2006).pdf -------------------------------------------------------------------------------- /labs/lab-4/literature/Bernanke, Gertler, and Glichrist (1999).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-4/literature/Bernanke, Gertler, and Glichrist (1999).pdf -------------------------------------------------------------------------------- /labs/lab-4/literature/Christiano, Eichenbaum and Evans (2005).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-4/literature/Christiano, Eichenbaum and Evans (2005).pdf -------------------------------------------------------------------------------- /labs/lab-4/literature/Collard and Juillard (2001a).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-4/literature/Collard and Juillard (2001a).pdf -------------------------------------------------------------------------------- /labs/lab-4/literature/Collard and Juillard (2001b).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-4/literature/Collard and Juillard (2001b).pdf -------------------------------------------------------------------------------- /labs/lab-4/literature/Schmitt-Grohe and Uribe (2004).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-4/literature/Schmitt-Grohe and Uribe (2004).pdf -------------------------------------------------------------------------------- /labs/lab-4/literature/Smets and Wouters (2003).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-4/literature/Smets and Wouters (2003).pdf -------------------------------------------------------------------------------- /labs/lab-4/literature/Smets and Wouters (2007).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-4/literature/Smets and Wouters (2007).pdf -------------------------------------------------------------------------------- /labs/lab-4/rbc_benchmark.mod: -------------------------------------------------------------------------------- 1 | ////////// Declare variables ////////// 2 | 3 | /* 4 | 5 | ///// Endogenous variables ///// 6 | 7 | K: capital 8 | C: consumption 9 | Z: productivity 10 | Y: output 11 | I: investment 12 | W: real wage 13 | r: net interest rate 14 | L: labor supply 15 | zero_profit: zero profit condition 16 | 17 | */ 18 | var Y, K, L, C, I, r, W, Z, zero_profit; 19 | ///// Exogenous variables ///// 20 | 21 | // eps_z: productivity shock 22 | varexo eps_z; 23 | ////////// Declare parameters ////////// 24 | parameters b, alpha, beta, delta, sigma, theta, omega, rho_z, KSS, LSS, YSS; 25 | // discount factor 26 | # insert your code here! 27 | 28 | // coefficient of relative risk aversion 29 | theta = 2.5; 30 | 31 | // inverse elasticity of substitution for leisure 32 | # insert your code here! 33 | 34 | // weight for leisure in utility 35 | b = 2.0; 36 | 37 | // elasticity of substitution between capital and labor 38 | # insert your code here! 39 | 40 | // relative weight of capital in production 41 | alpha = 0.40; 42 | 43 | // depreciation rate of capital 44 | # insert your code here! 45 | 46 | // persistence of productivity process 47 | rho_z = 0.95; 48 | 49 | // steady state labor supply (computed for theta=omega=delta=sigma=1) 50 | LSS = (1 - alpha) / (1 - alpha + b * (1 - alpha * beta)); 51 | 52 | // steady state capital (computed for theta=omega=delta=sigma=1) 53 | KSS = (alpha * beta)^(1 / (1 - alpha)) * LSS; 54 | 55 | // steady state output (computed for theta=omega=delta=sigma=1) 56 | YSS = KSS^alpha * LSS^(1 - alpha); 57 | 58 | ////////// Model equations ////////// 59 | 60 | model; 61 | 62 | // production (i.e., equation 3.1) 63 | # insert your code here! 64 | 65 | // productivity process (i.e., equation 3.2) 66 | Z = rho_z * Z(-1) + eps_z; 67 | 68 | // real wage (i.e., equation 3.3) 69 | # insert your code here! 70 | 71 | // rental rate (i.e., equation 3.4) 72 | r = ((alpha *K(-1)^(-1 / sigma)) / (alpha * K(-1)^((sigma - 1) / sigma) + (1 - alpha) * L^((sigma - 1) / sigma))) * Y; 73 | 74 | // check that zero profit condition holds (i.e., equation 3.5) 75 | zero_profit = Y - W * L - r * K(-1); 76 | 77 | // household budget constraint (i.e., equation 3.6a) 78 | # insert your code here! 79 | 80 | // household evolution of capital (i.e., equation 3.6b) 81 | K = (1 - delta) * K(-1) + I; 82 | 83 | // consumption Euler equation (i.e., equation 3.7) 84 | # insert your code here! 85 | 86 | // intra-temporal consumption/labor trade-off (i.e., equation 3.8) 87 | b * (1 - L)^(-omega) = W * C^(-theta); 88 | 89 | end; 90 | ////////// Initial values for computing steady state ////////// 91 | 92 | initval; 93 | K = KSS; 94 | L = LSS; 95 | Y = YSS; 96 | C = (1 - alpha * beta) * YSS; 97 | Z = 0.0; 98 | I = alpha * beta * YSS; 99 | W = (1 - alpha) * (YSS / LSS); 100 | r = (1 / beta); 101 | zero_profit = 0.0; 102 | end; 103 | ////////// Variance covariance matrix ////////// 104 | vcov = [0.007]; -------------------------------------------------------------------------------- /labs/lab-4/rbc_benchmark_answers.dump: -------------------------------------------------------------------------------- 1 | var K C Z Y I W r L zero_profit; 2 | 3 | varexo eps_z; 4 | 5 | parameters b alpha beta delta sigma theta omega rho_z KSS LSS YSS; 6 | 7 | b=2; 8 | alpha=0.4; 9 | beta=0.9896; 10 | delta=0.025; 11 | sigma=0.75; 12 | theta=2.5; 13 | omega=1.5; 14 | rho_z=0.95; 15 | KSS=0.07080687506762097; 16 | LSS=0.3317996814723058; 17 | YSS=0.1788775138127046; 18 | 19 | 20 | model; 21 | // Equation 0 22 | 0 = Y - exp(Z) * ((alpha * (K(-1) ^ ((sigma - 1) / sigma)) + (1 - alpha) * (L ^ ((sigma - 1) / sigma))) ^ (sigma / (sigma - 1))); 23 | // Equation 1 24 | 0 = Z - (rho_z * Z(-1) + eps_z); 25 | // Equation 2 26 | 0 = W - Y * (((1 - alpha) * (L ^ (-(1) / sigma))) / (alpha * (K(-1) ^ ((sigma - 1) / sigma)) + (1 - alpha) * (L ^ ((sigma - 1) / sigma)))); 27 | // Equation 3 28 | 0 = r - Y * ((alpha * (K(-1) ^ (-(1) / sigma))) / (alpha * (K(-1) ^ ((sigma - 1) / sigma)) + (1 - alpha) * (L ^ ((sigma - 1) / sigma)))); 29 | // Equation 4 30 | 0 = zero_profit - (Y - L * W - K(-1) * r); 31 | // Equation 5 32 | 0 = C + I - (L * W + K(-1) * r); 33 | // Equation 6 34 | 0 = K - (I + K(-1) * (1 - delta)); 35 | // Equation 7 36 | 0 = C ^ -(theta) - (beta * (C(1) ^ -(theta))) * (1 + r(1) - delta); 37 | // Equation 8 38 | 0 = b * ((1 - L) ^ -(omega)) - W * (C ^ -(theta)); 39 | end; 40 | initval; 41 | Y=0.1788775138127046; 42 | I=0.07080687506762097; 43 | W=0.3234677857777899; 44 | L=0.3317996814723058; 45 | zero_profit=0; 46 | K=0.07080687506762097; 47 | Z=0; 48 | C=0.1080706387450836; 49 | r=1.01050929668553; 50 | end; 51 | -------------------------------------------------------------------------------- /labs/lab-4/rbc_benchmark_answers.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidrpugh/numerical-methods/96781edf61831488b8270b3b9d80c67ae78a3169/labs/lab-4/rbc_benchmark_answers.mat -------------------------------------------------------------------------------- /labs/lab-4/rbc_benchmark_answers.mod: -------------------------------------------------------------------------------- 1 | ////////// Declare variables ////////// 2 | 3 | /* ///// Endogenous variables ///// 4 | 5 | K: capital 6 | C: consumption 7 | Z: productivity 8 | Y: output 9 | I: investment 10 | W: real wage 11 | r: net interest rate 12 | L: labor supply 13 | zero_profit: zero profit condition 14 | 15 | */ 16 | var K, C, Z, Y, I, W, r, L, zero_profit; 17 | 18 | ///// Exogenous variables ///// 19 | 20 | // eps_z: productivity shock 21 | varexo eps_z; 22 | 23 | ////////// Declare parameters ////////// 24 | parameters b, alpha, beta, delta, sigma, theta, omega, rho_z, KSS, LSS, YSS; 25 | 26 | // discount factor 27 | beta = 0.9896; 28 | 29 | // coefficient of relative risk aversion 30 | theta = 2.5; 31 | 32 | // inverse elasticity of substitution for leisure 33 | omega = 1.5; 34 | 35 | // weight for leisure in utility 36 | b = 2.0; 37 | 38 | // elasticity of substitution between capital and labor 39 | sigma = 0.75; 40 | 41 | // relative weight of capital in production 42 | alpha = 0.40; 43 | 44 | // depreciation rate of capital 45 | delta = 0.025; 46 | 47 | // persistence of productivity process 48 | rho_z = 0.95; 49 | 50 | // steady state labor supply (computed for theta=omega=delta=sigma=1) 51 | LSS = (1 - alpha) / (1 - alpha + b * (1 - alpha * beta)); 52 | 53 | // steady state capital (computed for theta=omega=delta=sigma=1) 54 | KSS = (alpha * beta)^(1 / (1 - alpha)) * LSS; 55 | 56 | // steady state output (computed for theta=omega=delta=sigma=1) 57 | YSS = KSS^alpha * LSS^(1 - alpha); 58 | 59 | ////////// Model equations ////////// 60 | 61 | model; 62 | 63 | // production (i.e., equation 3.1) 64 | Y = exp(Z) * (alpha * K(-1)^((sigma - 1) / sigma) + (1 - alpha) * L^((sigma - 1) / sigma))^(sigma / (sigma - 1)); 65 | 66 | // productivity process (i.e., equation 3.2) 67 | Z = rho_z * Z(-1) + eps_z; 68 | 69 | // real wage (i.e., equation 3.3) 70 | W = (((1 - alpha) * L^(-1 / sigma)) / (alpha * K(-1)^((sigma - 1) / sigma) + (1 - alpha) * L^((sigma - 1) / sigma))) * Y; 71 | 72 | // rental rate (i.e., equation 3.4) 73 | r = ((alpha *K(-1)^(-1 / sigma)) / (alpha * K(-1)^((sigma - 1) / sigma) + (1 - alpha) * L^((sigma - 1) / sigma))) * Y; 74 | 75 | // check that zero profit condition holds (i.e., equation 3.5) 76 | zero_profit = Y - W * L - r * K(-1); 77 | 78 | // household budget constraint (i.e., equation 3.6a) 79 | C + I = W * L + r * K(-1); 80 | 81 | // household evolution of capital (i.e., equation 3.6b) 82 | K = (1 - delta) * K(-1) + I; 83 | 84 | // consumption Euler equation (i.e., equation 3.7) 85 | C^(-theta) = beta * C(+1)^(-theta) * (1 + r(+1) - delta); 86 | 87 | // intra-temporal consumption/labor trade-off (i.e., equation 3.8) 88 | b * (1 - L)^(-omega) = W * C^(-theta); 89 | 90 | end; 91 | 92 | ////////// Initial values for computing steady state ////////// 93 | 94 | initval; 95 | K = KSS; 96 | L = LSS; 97 | Y = YSS; 98 | C = YSS - KSS; 99 | Z = 0.0; 100 | I = KSS; 101 | W = (1 - alpha) * (YSS / LSS); 102 | r = (1 / beta); 103 | zero_profit = 0.0; 104 | end; 105 | 106 | ////////// Variance covariance matrix ////////// 107 | vcov = [0.007]; 108 | -------------------------------------------------------------------------------- /labs/lab-4/rbc_benchmark_answers_f.m: -------------------------------------------------------------------------------- 1 | % Usage: 2 | % out = rbc_benchmark_answers_f(params, y) 3 | % where 4 | % out is a (9,1) column vector of the residuals 5 | % of the static system 6 | % params is a (11,1) vector of parameter values 7 | % in the ordering as declared 8 | % y is a (9,1) vector of endogenous variables 9 | % in the ordering as declared 10 | % 11 | % Created by Dynare++ v. 4.3.3 12 | 13 | % params ordering 14 | % ===================== 15 | % b 16 | % alpha 17 | % beta 18 | % delta 19 | % sigma 20 | % theta 21 | % omega 22 | % rho_z 23 | % KSS 24 | % LSS 25 | % YSS 26 | % 27 | % y ordering 28 | % ===================== 29 | % K 30 | % C 31 | % Z 32 | % Y 33 | % I 34 | % W 35 | % r 36 | % L 37 | % zero_profit 38 | 39 | function out = rbc_benchmark_answers_f(params, y) 40 | if size(y) ~= [9,1] 41 | error('Wrong size of y, must be [9,1]'); 42 | end 43 | if size(params) ~= [11,1] 44 | error('Wrong size of params, must be [11,1]'); 45 | end 46 | 47 | % hardwired constants 48 | a0 = 0; 49 | a1 = 1; 50 | a2 = NaN; 51 | a3 = 1.1283792; 52 | % numerical constants 53 | a10 = 1; 54 | % parameter values 55 | a73 = params(1); % b 56 | a7 = params(2); % alpha 57 | a64 = params(3); % beta 58 | a56 = params(4); % delta 59 | a9 = params(5); % sigma 60 | a61 = params(6); % theta 61 | a75 = params(7); % omega 62 | a24 = params(8); % rho_z 63 | % KSS not used in the model 64 | % LSS not used in the model 65 | % YSS not used in the model 66 | % exogenous variables to zeros 67 | a27 = 0.0; % eps_z 68 | % endogenous variables to y 69 | a8 = y(1); % K 70 | a55 = y(1); % K 71 | a50 = y(2); % C 72 | a65 = y(2); % C 73 | a25 = y(3); % Z 74 | a5 = y(3); % Z 75 | a4 = y(4); % Y 76 | a51 = y(5); % I 77 | a30 = y(6); % W 78 | a38 = y(7); % r 79 | a68 = y(7); % r 80 | a16 = y(8); % L 81 | a44 = y(9); % zero_profit 82 | 83 | t6 = exp(a5); 84 | t11 = a9 - a10; 85 | t12 = t11 / a9; 86 | t13 = a8 ^ t12; 87 | t14 = a7 * t13; 88 | t15 = a10 - a7; 89 | t17 = a16 ^ t12; 90 | t18 = t15 * t17; 91 | t19 = t14 + t18; 92 | t20 = a9 / t11; 93 | t21 = t19 ^ t20; 94 | t22 = t6 * t21; 95 | t23 = a4 - t22; 96 | t26 = a24 * a25; 97 | t28 = t26 + a27; 98 | t29 = a5 - t28; 99 | t31 = -(a10); 100 | t32 = t31 / a9; 101 | t33 = a16 ^ t32; 102 | t34 = t15 * t33; 103 | t35 = t34 / t19; 104 | t36 = a4 * t35; 105 | t37 = a30 - t36; 106 | t39 = a8 ^ t32; 107 | t40 = a7 * t39; 108 | t41 = t40 / t19; 109 | t42 = a4 * t41; 110 | t43 = a38 - t42; 111 | t45 = a16 * a30; 112 | t46 = a4 - t45; 113 | t47 = a8 * a38; 114 | t48 = t46 - t47; 115 | t49 = a44 - t48; 116 | t52 = a50 + a51; 117 | t53 = t45 + t47; 118 | t54 = t52 - t53; 119 | t57 = a10 - a56; 120 | t58 = a8 * t57; 121 | t59 = a51 + t58; 122 | t60 = a55 - t59; 123 | t62 = -(a61); 124 | t63 = a50 ^ t62; 125 | t66 = a65 ^ t62; 126 | t67 = a64 * t66; 127 | t69 = a10 + a68; 128 | t70 = t69 - a56; 129 | t71 = t67 * t70; 130 | t72 = t63 - t71; 131 | t74 = a10 - a16; 132 | t76 = -(a75); 133 | t77 = t74 ^ t76; 134 | t78 = a73 * t77; 135 | t79 = a30 * t63; 136 | t80 = t78 - t79; 137 | % setting the output variable 138 | out = zeros(9, 1); 139 | out(1) = t23; 140 | out(2) = t29; 141 | out(3) = t37; 142 | out(4) = t43; 143 | out(5) = t49; 144 | out(6) = t54; 145 | out(7) = t60; 146 | out(8) = t72; 147 | out(9) = t80; 148 | -------------------------------------------------------------------------------- /labs/lab-4/rbc_benchmark_answers_ff.m: -------------------------------------------------------------------------------- 1 | % Usage: 2 | % out = rbc_benchmark_answers_ff(params, y) 3 | % where 4 | % out is a (9,9) matrix of the first order 5 | % derivatives of the static system residuals 6 | % columns correspond to endo variables in 7 | % the ordering as declared 8 | % params is a (11,1) vector of parameter values 9 | % in the ordering as declared 10 | % y is a (9,1) vector of endogenous variables 11 | % in the ordering as declared 12 | % 13 | % Created by Dynare++ v. 4.3.3 14 | 15 | % params ordering 16 | % ===================== 17 | % b 18 | % alpha 19 | % beta 20 | % delta 21 | % sigma 22 | % theta 23 | % omega 24 | % rho_z 25 | % KSS 26 | % LSS 27 | % YSS 28 | % 29 | % y ordering 30 | % ===================== 31 | % K 32 | % C 33 | % Z 34 | % Y 35 | % I 36 | % W 37 | % r 38 | % L 39 | % zero_profit 40 | 41 | function out = rbc_benchmark_answers_ff(params, y) 42 | if size(y) ~= [9,1] 43 | error('Wrong size of y, must be [9,1]'); 44 | end 45 | if size(params) ~= [11,1] 46 | error('Wrong size of params, must be [11,1]'); 47 | end 48 | 49 | % hardwired constants 50 | a0 = 0; 51 | a1 = 1; 52 | a2 = NaN; 53 | a3 = 1.1283792; 54 | % numerical constants 55 | a10 = 1; 56 | % parameter values 57 | a73 = params(1); % b 58 | a7 = params(2); % alpha 59 | a64 = params(3); % beta 60 | a56 = params(4); % delta 61 | a9 = params(5); % sigma 62 | a61 = params(6); % theta 63 | a75 = params(7); % omega 64 | a24 = params(8); % rho_z 65 | % KSS not used in the model 66 | % LSS not used in the model 67 | % YSS not used in the model 68 | % exogenous variables to zeros 69 | a27 = 0.0; % eps_z 70 | % endogenous variables to y 71 | a8 = y(1); % K 72 | a55 = y(1); % K 73 | a50 = y(2); % C 74 | a65 = y(2); % C 75 | a25 = y(3); % Z 76 | a5 = y(3); % Z 77 | a4 = y(4); % Y 78 | a51 = y(5); % I 79 | a30 = y(6); % W 80 | a38 = y(7); % r 81 | a68 = y(7); % r 82 | a16 = y(8); % L 83 | a44 = y(9); % zero_profit 84 | 85 | t1 = a1; 86 | t6 = exp(a5); 87 | t15 = a10 - a7; 88 | t11 = a9 - a10; 89 | t12 = t11 / a9; 90 | t83 = t12 - a1; 91 | t84 = a16 ^ t83; 92 | t85 = t12 * t84; 93 | t86 = t15 * t85; 94 | t20 = a9 / t11; 95 | t13 = a8 ^ t12; 96 | t14 = a7 * t13; 97 | t17 = a16 ^ t12; 98 | t18 = t15 * t17; 99 | t19 = t14 + t18; 100 | t89 = t20 - a1; 101 | t90 = t19 ^ t89; 102 | t91 = t20 * t90; 103 | t92 = t86 * t91; 104 | t93 = t6 * t92; 105 | t94 = -(t93); 106 | t21 = t19 ^ t20; 107 | t22 = t6 * t21; 108 | t95 = -(t22); 109 | t98 = a8 ^ t83; 110 | t99 = t12 * t98; 111 | t100 = a7 * t99; 112 | t101 = t91 * t100; 113 | t102 = t6 * t101; 114 | t103 = -(t102); 115 | t436 = -(a24); 116 | t31 = -(a10); 117 | t32 = t31 / a9; 118 | t33 = a16 ^ t32; 119 | t34 = t15 * t33; 120 | t35 = t34 / t19; 121 | t438 = -(t35); 122 | t440 = t32 - a1; 123 | t441 = a16 ^ t440; 124 | t442 = t32 * t441; 125 | t443 = t15 * t442; 126 | t445 = t19 * t443; 127 | t444 = t34 * t86; 128 | t446 = t445 - t444; 129 | t447 = t19 * t19; 130 | t448 = t446 / t447; 131 | t449 = a4 * t448; 132 | t450 = -(t449); 133 | t451 = t34 * t100; 134 | t452 = -(t451); 135 | t453 = t452 / t447; 136 | t454 = a4 * t453; 137 | t455 = -(t454); 138 | t39 = a8 ^ t32; 139 | t40 = a7 * t39; 140 | t41 = t40 / t19; 141 | t1116 = -(t41); 142 | t1117 = t40 * t86; 143 | t1118 = -(t1117); 144 | t1119 = t1118 / t447; 145 | t1120 = a4 * t1119; 146 | t1121 = -(t1120); 147 | t1123 = a8 ^ t440; 148 | t1124 = t32 * t1123; 149 | t1125 = a7 * t1124; 150 | t1127 = t19 * t1125; 151 | t1126 = t40 * t100; 152 | t1128 = t1127 - t1126; 153 | t1129 = t1128 / t447; 154 | t1130 = a4 * t1129; 155 | t1131 = -(t1130); 156 | t437 = -(a1); 157 | t1678 = -(a16); 158 | t1679 = -(t1678); 159 | t1680 = -(a30); 160 | t1681 = -(t1680); 161 | t1682 = -(a8); 162 | t1683 = -(t1682); 163 | t1684 = -(a38); 164 | t1685 = -(t1684); 165 | t57 = a10 - a56; 166 | t1687 = -(t57); 167 | t69 = a10 + a68; 168 | t70 = t69 - a56; 169 | t62 = -(a61); 170 | t1690 = t62 - a1; 171 | t1691 = a65 ^ t1690; 172 | t1692 = t62 * t1691; 173 | t1693 = a64 * t1692; 174 | t1694 = t70 * t1693; 175 | t1695 = -(t1694); 176 | t66 = a65 ^ t62; 177 | t67 = a64 * t66; 178 | t1696 = -(t67); 179 | t1699 = a50 ^ t1690; 180 | t1700 = t62 * t1699; 181 | t63 = a50 ^ t62; 182 | t1765 = -(t63); 183 | t76 = -(a75); 184 | t74 = a10 - a16; 185 | t1768 = t76 - a1; 186 | t1769 = t74 ^ t1768; 187 | t1770 = t76 * t1769; 188 | t1771 = t437 * t1770; 189 | t1772 = a73 * t1771; 190 | t1773 = a30 * t1700; 191 | t1774 = -(t1773); 192 | % setting the output variable 193 | out = zeros(9, 9); 194 | out(1,4) = out(1,4) + t1; % Y(0) 195 | out(1,8) = out(1,8) + t94; % L(0) 196 | out(1,3) = out(1,3) + t95; % Z(0) 197 | out(1,1) = out(1,1) + t103; % K(-1) 198 | out(2,3) = out(2,3) + t1; % Z(0) 199 | out(2,3) = out(2,3) + t436; % Z(-1) 200 | out(3,4) = out(3,4) + t438; % Y(0) 201 | out(3,6) = out(3,6) + t1; % W(0) 202 | out(3,8) = out(3,8) + t450; % L(0) 203 | out(3,1) = out(3,1) + t455; % K(-1) 204 | out(4,4) = out(4,4) + t1116; % Y(0) 205 | out(4,8) = out(4,8) + t1121; % L(0) 206 | out(4,7) = out(4,7) + t1; % r(0) 207 | out(4,1) = out(4,1) + t1131; % K(-1) 208 | out(5,4) = out(5,4) + t437; % Y(0) 209 | out(5,6) = out(5,6) + t1679; % W(0) 210 | out(5,8) = out(5,8) + t1681; % L(0) 211 | out(5,9) = out(5,9) + t1; % zero_profit(0) 212 | out(5,7) = out(5,7) + t1683; % r(0) 213 | out(5,1) = out(5,1) + t1685; % K(-1) 214 | out(6,5) = out(6,5) + t1; % I(0) 215 | out(6,6) = out(6,6) + t1678; % W(0) 216 | out(6,8) = out(6,8) + t1680; % L(0) 217 | out(6,2) = out(6,2) + t1; % C(0) 218 | out(6,7) = out(6,7) + t1682; % r(0) 219 | out(6,1) = out(6,1) + t1684; % K(-1) 220 | out(7,5) = out(7,5) + t437; % I(0) 221 | out(7,1) = out(7,1) + t1; % K(0) 222 | out(7,1) = out(7,1) + t1687; % K(-1) 223 | out(8,2) = out(8,2) + t1695; % C(1) 224 | out(8,7) = out(8,7) + t1696; % r(1) 225 | out(8,2) = out(8,2) + t1700; % C(0) 226 | out(9,6) = out(9,6) + t1765; % W(0) 227 | out(9,8) = out(9,8) + t1772; % L(0) 228 | out(9,2) = out(9,2) + t1774; % C(0) 229 | -------------------------------------------------------------------------------- /labs/lab-4/rbc_benchmark_f.m: -------------------------------------------------------------------------------- 1 | % Usage: 2 | % out = rbc_benchmark_f(params, y) 3 | % where 4 | % out is a (9,1) column vector of the residuals 5 | % of the static system 6 | % params is a (12,1) vector of parameter values 7 | % in the ordering as declared 8 | % y is a (9,1) vector of endogenous variables 9 | % in the ordering as declared 10 | % 11 | % Created by Dynare++ v. 4.3.3 12 | 13 | % params ordering 14 | % ===================== 15 | % b 16 | % alpha 17 | % beta 18 | % delta 19 | % sigma 20 | % theta 21 | % omega 22 | % rho_z 23 | % sigma_z 24 | % KSS 25 | % LSS 26 | % YSS 27 | % 28 | % y ordering 29 | % ===================== 30 | % K 31 | % C 32 | % Z 33 | % Y 34 | % I 35 | % W 36 | % r 37 | % L 38 | % zero_profit 39 | 40 | function out = rbc_benchmark_f(params, y) 41 | if size(y) ~= [9,1] 42 | error('Wrong size of y, must be [9,1]'); 43 | end 44 | if size(params) ~= [12,1] 45 | error('Wrong size of params, must be [12,1]'); 46 | end 47 | 48 | % hardwired constants 49 | a0 = 0; 50 | a1 = 1; 51 | a2 = NaN; 52 | a3 = 1.1283792; 53 | % numerical constants 54 | a10 = 1; 55 | % parameter values 56 | a73 = params(1); % b 57 | a7 = params(2); % alpha 58 | a64 = params(3); % beta 59 | a56 = params(4); % delta 60 | a9 = params(5); % sigma 61 | a61 = params(6); % theta 62 | a75 = params(7); % omega 63 | a24 = params(8); % rho_z 64 | % sigma_z not used in the model 65 | % KSS not used in the model 66 | % LSS not used in the model 67 | % YSS not used in the model 68 | % exogenous variables to zeros 69 | a27 = 0.0; % eps_z 70 | % endogenous variables to y 71 | a8 = y(1); % K 72 | a55 = y(1); % K 73 | a50 = y(2); % C 74 | a65 = y(2); % C 75 | a25 = y(3); % Z 76 | a5 = y(3); % Z 77 | a4 = y(4); % Y 78 | a51 = y(5); % I 79 | a30 = y(6); % W 80 | a38 = y(7); % r 81 | a68 = y(7); % r 82 | a16 = y(8); % L 83 | a44 = y(9); % zero_profit 84 | 85 | t6 = exp(a5); 86 | t11 = a9 - a10; 87 | t12 = t11 / a9; 88 | t13 = a8 ^ t12; 89 | t14 = a7 * t13; 90 | t15 = a10 - a7; 91 | t17 = a16 ^ t12; 92 | t18 = t15 * t17; 93 | t19 = t14 + t18; 94 | t20 = a9 / t11; 95 | t21 = t19 ^ t20; 96 | t22 = t6 * t21; 97 | t23 = a4 - t22; 98 | t26 = a24 * a25; 99 | t28 = t26 + a27; 100 | t29 = a5 - t28; 101 | t31 = -(a10); 102 | t32 = t31 / a9; 103 | t33 = a16 ^ t32; 104 | t34 = t15 * t33; 105 | t35 = t34 / t19; 106 | t36 = a4 * t35; 107 | t37 = a30 - t36; 108 | t39 = a8 ^ t32; 109 | t40 = a7 * t39; 110 | t41 = t40 / t19; 111 | t42 = a4 * t41; 112 | t43 = a38 - t42; 113 | t45 = a16 * a30; 114 | t46 = a4 - t45; 115 | t47 = a8 * a38; 116 | t48 = t46 - t47; 117 | t49 = a44 - t48; 118 | t52 = a50 + a51; 119 | t53 = t45 + t47; 120 | t54 = t52 - t53; 121 | t57 = a10 - a56; 122 | t58 = a8 * t57; 123 | t59 = a51 + t58; 124 | t60 = a55 - t59; 125 | t62 = -(a61); 126 | t63 = a50 ^ t62; 127 | t66 = a65 ^ t62; 128 | t67 = a64 * t66; 129 | t69 = a10 + a68; 130 | t70 = t69 - a56; 131 | t71 = t67 * t70; 132 | t72 = t63 - t71; 133 | t74 = a10 - a16; 134 | t76 = -(a75); 135 | t77 = t74 ^ t76; 136 | t78 = a73 * t77; 137 | t79 = a30 * t63; 138 | t80 = t78 - t79; 139 | % setting the output variable 140 | out = zeros(9, 1); 141 | out(1) = t23; 142 | out(2) = t29; 143 | out(3) = t37; 144 | out(4) = t43; 145 | out(5) = t49; 146 | out(6) = t54; 147 | out(7) = t60; 148 | out(8) = t72; 149 | out(9) = t80; 150 | -------------------------------------------------------------------------------- /labs/lab-4/rbc_benchmark_ff.m: -------------------------------------------------------------------------------- 1 | % Usage: 2 | % out = rbc_benchmark_ff(params, y) 3 | % where 4 | % out is a (9,9) matrix of the first order 5 | % derivatives of the static system residuals 6 | % columns correspond to endo variables in 7 | % the ordering as declared 8 | % params is a (12,1) vector of parameter values 9 | % in the ordering as declared 10 | % y is a (9,1) vector of endogenous variables 11 | % in the ordering as declared 12 | % 13 | % Created by Dynare++ v. 4.3.3 14 | 15 | % params ordering 16 | % ===================== 17 | % b 18 | % alpha 19 | % beta 20 | % delta 21 | % sigma 22 | % theta 23 | % omega 24 | % rho_z 25 | % sigma_z 26 | % KSS 27 | % LSS 28 | % YSS 29 | % 30 | % y ordering 31 | % ===================== 32 | % K 33 | % C 34 | % Z 35 | % Y 36 | % I 37 | % W 38 | % r 39 | % L 40 | % zero_profit 41 | 42 | function out = rbc_benchmark_ff(params, y) 43 | if size(y) ~= [9,1] 44 | error('Wrong size of y, must be [9,1]'); 45 | end 46 | if size(params) ~= [12,1] 47 | error('Wrong size of params, must be [12,1]'); 48 | end 49 | 50 | % hardwired constants 51 | a0 = 0; 52 | a1 = 1; 53 | a2 = NaN; 54 | a3 = 1.1283792; 55 | % numerical constants 56 | a10 = 1; 57 | % parameter values 58 | a73 = params(1); % b 59 | a7 = params(2); % alpha 60 | a64 = params(3); % beta 61 | a56 = params(4); % delta 62 | a9 = params(5); % sigma 63 | a61 = params(6); % theta 64 | a75 = params(7); % omega 65 | a24 = params(8); % rho_z 66 | % sigma_z not used in the model 67 | % KSS not used in the model 68 | % LSS not used in the model 69 | % YSS not used in the model 70 | % exogenous variables to zeros 71 | a27 = 0.0; % eps_z 72 | % endogenous variables to y 73 | a8 = y(1); % K 74 | a55 = y(1); % K 75 | a50 = y(2); % C 76 | a65 = y(2); % C 77 | a25 = y(3); % Z 78 | a5 = y(3); % Z 79 | a4 = y(4); % Y 80 | a51 = y(5); % I 81 | a30 = y(6); % W 82 | a38 = y(7); % r 83 | a68 = y(7); % r 84 | a16 = y(8); % L 85 | a44 = y(9); % zero_profit 86 | 87 | t1 = a1; 88 | t6 = exp(a5); 89 | t15 = a10 - a7; 90 | t11 = a9 - a10; 91 | t12 = t11 / a9; 92 | t83 = t12 - a1; 93 | t84 = a16 ^ t83; 94 | t85 = t12 * t84; 95 | t86 = t15 * t85; 96 | t20 = a9 / t11; 97 | t13 = a8 ^ t12; 98 | t14 = a7 * t13; 99 | t17 = a16 ^ t12; 100 | t18 = t15 * t17; 101 | t19 = t14 + t18; 102 | t89 = t20 - a1; 103 | t90 = t19 ^ t89; 104 | t91 = t20 * t90; 105 | t92 = t86 * t91; 106 | t93 = t6 * t92; 107 | t94 = -(t93); 108 | t21 = t19 ^ t20; 109 | t22 = t6 * t21; 110 | t95 = -(t22); 111 | t98 = a8 ^ t83; 112 | t99 = t12 * t98; 113 | t100 = a7 * t99; 114 | t101 = t91 * t100; 115 | t102 = t6 * t101; 116 | t103 = -(t102); 117 | t104 = -(a24); 118 | t31 = -(a10); 119 | t32 = t31 / a9; 120 | t33 = a16 ^ t32; 121 | t34 = t15 * t33; 122 | t35 = t34 / t19; 123 | t106 = -(t35); 124 | t108 = t32 - a1; 125 | t109 = a16 ^ t108; 126 | t110 = t32 * t109; 127 | t111 = t15 * t110; 128 | t113 = t19 * t111; 129 | t112 = t34 * t86; 130 | t114 = t113 - t112; 131 | t115 = t19 * t19; 132 | t116 = t114 / t115; 133 | t117 = a4 * t116; 134 | t118 = -(t117); 135 | t119 = t34 * t100; 136 | t120 = -(t119); 137 | t121 = t120 / t115; 138 | t122 = a4 * t121; 139 | t123 = -(t122); 140 | t39 = a8 ^ t32; 141 | t40 = a7 * t39; 142 | t41 = t40 / t19; 143 | t124 = -(t41); 144 | t125 = t40 * t86; 145 | t126 = -(t125); 146 | t127 = t126 / t115; 147 | t128 = a4 * t127; 148 | t129 = -(t128); 149 | t131 = a8 ^ t108; 150 | t132 = t32 * t131; 151 | t133 = a7 * t132; 152 | t135 = t19 * t133; 153 | t134 = t40 * t100; 154 | t136 = t135 - t134; 155 | t137 = t136 / t115; 156 | t138 = a4 * t137; 157 | t139 = -(t138); 158 | t105 = -(a1); 159 | t140 = -(a16); 160 | t141 = -(t140); 161 | t142 = -(a30); 162 | t143 = -(t142); 163 | t144 = -(a8); 164 | t145 = -(t144); 165 | t146 = -(a38); 166 | t147 = -(t146); 167 | t57 = a10 - a56; 168 | t148 = -(t57); 169 | t69 = a10 + a68; 170 | t70 = t69 - a56; 171 | t62 = -(a61); 172 | t151 = t62 - a1; 173 | t152 = a65 ^ t151; 174 | t153 = t62 * t152; 175 | t154 = a64 * t153; 176 | t155 = t70 * t154; 177 | t156 = -(t155); 178 | t66 = a65 ^ t62; 179 | t67 = a64 * t66; 180 | t157 = -(t67); 181 | t160 = a50 ^ t151; 182 | t161 = t62 * t160; 183 | t63 = a50 ^ t62; 184 | t162 = -(t63); 185 | t76 = -(a75); 186 | t74 = a10 - a16; 187 | t165 = t76 - a1; 188 | t166 = t74 ^ t165; 189 | t167 = t76 * t166; 190 | t168 = t105 * t167; 191 | t169 = a73 * t168; 192 | t170 = a30 * t161; 193 | t171 = -(t170); 194 | % setting the output variable 195 | out = zeros(9, 9); 196 | out(1,4) = out(1,4) + t1; % Y(0) 197 | out(1,8) = out(1,8) + t94; % L(0) 198 | out(1,3) = out(1,3) + t95; % Z(0) 199 | out(1,1) = out(1,1) + t103; % K(-1) 200 | out(2,3) = out(2,3) + t1; % Z(0) 201 | out(2,3) = out(2,3) + t104; % Z(-1) 202 | out(3,4) = out(3,4) + t106; % Y(0) 203 | out(3,6) = out(3,6) + t1; % W(0) 204 | out(3,8) = out(3,8) + t118; % L(0) 205 | out(3,1) = out(3,1) + t123; % K(-1) 206 | out(4,4) = out(4,4) + t124; % Y(0) 207 | out(4,8) = out(4,8) + t129; % L(0) 208 | out(4,7) = out(4,7) + t1; % r(0) 209 | out(4,1) = out(4,1) + t139; % K(-1) 210 | out(5,4) = out(5,4) + t105; % Y(0) 211 | out(5,6) = out(5,6) + t141; % W(0) 212 | out(5,8) = out(5,8) + t143; % L(0) 213 | out(5,9) = out(5,9) + t1; % zero_profit(0) 214 | out(5,7) = out(5,7) + t145; % r(0) 215 | out(5,1) = out(5,1) + t147; % K(-1) 216 | out(6,5) = out(6,5) + t1; % I(0) 217 | out(6,6) = out(6,6) + t140; % W(0) 218 | out(6,8) = out(6,8) + t142; % L(0) 219 | out(6,2) = out(6,2) + t1; % C(0) 220 | out(6,7) = out(6,7) + t144; % r(0) 221 | out(6,1) = out(6,1) + t146; % K(-1) 222 | out(7,5) = out(7,5) + t105; % I(0) 223 | out(7,1) = out(7,1) + t1; % K(0) 224 | out(7,1) = out(7,1) + t148; % K(-1) 225 | out(8,2) = out(8,2) + t156; % C(1) 226 | out(8,7) = out(8,7) + t157; % r(1) 227 | out(8,2) = out(8,2) + t161; % C(0) 228 | out(9,6) = out(9,6) + t162; % W(0) 229 | out(9,8) = out(9,8) + t169; % L(0) 230 | out(9,2) = out(9,2) + t171; % C(0) 231 | -------------------------------------------------------------------------------- /labs/lab-4/rbc_example.mod: -------------------------------------------------------------------------------- 1 | ////////// Declare variables ////////// 2 | 3 | /* ///// Endogenous variables ///// 4 | 5 | K: capital 6 | C: consumption 7 | Z: productivity 8 | Y: output 9 | I: investment 10 | W: real wage 11 | r: net interest rate 12 | L: labor supply 13 | zero_profit: zero profit condition 14 | 15 | */ 16 | var K, C, Z, Y, I, W, r, L, zero_profit; 17 | 18 | ///// Exogenous variables ///// 19 | 20 | // eps_z: productivity shock 21 | varexo eps_z; 22 | 23 | ////////// Declare parameters ////////// 24 | parameters b, alpha, beta, delta, sigma, theta, omega, rho_z, KSS, LSS, YSS; 25 | 26 | // discount factor 27 | beta = 0.9896; 28 | 29 | // coefficient of relative risk aversion 30 | theta = 2.5; 31 | 32 | // inverse elasticity of substitution for leisure 33 | omega = 1.5; 34 | 35 | // weight for leisure in utility 36 | b = 2.0; 37 | 38 | // elasticity of substitution between capital and labor 39 | sigma = 0.75; 40 | 41 | // relative weight of capital in production 42 | alpha = 0.40; 43 | 44 | // depreciation rate of capital 45 | delta = 0.025; 46 | 47 | // persistence of productivity process 48 | rho_z = 0.95; 49 | 50 | // steady state labor supply (computed for theta=omega=delta=sigma=1) 51 | LSS = (1 - alpha) / (1 - alpha + b * (1 - alpha * beta)); 52 | 53 | // steady state capital (computed for theta=omega=delta=sigma=1) 54 | KSS = (alpha * beta)^(1 / (1 - alpha)) * LSS; 55 | 56 | // steady state output (computed for theta=omega=delta=sigma=1) 57 | YSS = KSS^alpha * LSS^(1 - alpha); 58 | 59 | ////////// Model equations ////////// 60 | 61 | model; 62 | 63 | // production (i.e., equation 3.1) 64 | Y = exp(Z) * (alpha * K(-1)^((sigma - 1) / sigma) + (1 - alpha) * L^((sigma - 1) / sigma))^(sigma / (sigma - 1)); 65 | 66 | // productivity process (i.e., equation 3.2) 67 | Z = rho_z * Z(-1) + eps_z; 68 | 69 | // real wage (i.e., equation 3.3) 70 | W = (((1 - alpha) * L^(-1 / sigma)) / (alpha * K(-1)^((sigma - 1) / sigma) + (1 - alpha) * L^((sigma - 1) / sigma))) * Y; 71 | 72 | // rental rate (i.e., equation 3.4) 73 | r = ((alpha *K(-1)^(-1 / sigma)) / (alpha * K(-1)^((sigma - 1) / sigma) + (1 - alpha) * L^((sigma - 1) / sigma))) * Y; 74 | 75 | // check that zero profit condition holds (i.e., equation 3.5) 76 | zero_profit = Y - W * L - r * K(-1); 77 | 78 | // household budget constraint (i.e., equation 3.6a) 79 | C + I = W * L + r * K(-1); 80 | 81 | // household evolution of capital (i.e., equation 3.6b) 82 | K = (1 - delta) * K(-1) + I; 83 | 84 | // consumption Euler equation (i.e., equation 3.7) 85 | C^(-theta) = beta * C(+1)^(-theta) * (1 + r(+1) - delta); 86 | 87 | // intra-temporal consumption/labor trade-off (i.e., equation 3.8) 88 | b * (1 - L)^(-omega) = W * C^(-theta); 89 | 90 | end; 91 | 92 | ////////// Initial values for computing steady state ////////// 93 | 94 | initval; 95 | K = KSS; 96 | L = LSS; 97 | Y = YSS; 98 | C = YSS - KSS; 99 | Z = 0.0; 100 | I = KSS; 101 | W = (1 - alpha) * (YSS / LSS); 102 | r = (1 / beta); 103 | zero_profit = 0.0; 104 | end; 105 | 106 | ////////// Variance covariance matrix ////////// 107 | vcov = [0.007]; 108 | -------------------------------------------------------------------------------- /labs/lab-5/Untitled0.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "metadata": { 3 | "name": "" 4 | }, 5 | "nbformat": 3, 6 | "nbformat_minor": 0, 7 | "worksheets": [ 8 | { 9 | "cells": [ 10 | { 11 | "cell_type": "code", 12 | "collapsed": false, 13 | "input": [ 14 | "720 * 40" 15 | ], 16 | "language": "python", 17 | "metadata": {}, 18 | "outputs": [ 19 | { 20 | "metadata": {}, 21 | "output_type": "pyout", 22 | "prompt_number": 4, 23 | "text": [ 24 | "28800" 25 | ] 26 | } 27 | ], 28 | "prompt_number": 4 29 | }, 30 | { 31 | "cell_type": "code", 32 | "collapsed": false, 33 | "input": [], 34 | "language": "python", 35 | "metadata": {}, 36 | "outputs": [] 37 | } 38 | ], 39 | "metadata": {} 40 | } 41 | ] 42 | } --------------------------------------------------------------------------------