function [ r_sq_mat ] = r_squared( param, excess_returns, factors , analysis, c_fac)
% time series R-squared for asset pricing time series regression

N=size(excess_returns,2);
T=size(excess_returns,1);

    % transforms N*K param vector an Nx1 alphas vector and into a KxN beta matrix       
    [ alphas , betas_mat, ~ ] = get_alpha_beta_lambda( param, analysis, excess_returns, factors, c_fac );  
    
    
    % time series residuals (for time series and cross-sectional regression
    residuals=excess_returns-ones(T,1)*alphas'-factors*betas_mat';
    
    total_var=(std(excess_returns).^2)';
    res_var=(std(residuals).^2)';
    r_sq=ones(size(residuals,2),1)-(res_var./total_var);
    
    
    % we can only arrange the R-squared in 5-5 form if 25 double sorted
    % test assets are used. Otherwise r_sq_mat is a vector containing the
    % R-squares
    intTest=~mod(sqrt(N),1);          % returns 1, if number is an integer
    
    if intTest==1
        r_sq_mat=reshape(r_sq,[sqrt(N),sqrt(N)]);
    else
        r_sq_mat=r_sq;
    end
end

