function [alpha, beta, R2, siga, sigb] = tsregress(rx,f);

% function tsregress. Does time series regressions of returns on factors
% this version for problem set 3 does not do GRS etc. tests
% inputs: 
% rx: T x N matrix of excess returns in percent units for test assets
% f: T x K matrix of factors 
% 
% outputs: 
% alpha N x 1 vector of alphas
% beta N x K vector of betas
% R2 N x 1 vector of time series R2 
% siga = N x 1 vector of standard errors of alpha
% sigb = N x K matrix of standard errors of betas

T = size(rx,1); 
N = size(rx,2); 
K = size(f,2); 
if size(f,1) ~= size(rx,1); 
    disp('tsregress error: factors and returns must be of same length'); 
end; 

X = [ones(T,1) f];
b = X\rx; 
u = rx-X*b; 
s2 = var(u)'*(T-1)/(T-K-1);      % produces a vector, variance of the 25 errors 
                                 % NOTE var uses 1/T-1, I corrected to 1/T-K-1 
mx = inv(X'*X); 
dmx = diag(mx); % we're interested in standard errors, the diagonals of the covariance matrix of bs
siga = (s2*dmx(1)).^0.5;         % standard errors of alpha, beta 
sigb = (s2*dmx(2:end)').^0.5;    % s2 is a column vector of 25. dmx' is a row vector corresponding to factors. 
                                 % this produces a matrix the same size as
                                 % the b3 coefficients. 

alpha = b(1,:)'; 
beta = b(2:end,:)';           % is now 25 x 3 with portfolios up and down 
R2 = 1-s2./(std(rx).^2)'; 

return; 