% File: ANDREWS.G 
% Procedure to compute Andrews (1991) plug-in bandwidth parameter for
%  spectral density estimation. The AR(1) approximation is used.
%  Note: The bandwidth is computed for the Bartlett window.
%
%        INPUT:  Z(T,1)   vector of data.
%
%        OUTPUT: m(1,1)   bandwidth parameter: 1.1447( a(1) * T )^(1/3),
%                         with a(1) = 4( rho / (1-rho^2) )^2
%
%  Note that in the bivariate regression context each row of Z, i.e.,
%  Z(t), typically contains (u(t)*1, u(t)*x(t)), where u is the estimated
%  error term and x(t) is the RHS variable.
%  Reference: Andrews (1991).

function M=andrews(z);

% Univariate z
       if size(z,2) == 1;
            ylag  = trimr(z,0,1);
            y     = trimr(z,1,0);

            %a     = y\ylag;  
	    a=inv(ylag'*ylag)*(ylag'*y);	

            rho   = (0.97 <= a )*0.97 + (a < 0.97)*a;
            a1    = 4*(rho/( (1+rho)*(1-rho) ) )^2;
       else
% Bivariate z (note that we exclude the constant term for HAC estimation)
% See Andrews(91:834)

            a1num = 0;
            a1den = 0;
	    j = 2;      
            while j <= size(z,2)
                 ylag  = trimr(z(:,j),0,1);
                 y     = trimr(z(:,j),1,0);

                 %a     = y\ylag;  
	         a=inv(ylag'*ylag)*(ylag'*y);	
		 %x=[ones(size(ylag,1),1) ylag];
		 %a=inv(x'*x)*(x'*y);

		 %theta=arx(y,1); a=-theta(3,1)

	         rho   = (0.97 <= a )*0.97 + (a < 0.97)*a;
                 v2    = (y-ylag*rho)'*(y-ylag*rho)/(size(y,1)-1);
                 a1num = a1num + 4*( rho*v2 / ( (1+rho)*(1-rho)^3 ) )^2;
                 a1den = a1den + ( v2 / (1-rho)^2 )^2;
            j = j + 1;
            end;
            a1    = a1num/a1den;
       end;
       m     = ceil( 1.1447*(a1*size(z,1))^(1/3) );

       if m <= 1
           m = 2;
       end;

       if m >= round(0.75*size(z,1));
           m = round(0.75*size(z,1));
       end;

M=m-1;         % subtract 1 to make Andrews notation compatible with
               % Newy-West notation (standard in related procedures)
               % See Andrews (1991) pag. 821, footnote 3. 


