% Monetary Economics. Econ221A. Fall 2006. Homework 2. Anton Cheremukhin
clear all;
close all;
clc;
addpath(genpath('C:/Matlab7/toolbox/KalmanAll'))
% get data
[y] = textread('MA2.txt','%f');
y=y';

%s=1;    m=2;    q1=0.6;     q2=0.3;
%err=s*randn(1,1000);
%y(1)=m+err(1);
%y(2)=m+err(2)+q1*err(1);
%for i=3:1000
%    y(i)=m+err(i)+q1*err(i-1)+q2*err(i-2);
%end
%m1=mean(y);
%y=y-mean(y);

%q1  q2  m  sigma
q0=[0.6, 0.2, 0, 1];
H0=0.0001*eye(4);
crit=0.000001;    nit=1000;
% find likelihood maximizer with csminwel
[fh,x,gh,H1,itct,fcount,retcodeh] = csminwel(@makelike2, q0, H0, [], crit, nit, y)
q1=x(1);    q2=x(2);    m=x(3); sig=x(4);

F = [0 0 0; 1 0 0; 0 1 0];
H = [1 q1 q2];
Q = diag([sig 0 0]);
R = 0;
initx = [y(1)-m;0;0];
initV = 0.00000001*eye(3);
[xfilt, Vfilt, VVfilt, loglik] = kalman_filter(y-m, F, H, Q, R, initx, initV);
L=-loglik;