for k in range(n // 2): xii = xi[(2 * k):(2 * k + 3)] xiii = linspace(xii[0], xii[2], 125) p = fitquad(xii) plt.fill_between(xiii, p(xiii), color='yellow') if k == 0: plt.plot(xiii, p(xiii), 'r--', label=r'$\tilde{f}_{%d}(x)$' % (n + 1)) else: plt.plot(xiii, p(xiii), 'r--') plt.vlines(xi, 0, f(xi), 'k', linestyle=':') plt.hlines(0, xmin - 0.1, xmax + 0.1, 'k', linewidth=2) plt.xlim(xmin - 0.1, xmax + 0.1) xtl = ['$x_{%d}$' % i for i in range(n + 1)] xtl[0] += '=a' xtl[n] += '=b' plt.xticks(xi, xtl) plt.yticks([0], ['0']) plt.legend() return fig # In[6]: figs = [plot_simp(n) for n in [2, 4, 8]] demo.savefig(figs)
n = 1000 x = np.linspace(a, b, n) r = resid(F.c) # ### Plot function inverse # In[6]: fig1 = demo.figure('Implicit Function', 'x', 'f(x)') plt.plot(x, F(x)) # ### Plot residual # In[7]: fig2 = demo.figure('Functional Equation Residual', 'x', 'Residual') plt.hlines(0, a, b, 'k', '--') plt.plot(x, r) # In[8]: demo.savefig([fig1, fig2])
B = BasisChebyshev(n,a,b) basisplot(x, B.Phi(x).T,'Chebychev Polynomial Basis Functions on [0,1]') nodeplot(B.nodes,'Chebychev Nodes on [0,1]') # ### % Plot linear spline basis functions and nodes # In[8]: L = BasisSpline(n,a,b,k=1) basisplot(x, L.Phi(x).T.toarray(),'Linear Spline Basis Functions on [0,1]') nodeplot(L.nodes,'Linear Spline Standard Nodes on [0,1]') # ### % Plot cubic spline basis functions and nodes # In[9]: C = BasisSpline(n,a,b,k=3) basisplot(x, C.Phi(x).T.toarray(),'Cubic Spline Basis Functions on [0,1]') nodeplot(C.nodes,'Cubic Spline Standard Nodes on [0,1]') # In[10]: demo.savefig(figures)
v += w[k] * np.maximum(K - np.exp(pnext), delta * Value(pnext)) Value[:] = v pcrit[t + 1] = f.broyden(pcrit[t]) # ### Print Critical Exercise Price 300 Periods to Expiration # In[9]: print('Critical Price = %5.2f' % np.exp(pcrit[-1])) # ### Plot Critical Exercise Prices # In[10]: fig1 = demo.figure('American Put Option Optimal Exercise Boundary', 'Periods Remaining Until Expiration', 'Exercise Price') plt.plot(np.exp(pcrit)) # In[ ]: demo.savefig([fig1])
results.set_index(['Integral', 'Nodes n'], inplace=True) results # ## Plot the functions # In[7]: a, b, n = -1, 1, 301 x = np.linspace(a, b, n) plt.figure(figsize=[10,4]) demo.subplot(1, 2, 1, '$e^{-x}$','','',[a,b],[0,f(a)]) plt.plot(x, f(x), linewidth=3) plt.xticks([-1,0,1]) plt.yticks([0]) demo.subplot(1, 2, 2, '$\sqrt{|x|}$','','',[a,b],[0,g(a)]) plt.plot(x, g(x), linewidth=3) plt.xticks([-1,0,1]) plt.yticks([0]) # In[8]: results.to_latex('figures/demqua03.tex', escape=False, float_format='%.1f') demo.savefig([plt.gcf()])
print('\nErgodic Standard Deviations') print(ff.format('Wage', data['wage'].std())) print(ff.format('Employment', (data['i'] == 'employed').std())) # ### Plot Expected Discrete State Path # In[15]: data.head() # In[16]: data['ii'] = data['i'] == 'employed' fig3 = demo.figure('Probability of Employment', 'Period', 'Probability') plt.plot(data[['ii', 'time']].groupby('time').mean()) # ### Plot Simulated and Expected Continuous State Path # In[17]: subdata = data[data['_rep'].isin(range(3))] fig4 = demo.figure('Simulated and Expected Wage', 'Period', 'Wage') plt.plot(subdata.pivot('time', '_rep', 'wage')) plt.plot(data[['time', 'wage']].groupby('time').mean(), 'k--', label='mean') # In[18]: demo.savefig([fig1, fig2, fig3, fig4])
# Next, for each possible price shock, we compute next period log-price by adding the shock to current log-prices (the nodes of the Value object). Then, we use each next-period price to compute the expected value of an option with one-period to maturity (save the values in ```v```). We update the value function to reflect the new time-to-maturity and use ```broyden``` to solve for the critical value. We repeat this procedure until we reach the $T=300$ horizon. # In[8]: for t in range(T): v = np.zeros((1, n)) for k in range(m): pnext = Value.nodes + e[k] v += w[k] * np.maximum(K - np.exp(pnext), delta * Value(pnext)) Value[:] = v pcrit[t + 1] = f.broyden(pcrit[t]) # ### Print Critical Exercise Price 300 Periods to Expiration # In[9]: print('Critical Price = %5.2f' % np.exp(pcrit[-1])) # ### Plot Critical Exercise Prices # In[10]: fig1 = demo.figure('American Put Option Optimal Exercise Boundary', 'Periods Remaining Until Expiration', 'Exercise Price') plt.plot(np.exp(pcrit)) # In[ ]: demo.savefig([fig1])
plt.plot(x, f(x), linewidth=3, label=r'$f(x)$') for k in range(n//2): xii = xi[(2*k):(2*k+3)] xiii = linspace(xii[0], xii[2], 125) p = fitquad(xii) plt.fill_between(xiii, p(xiii), color='yellow') if k==0: plt.plot(xiii, p(xiii),'r--', label=r'$\tilde{f}_{%d}(x)$' % (n+1)) else: plt.plot(xiii, p(xiii),'r--') plt.vlines(xi, 0, f(xi),'k', linestyle=':') plt.hlines(0,xmin-0.1, xmax+0.1,'k',linewidth=2) plt.xlim(xmin-0.1, xmax+0.1) xtl = ['$x_{%d}$' % i for i in range(n+1)] xtl[0] += '=a' xtl[n] += '=b' plt.xticks(xi, xtl) plt.yticks([0],['0']) plt.legend() return fig # In[6]: figs = [plot_simp(n) for n in [2, 4, 8]] demo.savefig(figs)
data.head() # In[18]: subdata = data[data['_rep'].isin(range(3))] # In[19]: fig3 = demo.figure('Simulated and Expected Price', 'Period','Net Unit Profit') demo.qplot('time','unit profit','_rep',subdata) plt.plot(data[['time','unit profit']].groupby('time').mean(),'k--',label='mean') plt.legend() # ### Plot Expected Discrete State Path # In[20]: fig4 = demo.figure('Expected Machine Age', 'Period','Age') demo.qplot('time','age','_rep',subdata) plt.plot(data[['time','age']].groupby('time').mean(),'k--',label='mean') plt.legend() demo.savefig([fig1,fig2,fig3,fig4])
Phi = np.array([x**j for j in np.arange(n)]) basisplot(x, Phi, 'Monomial Basis Functions on [0,1]') # ### % Plot Chebychev basis functions and nodes # In[7]: B = BasisChebyshev(n, a, b) basisplot(x, B.Phi(x).T, 'Chebychev Polynomial Basis Functions on [0,1]') nodeplot(B.nodes, 'Chebychev Nodes on [0,1]') # ### % Plot linear spline basis functions and nodes # In[8]: L = BasisSpline(n, a, b, k=1) basisplot(x, L.Phi(x).T.toarray(), 'Linear Spline Basis Functions on [0,1]') nodeplot(L.nodes, 'Linear Spline Standard Nodes on [0,1]') # ### % Plot cubic spline basis functions and nodes # In[9]: C = BasisSpline(n, a, b, k=3) basisplot(x, C.Phi(x).T.toarray(), 'Cubic Spline Basis Functions on [0,1]') nodeplot(C.nodes, 'Cubic Spline Standard Nodes on [0,1]') # In[10]: demo.savefig(figures)
# ## Two-sided finite difference derivative # In[5]: d2 = deriv_error(x - h, x + h) e2 = np.log10(eps**(1 / 3)) # ## Plot finite difference derivatives # In[6]: ylim = [-15, 5] xlim = [-15, 0] lcolor = [z['color'] for z in plt.rcParams['axes.prop_cycle']] demo.figure('Error in Numerical Derivatives', '$\log_{10}(h)$', '$\log_{10}$ Approximation Error', xlim, ylim) plt.plot(c, d1, label='One-Sided') plt.plot(c, d2, label='Two-Sided') plt.vlines([e1, e2], *ylim, lcolor, linestyle=':') plt.xticks(np.arange(-15, 5, 5)) plt.yticks(np.arange(-15, 10, 5)) demo.annotate(e1, 2, '$\sqrt{\epsilon}$', color=lcolor[0], ms=0) demo.annotate(e2, 2, '$\sqrt[3]{\epsilon}$', color=lcolor[1], ms=0) plt.legend(loc='lower left') # In[7]: demo.savefig([plt.gcf()])
# ### Plot Residuals # In[13]: S['resid2'] = 100*S.resid / S.value fig2 = demo.figure('Bellman Equation Residual','','Percent Residual') S['resid2'].plot(ax=plt.gca()) plt.hlines(0,0,smax,'k') # ### Simulation # # The path followed by the biomass is computed by the ```simulate()``` method. Here we simulate 32 periods starting with a biomass level $s_0 = 0$. # In[14]: H = model.simulate(32, 0.0) fig3 = demo.figure('Timber harvesting simulation','Period','Biomass') H['biomass'].plot(ax=plt.gca()) # In[15]: demo.savefig([fig1, fig2, fig3])