% Good Day%
% This MATLAB code is for estiomation of a) Modified HP filter lambda,% 
% b) trend, and c) cyclical component of a given series (y) %
% For details see: M. Ali Choudhary, M. Nadim Hanif and Javed Iqbal (2014)%
% On smoothing macroeconomic time series using the modified HP filter, %
% Applied Economics, 46:19, 2205-2214 %
function [tcmhp,ccmhp,lambda]=modifiedhpfilter(data);

y=data;
% where y is original data series (single)%
x=(y);
siz=size(x);
t=siz(1,1);
maxlam=10000;
% where maxlam is maximum number of lambda to try for best fit.%
% Choice of maxlam is optional. This 10000 is based upon a working on
% variuos macroeconomic series of 93 countries %
lam=(1:1:maxlam)';
k=zeros(t-2,t);
for i=1:t-2;
   for j=1:t;
    if i==j 
        k(i,j)=1;
    end
    if j==i+2
        k(i,j)=1;
    end
    if j==i+1
        k(i,j)=-2;
    end
    end
end
id=eye(t,t);
a=k'*k;
sss=zeros(maxlam,1);
for m=1:maxlam   
b=lam(m,1)*a;
cc=id+b;
d=cc^-1;
% tc is trended component, cc is cyclical component %
tc=d*x;
ss=zeros(t,1);
for i=1:t;    
ss(i,1)=((x(i,1)-tc(i,1))^2)*(1+(2*t)/lam(m,1));
end
sss(m,1)=sum(ss);
end
for mm=1:maxlam;
    if(sss(mm,1)==min(sss))
      pt=mm;
    end
end
lambda=lam(pt,1);
% Where Lambda is the smoothing parameter by modified HP filter approach%
bmhp=lambda*a;
ccmhp=id+bmhp;
dmhp=ccmhp^-1;
% Now, tcmhp and ccmhp (below) are final trend and cyclical component of %
% the series respectivly by Modified HP filter approach%
tcmhp=dmhp*x;
ccmhp=x-tcmhp;

end
