function OUTres = oos_performance_stock(ret, FF, tdate)
% calculate total R2 and PE
% ret=[permno, yymm, xret]

[obs,permno]=hist(ret(:,1),unique(ret(:,1))); 
obs = obs';
nn = find(obs>=36);
permno = permno(nn);     
N = length(permno);
L0 = 24;
res = nan(N,5); 
for i = 1:N
    i
  tt = find(ret(:,1)==permno(i));
  tempR = ret(tt,:);
  tempR(any(isnan(tempR), 2), :) = [];
  [~,ia,ib] = intersect(tdate, tempR(:,2));
  Ri = tempR(ib,3);
  ffi = FF(ia,:);   
  obs = length(Ri);
  temp = nan(obs,3);
  if obs<=60
     for t = L0+1:obs
      lhv = Ri(1:t);
      rhv = [ones(t,1) ffi(1:t,:)];
      b = rhv(1:t-1,:)\lhv(1:t-1,:); 
      temp(t,:) = [lhv(end)-rhv(end,:)*b, lhv(end), lhv(end)-rhv(end,2:end)*b(2:end)];
     end
    else
     for t = L0+1:60
      lhv = Ri(1:t);
      rhv = [ones(t,1) ffi(1:t,:)];
      b = rhv(1:t-1,:)\lhv(1:t-1,:); 
     temp(t,:) = [lhv(end)-rhv(end,:)*b, lhv(end), lhv(end)-rhv(end,2:end)*b(2:end)];
     end
     for t = 61:obs
      lhv = Ri(t-60:t);
      rhv = [ones(61,1) ffi(t-60:t,:)];
      b = rhv(1:60,:)\lhv(1:60,:); 
    temp(t,:) = [lhv(end)-rhv(end,:)*b, lhv(end), lhv(end)-rhv(end,2:end)*b(2:end)];
      end
  end
      
  temp = temp(L0+1:end,:);  
  adj = (length(temp)-1)/(length(temp)-1-size(FF,2));
  %%         sum_(Rit-a-bf_t)^2      sum_Rit^2          alpha_i          sigma_alpha_i  mu_i
  res(i,:) = [sum(temp(:,1).^2)*adj, sum(temp(:,2).^2), mean(temp(:,3)), std(temp(:,1)), mean(temp(:,2))];
  %%          1                      2                  3                4               5  
end
 
MPE = 100*sqrt(mean(res(:,3).^2));
TotalR2 = 100*(1- sum(res(:,1))/sum(res(:,2)) );
SR = mean( abs( res(:,3)./res(:,4) ) );
A2R = mean( abs(res(:,3)./res(:,5)) ); 
OUTres = [MPE, TotalR2, SR, A2R];