%% Muth Model with Adaptive and Rational Expectations
%
% Ben J. Heijdra, Foundations of Modern Macroeconomics, Third Ed.
% Oxford University Press
%
% Chapter 5
%
% Ben J. Heijdra
% Groningen, June 15, 2015

clear
clf
clc
close all

% Control the seed number for the random number generator so that the same 
% pictures are obtained each time
rng(1);

% Structural parameters
a_0    =  3;
a_1    =  1;
b_0    =  1;
b_1    =  1;
sigma  =  0.1;
lambda =  0.8;

% Deterministic steady-state values
P_bar = (a_0 - b_0) / (a_1 + b_1);
Q_bar = a_0 - a_1 * P_bar;

% Draw a 101 x 1 vector of random variables: N(0,sigma^2)
U     = normrnd(0,sigma,101,1);  
Ben   = U;
time  = linspace(1,100,100)

% Compute the market clearing price and quantities traded under REH
P_REH = P_bar - (1/a_1) * U;
Q_REH = a_0 - a_1 * P_REH;

% Compute the market clearing price and quantities traded under AEH

P_AEH     = zeros(101,1);
P_AEH(1)  = P_bar;
Pe_AEH    = zeros(101,1);
Pe_AEW(1) = P_bar;

for i = 1:100
    P_AEH(i+1)  = lambda*(a_0-b_0)/a_1 + (1  - lambda*(a_1+b_1)/a_1) ...
        * P_AEH(i) - (1/a_1)* (U(i+1) - (1-lambda)*U(i)) ;
    Pe_AEH(i+1) = lambda * P_AEH(i) + (1-lambda) * Pe_AEH(i) ;  
end

figure(1)
hold on;
plot(time,P_REH(1:100),'-','LineWidth',2)
box off;
plot([1 100],[P_bar P_bar],'--','LineWidth',2)
xlim([1 100]);
%hline = refline([P_bar P_bar]);
legend('Actual price','Expected price','Location','SouthEast')
hold off;
xlabel('time (t)')
ylabel('expected and actual price')
print('-deps2','-loose','F05_04')
pause(1)

figure(2)
hold on;
plot(time,P_AEH(2:101),'-','LineWidth',2)
box off;
plot(time,Pe_AEH(2:101),'--','LineWidth',2)
plot([1 100],[P_bar P_bar],':','LineWidth',1)
xlim([1 100]);
%hline = refline([P_bar P_bar]);
legend('Actual price','Expected price','Location','SouthEast')
hold off;
xlabel('time (t)')
ylabel('expected and actual price')
print('-deps2','-loose','F05_05')
pause(1)
