BookmarkSubscribeRSS Feed
smilingmelbourne
Fluorite | Level 6
Hi, I need to compute rolling 3-month and 9-month returns. I wrote this code but it is very awkward (and lengthy with y1, y2, y3, vv...y8);

Can you please help suggest a better yet simple code? Thanks

data temp;
input x y;
datalines;
15 151
151 54
890 521
451 90
521 588
515 85
52 80
89 56
24 55
252 51
145 58
;
run;

data m3; /*Rolling 3-month*/
set temp;
n=_n_;
y1=lag(y); y2=lag(y1);
cum_y=y+y1+y2;
if mod(n,3)^=0 then delete;
keep x cum_y;
run;

data m9; /*Rolling 9-month*/
set temp;
n=_n_;
y1=lag(y); y2=lag(y1); y3=lag(y2); y4=lag(y3); y5=lag(y4); y6=lag(y5); y7=lag(y6); y8=lag(y7);
cum_y=y+y1+y2+y3+y4+y5+y6+y7+y8;
if mod(n,9)^=0 then delete;
keep x cum_y;
run;
2 REPLIES 2
Patrick
Opal | Level 21
data m3;
set temp;
retain cum_y;
cum_y=sum(cum_y,y);
if mod(_n_,3)=0 then
do;
output;
call missing(cum_y);
end;
run;

data m9;
set temp;
retain cum_y;
cum_y=sum(cum_y,y);
if mod(_n_,9)=0 then
do;
output;
call missing(cum_y);
end;
run;


... and "better" than y3=lag(y2); would have been y3=lag3(y);


HTH
Patrick
smilingmelbourne
Fluorite | Level 6
Thanks, Pattrick, for help. I'd read the book on Output several times, and didn't quite really catch the idea until I've read your code! I just couldn't think of using Output right after the MOD function. Yesterday I found a macro from a university for this rolling, and the macro was far, far complicated than yours. Basically, they used Proc Means for each 3-month and 9-month interval, then output the datasets, then use Proc Append to concatenate all datasets, and for the same thing it has at leas 5 SAS programs.

Thanks so much and I've learnt a lot from your codes. Message was edited by: smilingmelbourne

SAS Innovate 2025: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

What is Bayesian Analysis?

Learn the difference between classical and Bayesian statistical approaches and see a few PROC examples to perform Bayesian analysis in this video.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 2 replies
  • 2196 views
  • 0 likes
  • 2 in conversation