You are processing the entire dataset three times, once for each desired forward period. I'd suggest processing the data once, in a data step, using an array to build up a complete history of dividends, and then subsequently retrieve those dividends
BTW - variables FYEAR? GVKEY? You are apparently using Compustat data. And it is probably sorted by GVKEY/DATADATE (almost, but not quite the same as sorted by GVKEY/FYEAR). I assume you are looking at annual data. So here is a DATA step to take advantage of the fact that the data are sorted by GVKEY (it won't matter what the order is within GVKEY).
Untested in the absence of sample data in a working data step:
%let minyear=1998;
%let maxyear=2021;
%let upper_bound=%eval(&maxyear+3);
data want (drop=_:);
array _v1_hist{&minyear:&upper_bound} ; /*dividend history*/
array _v2_hist{&minyear:&upper_bound} ; /*some other history*/
do until (last.gvkey); /*Build history of variables of interest */
set have;
by gvkey;
_v1_hist{fyear}=var1;
_v2_hist{fyear}=var2;
end;
/* Now reread the data and fetch values from future years*/
do until (last.gvkey);
set have;
by gvkey;
var1_f1=_v1_hist{fyear+1};
var2_f1=_v2_hist{fyear+1};
var1_f2=_v1_hist{fyear+2};
var2_f2=_v2_hist{fyear+2};
var1_f3=_v1_hist{fyear+3};
var2_f3=_v2_hist{fyear+3};
output;
end;
run;
The arrays are indexed by fiscal year. You can modify the macrovars minyear and maxyear for your data. This code makes the upper bound of the array equivalent to maxyear+3, so as to avoid an error when retrieving a value for three years after 2021 in this case.
... View more