forecasting - Matlab Kalman Filter Code - Forecast h-steps ahead? -
i have following code forecast variable zhi. far can see result ezhivec(i) given me the t+1 observation.
but want compute h-steps ahead forecasts , absolutely don't know how...
clear all; % state space reprsentation forcasted kalman filter % zhi(t+1) = f*zhi(t) + v(t+1) --> unbobserved varaibles % v~n(0,q) % y(t) = a'*x(t) + h'*zhi(t) + w(t) % w~n(0,r) global y; global x; global hvec; %%---- enter input parameters load hon.txt %filename stock prices load dji.txt %filename index prices n=100; %no. of points consider offset=1; %use 1 daily return or 30 monthly return %------------------------------- datapts=1:offset:(n+1)*offset; dji=dji(datapts); hon=hon(datapts); %hvec=(dji(1:n)-dji(2:n+1))./dji(2:n+1); %index returns process %y=(hon(1:n)-hon(2:n+1))./hon(2:n+1); %index returns process hvec=log(dji(1:n)./dji(2:n+1)); %index returns process y=log(hon(1:n)./hon(2:n+1)); %stock returns process hvec=flipud(hvec); y=flipud(y); x=ones(n,1); param=zeros(5,1); f=0.5; f=-log(1/f-1); param(1)=f; param(2)=0.2; param(3)=1; param(4)=0.2; param(5)=0.5; resultparam=fminsearch(mylikelihoodfn,param) f=resultparam(1) f=1/(1+exp(-f)) q=resultparam(2)^2 a=resultparam(3) r=resultparam(4)^2 betai=resultparam(5) n=size(y,1); p=q; ezhi=0.01; ezhivec=zeros(n,1); ezhivec(1)=ezhi; i=2:n yt=y(i); xt=x(i); h=hvec(i); ezhi = f*ezhi + f*p*h*inv(h'*p*h+r)*(yt-a'*xt-h'*betai-h'*ezhi); p = f*p*f' - f*p*h*inv(h'*p*h+r)*h'*p*f' + q; ezhivec(i)=ezhi; end ezhivec=ezhivec+betai; test=[ezhivec hvec y]; tmp=1:n; subplot(3,1,1); plot(tmp,y,'-'); subplot(3,1,2); plot(tmp,hvec,'-'); subplot(3,1,3); plot(tmp,ezhivec,'-'); %plot(tmp,ezhivec,'-',tmp,hvec,'-',tmp,y,'-'); %plot(tmp,zhi,'-',tmp,ezhivec,'-'); %% ------------------ %test=[zhi y] function ret=mylikelihoodfn(p) global y; global x; global hvec; f=p(1); f=1/(1+exp(-f)); q=p(2)^2; a=p(3); r=p(4)^2; betai=p(5); n=size(y,1); p=q; ezhi=0; ezhivec=zeros(n,1); ezhivec(1)=ezhi; tmpsum=0; tmp1=-(n/2)*log(2*pi); i=2:n yt=y(i); xt=x(i); h=hvec(i); ezhi = f*ezhi + f*p*h*inv(h'*p*h+r)*(yt-a'*xt-h'*betai-h'*ezhi); p = f*p*f' - f*p*h*inv(h'*p*h+r)*h'*p*f' + q; ezhivec(i)=ezhi; tmpmat = h'*p*h + r; tmp2 = -0.5*log(det(tmpmat)); tmpmat2 = yt - a'*xt - h'*betai - h'*ezhi; tmp3=-0.5*tmpmat2'*inv(tmpmat)*tmpmat2; tmpsum=tmp1+tmp2+tmp3; end ret=-tmpsum; end
Comments
Post a Comment