And it doesn't matter if that's 120, 125, or 130 days?
Sure. Also assuming table has been sorted by Stock,Date.
data have;
infile cards truncover;
input stock date : yymmdd10. ret ;
format date yymmdd10.;
cards;
1 20100107 0.04135
1 20100126 -0.02544
1 20100129 0.03384
1 20100201 0.01089
1 20100202 0.02621
1 20100226 0.01001
1 20100301 -0.0132
1 20100330 -0.0181
1 20100331 -0.00308
1 20100401 0.05394
1 20100429 -0.01077
1 20100430 0.0031
1 20100503 0.00931
1 20100521 0
1 20100531 -0.01427
1 20100601 -0.02718
1 20100617 0.05019
1 20100630 -0.01236
1 20100701 0
1 20100728 0.01193
1 20100730 0.01621
1 20100802 -0.0174
2 20100107 0.06069
2 20100126 -0.06219
2 20100129 0.01989
2 20100201 -0.04551
2 20100202 0.04768
2 20100226 -0.05462
2 20100301 0.02613
2 20100330 -0.04155
2 20100331 0.04336
2 20100401 -0.00536
2 20100429 -0.02561
2 20100430 -0.0166
2 20100503 0.00563
2 20100521 0
2 20100531 0.01119
2 20100601 0
2 20100617 0.01521
2 20100630 0.27384
2 20100701 0.09519
2 20100728 -0.12793
2 20100730 -0.04815
2 20100802 -0.02235
;
run;
data want;
if _n_=1 then do;
if 0 then set have(rename=(ret=_ret));
declare hash h();
h.definekey('date');
h.definedata('_ret');
h.definedone();
end;
do until(last.stock);
set have;
by stock;
_ret=ret;h.add();
end;
do until(last.stock);
set have;
by stock;
avg_ret=.;
month=month(date);
if lag(month) ne month then do;
sum=0;n=0;
do k=intnx('month',date,-6,'b') to intnx('month',date,-1,'e');
if h.find(key:k)=0 then do;sum+_ret;n+1;end;
end;
avg_ret=divide(sum,n);
end;
output;
end;
h.clear();
drop sum n k _ret month;
run;
@Kyojik Please post as a new question and link to this or your partial solution ideally. Make sure to include sample data. You'll get a faster response that way. As initially mentioned, PROC EXPAND is the easiest to code solution if you have SAS/ETS licensed.
Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.