Kalman filter question
Show older comments
Hello,
I am modeling the influence of systemic risk on a portfolio formed of equity indices. In the first case I am considering that stock returns are following a pure-diffusion process and every return is influenced by a marked-wide risk factor and k region-specific factors.(every international equity index belongs to a country and each country belongs to a region and there are k regions). In order to estimate the expected returns and sensitivities towards this risk I am performing a Kalman filter. This are the equations: x(t+1) = b+F*x(t) + e(t), e(t) ~ N(0,S); z(t) = a + A*x(t) + w(t), w(t)~ N(0,W) x k+1xT represents the matrix containing the brownian motion increments F-k+1xk+1; Z-nxT contains the observed returns of indices
I have tried to implement a code,but I only get 0 values or Nan for all arrays. Is definitely something wrong with the way I initialized the variables: function [xfilt, Vfilt, Vmfilt, loglik] = kalmanFilter( Z, A, W, F, S, a, b) T = size(Z,2); n = size(Z,1); k=3 xfilt = ones( k, T); Vfilt = zeros( k, k, T); Vmfilt = zeros( k, k, T); V=zeros(k,k,T) Vm=zeros(k,k,T) xhat=ones(k,T) xhatm=ones(k,T) if n~=size(A,1) error('Dimension error - A & Z must agree.'); end
if (n~=size(W,1) n~=size(W,2)) error('Dimension error - W is not valid covariance matrix.'); end
if (k~=size(F,2)) error('Dimension error - F not square.'); end
if (k~=size(A,2)) error('Dimension error - F & A do not agree.'); end
if (k~=size(S,1) k~=size(S,2)) error('Dimension error - S is not valid.'); end
if nargin < 6, a=0; else a=zeros(n,T); end if nargin < 7, b=0; else b= ones(k,T); end
% Initialize log-likelihood loglik = 0;
for i=1:T % Time update xhatm = F*xhat + b; Vm(:,:,i) = F*V(:,:,i)*F'+ S; end % Correction H = A*Vm(:,:,i)*A' + W; K = Vm(:,:,i) * A'*inv(H); xhat= xhatm+ K*(Z - a - A*xhatm); V= (eye(k) - K*A)*Vm(:,:,i)*(eye(k) - K*A)'; xfilt(:,i) = xhat(:,i); Vfilt = V; Vmfilt(:,:,i) = Vm(:,:,i); % Update log likelihood loglik = loglik -(n/2)*log(2*pi) - .5 * log( abs(det(H)) ) -.5*(( Z - a - A*xhatm )'*inv(H)*( Z - a - A*xhatm )); end
A call this funtion from another.m file: load DAT1.dat Z=DAT1 T = size(Z,2); n = size(Z,1); k = 3; xfilt = ones( k, T); Vfilt = zeros( k, k, T); Vmfilt = zeros( k, k, T); A=eye(n,k) W=zeros(n,n) F=zeros(k,k) S=zeros(k,k) a=zeros(n,T) b=ones(k,T); [xfilt, Vfilt, Vmfilt, loglik] = kalmanFilter( Z, A, W, F, S, a, b)
Could you please help me, any suggestions will be greatly appreciated?
Thank you in advance, Isabela
Answers (0)
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!