%Econ 202C Macro. Homework#2. Problem1 Anton Cheremukhin
close all;  clear all;  clc;
% Parameters %
T=70;          %number of periods for transition%
teta=7/20;     %capital share%
fi=65/41;      %elasticity of disutility of labor  1.5853
delta=123/680; %depreciation rate%     0.1810=123/680
beta=203/240;  %discount rate%         0.845=203/240
gamma0=203/200; %scale parameter in production function% 
gamma=gamma0;

%old steady-state
u=teta/(gamma/beta-1+delta);   v=gamma-1+delta;
kk1=(u^(1/(1-teta)))/((fi/(1-teta))*(1/(u*v)-1)+1/(u*v));
kc1=kk1*(1/(u*v)-1);

%new s-s
gamma=212/200; %scale parameter in production function% 
u=teta/(gamma/beta-1+delta);   v=gamma-1+delta;
kkT=(u^(1/(1-teta)))/((fi/(1-teta))*(1/(u*v)-1)+1/(u*v));
kcT=kkT*(1/(u*v)-1);

%initial guess
%kguess=ones(T,1)*[kcT, kkT];
kguess=[kc1+(kcT-kc1)*[0:1:T-1]'/(T-1), kk1+(kkT-kk1)*[0:1:T-1]'/(T-1)];
a=1+fi/(1-teta);    b=1-delta;
%solve
options = optimset('Display','iter','LargeScale','on','Jacobian','off','MaxFunEvals',100000000,'TolX',0.0000000000001,'TolFun',0.0000000000001,'MaxIter',1000);
[kpath,G]=fsolve(@optpath2,kguess,options,a,b,gamma,beta,teta,kc1,kk1,kcT,kkT,T);

%results
%T=70;
kc=kpath(1:T,1);  kk=kpath(1:T,2);
lc=1./(a+kk./kc);   lk=kk.*lc./kc;  c=(kc.^teta).*(lc.^(1-teta));
ic=gamma*kc(2:T)-b*kc(1:T-1);   ic(T)=ic(T-1);
ik=gamma*kk(2:T)-b*kk(1:T-1);   ik(T)=ik(T-1);
p=(c.*kk)./(kc.*(ik+ic));
figure(1)
plot(1:T,kc,1:T,kk,1:T,kc1,1:T,kcT,1:T,kk1,1:T,kkT,...
               'LineWidth',2);    
title('capital');   legend('kc','kk');  xlabel('periods');
figure(2)
plot(1:T,lc,1:T,lk,...
               'LineWidth',2);
title('labor');     legend('lc','lk');  xlabel('periods');
figure(3)
plot(1:T,ic,1:T,ik,1:T,c,...
               'LineWidth',2);
title('investment and consumption'); legend('ic','ik','c'); xlabel('periods');
figure(4)
plot(1:T,p,...
               'LineWidth',2);    
title('price');     legend('p');    xlabel('periods');

%intuition
L=7;
kc=[ones(L,1)*kc(1); kc(1:T)];  
kk=[ones(L,1)*kk(1); kk(1:T)];
lk=[ones(L,1)*lk(1); lk(1:T)];
lc=[ones(L,1)*lc(1); lc(1:T)];
c=[ones(L,1)*c(1); c(1:T)];
ik=[ones(L,1)*ik(1); ik(1:T)];
ic=[ones(L,1)*ic(1); ic(1:T)];

trend=[gamma0.^[1-L:0] gamma.^[1:T]];
gamma1=(gamma0^(1-teta))*(gamma^teta);
trendc=[gamma0.^[1-L:0] gamma1.^[1:T]];

kc1=log(kc.*trend');  
kk1=log(kk.*trend');
lk1=lk; lc1=lc;
c1=log(c.*trendc');
ik1=log(ik.*trend');
ic1=log(ic.*trend');

T=20;
figure(5)
plot(1:T,kc1(1:T),1:T,kk1(1:T),...
               'LineWidth',2);    
title('log undetrended capital');   legend('kc','kk');  xlabel('periods');
figure(6)
plot(1:T,ic1(1:T),1:T,ik1(1:T),1:T,c1(1:T),...
               'LineWidth',2);
title('log undetrended investment and consumption'); legend('ic','ik','c'); xlabel('periods');
