ps2 Macro Bongioanni TXT
ps2 Macro Bongioanni TXT
ps2 Macro Bongioanni TXT
"""
Created on Mon Feb 7 11:21:04 2022
@author: gbongio
"""
import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns
sns.set_theme(style="whitegrid")
class A(object):
def __init__(self):
print ('init')
self.v = 10
self.z = [2,3,4]
def __copy__(self):
cls = self.__class__
result = cls.__new__(cls)
result.__dict__.update(self.__dict__)
return result
#parameters
alpha = 0.36
f = lambda k: k**alpha
beta = 0.9
delta = 0.025
#ss capital
kstar=((1-beta*(1-delta))/(alpha*beta))**(1/(alpha-1))
#initial guess
vf0 = np.zeros(500)
vf1 = np.zeros(500)
max_k_prime = np.zeros(500)
k = nkk[0]
e=10000000000
iterations=0
#as long as the distance between the two functions is greater than 0.001
start = time.time()
while e > 10**(-3):
iterations+=1
#loop through all values of k
for i in range(0,len(nkk)):
for j in range(0,len(nkk)):
c = f(nkk[i])+(1-delta)*nkk[i]-nkk[j]
if c>0:
temp[j] = np.log(c) + beta * vf0[j]
else:
temp[j]=np.nan
maximum = np.max(temp)
max_k_prime[i]=np.argmax(temp)
vf1[i]=maximum
#check the distance between the old value function and the new one, if small
enough
#we have reached the fixed point
e = np.linalg.norm(vf1 - vf0)/np.linalg.norm(vf0)
#question g
#remember the policy function will contain still values from the grid but only the
#ones that are optimal given a specific value of capital today
pf = np.zeros(500)
max_pf = np.zeros(500)
pf_idx = np.zeros(500)
temp=np.zeros(500)
pf_idx[i] = np.argmax(temp)
pf[i] = nkk[np.argmax(temp)]
plt.title("Policy Function")
plt.xlabel("k")
plt.ylabel("PF")
plt.plot(nkk,pf, label="policy function", color="blue")
plt.plot(np.linspace(4.11,5),np.linspace(4.11,5), label="45 degree line",
color="red",linestyle='dashed')
plt.legend(loc="upper left")
plt.show()
plt.xlabel("k")
plt.ylabel("k'-k")
plt.plot(nkk,pf-nkk, color="blue")
plt.plot(np.linspace(4.1,5),np.linspace(0,0), color="red",linestyle='dashed')
plt.legend(loc="upper right")
plt.show()
#question h
assets = np.zeros(51)
assets[0] = nkk[0]
assets_idx = np.zeros(51)
assets_idx[0] = 1
#for every period
for t in range(0,50):
#recover the k' that achieves the maximum continuation value given the starting
point
#e.g. the index of the k' that maximizes the expression given that the starting
point
#is nkk[0]=4.11 is going to be the 28th element in the grid. We add the value
of the 28th
#element of the pf, which will give us a new k'. Then we go back to the 28th
element
#the pf index list and find out the the best k' is the 52nd in the grid and so
on...
assets_idx[t+1] = pf_idx[int(assets_idx[t])]
assets[t+1] = pf[int(assets_idx[t+1])]
plt.title("Capital Dynamics")
plt.xlabel("time")
plt.ylabel("k")
plt.plot(np.linspace(0,50),np.linspace(4.57,4.57), color="red",linestyle='dashed')
plt.plot(assets, color="blue")