********************************************
* IML Rolling Regression By Group.sas **
* This code calculates Betas by "Cusip" **
*******************************************;
libname sample "E:\Data";
proc iml;
start OLSParamEst(y,x, k);
Estimate= j(nrow(y),2,.);
do i = 1 to nrow(y);
idx = max(1,(i-k+1)):i; /* rolling window of data points */
Estimate[i] = ginv(x[idx]`*x[idx])*x[idx]`*y[idx];
end;
return (Estimate);
finish;
use sample.threefirms; /* input data */
read all var {"Cusip"}; /* read BY var */
byGroup = unique( Cusip ); /* compute unique levels */
ByVal = BlankStr(nleng(Cusip)); /* set sprtrn of ByVal variable (12.3) */
OutVarNames = {"ret" "sprtrn" "shrout"};
Estimate = {..}; /* output variables are numeric */
create RegOut from Estimate[r=ByVal c=OutVarNames];
setin sample.threefirms; /* Cusip current for reading */
setout RegOut; /* Cusip current for writing */
InVarNames = {"ret" "sprtrn" "shrout"}; /* input variables */
index Cusip; /* index by BY group variable */
do i = 1 to ncol(byGroup);
ByVal = byGroup[i];
read all var InVarNames where(Cusip=(ByVal));
Estimate = OLSParamEst(ret,sprtrn||shrout,36);
append from Estimate[r=ByVal];
end;
close sample.threefirms RegOut;
quit; Many thanks for your response to my inquiry, Rick. In fact, I am trying to learn how SAS/IML can run rolling window regressions with the similar results offered using PROC REG. I have never used SAS/IML before. After reading your book "Statistical Programming with SAS/IML Software", I found SAS/IML a power tool that is worth spending time/effort to learn. The code shown above tries to run rolling regression of monthly stock returns on the S&P 500 index returns. It seems to work but needs to revise: 1. The "ByVal" cusip only displays for the first estimate of each firm. How can I revise to code to display for each row of the results? 2. How to display the "Date" of the end of each time window for each row? 3. How to revise the code in order to not show the invalid estimates "."? In sum, I want to report all the results using SAS/IML similar to those offered by PROC REG Thanks.
... View more