% MALLOWS.M 


% This Matlab procedure computes the Mallows Model Average (MMA) least-squares estimates, 
% as described in the paper "Least Squares Model Averaging"


% written by
% Bruce E. Hansen
% Department of Economics
% Univerity of Wisconsin


% Format:


% {betahat,w}=mma(y,x,m,k);


% Inputs:
% y                     nx1 dependent variable
% x                     nxp regressor matrix
% m                     positive integer. 1<=m<=p. Largest fitted model order
% k                     positive integer. 1<=k<=p. Model order used to estimate variance.


% Outputs:
% betahat                       mx1 parameter estimate
% w                     mx1 weight vector


% Note:
% The regressors columns should be ordered, with the intercept first and then in order of relevance.
% 


function [betahat,w] = mma(y,x,m,k);
xx=x'*x;
sxy=x'*y;
bbeta=zeros(m,m);


for j=1:m
    bbeta(1:j,j)=(sxy(1:j)'/xx(1:j,1:j)')';
end;
ee=y-x(:,1:m)*bbeta;
a1=ee'*ee;
if k>m; 
    k=m;
end;
ehat=y-x(:,1:k)*bbeta(1:k,k);
sighat=(ehat'*ehat)/(length(y(:,1))-k);
a2=-1*(1:m)'*sighat;
w0=ones(m,1)/m;
w=quadprog(a1,-a2,zeros(1,m),0,ones(1,m),1,zeros(m,1),ones(m,1),w0);
w=w.*(w>0);
w=w/sum(w)';
betahat=bbeta*w;
