DATA Step, Macro, Functions and more

how to do a loop(do) in SAS

Frequent Contributor
Posts: 122

how to do a loop(do) in SAS

I want to do a loop to do regression multiple times. Let me briefly talk about my case. I have a dataset with variables id,y, x1, x2, x3, ... x10 and t. id is stock id, y is return, x1...x10 are some factors, t is time. First I want to do a time series regression of y on x1 for each id (should have t months) to get coefficients of x1, then regress some change of y on the coefficients of x1 for each t (month). I need to repeat this for 10 times, x1 until x10. I wrote a program to do one rolling regression, but want to use a do loop to repeat from x1 to x10. I attach part of my code here. Please help me loop over x1 to x10 part. Thanks.

* Define independent and dependent variables;

%let x1=def;

%let x2=smb;

%let x3=hml;

%let x4=mom;

%let x5=def;

%let x6=term;

%let x7=div;

%let x8=inf;

%let x9=ip;

%let x10=pyrl;

%let y=ret;

data betas1; stop; run;

%macro tsreg; * time series regression;

%do m = 37 %to 216; * from month 37 to 216;

    data roll; set temp;

  if &m - 36 <= t < &m; * Past 36 months data, for example, for month 37, t=1-36;

  mon = &m; * Create a variable "mon" for each m loop;

  proc reg data=roll noprint outest=results EDF;

  model &y=&x1;

  by productreference mon;


  data betas1 ;

   set betas1 results;



%mend tsreg;


proc sort data = betas1;

by t;


proc reg data = betas1 noprint outest = final;

model &y = &x1;

by t;


Super User
Posts: 19,789

Re: how to do a loop(do) in SAS

Here's a perfect example of what you want to do:

Posts: 3,752

Re: how to do a loop(do) in SAS

Do you have missing values in these variables? If not, you don't need more macro loops. The REG procedure supports multiple MODEL statements.  Just list all of the explanatory variables on the VAR statement and then use multiple MODEL statements for your 10 variables within a single PROC REG call.  Here's an example:

proc reg noprint outest=results;

var Cylinders EngineSize Length MPG_City Weight;

Cylinders:  model Horsepower = Cylinders;

EngineSize: model Horsepower = EngineSize;

Length:     model Horsepower = Length;

MPG_City:   model Horsepower = MPG_City;

Weight:     model Horsepower = Weight;


Look in the OUTEST= data set and you'll see the parameter estimates for each model.

Ask a Question
Discussion stats
  • 2 replies
  • 3 in conversation