BookmarkSubscribeRSS Feed
☑ This topic is solved. Need further help from the community? Please sign in and ask a new question.
bd_user_10
Quartz | Level 8

 

The macro below shows how you can compute a "rolling" standard deviation. For example, it gets the standard deviation for observations 1-25, then 
observations 2-26 then 3-27 … up to 476-500, and then saves this into a SAS data file.


%macro rollsd; proc delete data=all; run; %do firstobs = 1 %to 476; %let lastobs = %eval( &firstobs + 24); proc means data=test(firstobs=&firstobs obs=&lastobs); var x; output out=tempfile stddev=sd25; run; proc append base=all data=tempfile ; run; %end; %mend rollsd;

I have hundreds of firms (ISIN) and each firm has different number of observations. This macro only considers the first observations from 1 to 476.
How do i adjust this macro so that i can calculate 252 day rolling standard deviation for all firms in my dataset? Thanks in advance for your help?
1 ACCEPTED SOLUTION

Accepted Solutions
Kurt_Bremser
Super User

Maxim 9: There Is a Function for It.

Instead of using the MEANS procedure, use the STD function on an array.

This is an example of using an array for any kind of rolling window calculations

%let winsize=252;

data want;
set have;
by isin;
array vals {&winsize.} _temporary_;
if first.isin then call missing(of vals{*});
vals{mod(_n_,&winsize.)+1} = x;
sd&winsize. = std(of vals{*});
run;

Untested; for tested code, supply example data in a data step with datalines.

View solution in original post

2 REPLIES 2
Kurt_Bremser
Super User

Maxim 9: There Is a Function for It.

Instead of using the MEANS procedure, use the STD function on an array.

This is an example of using an array for any kind of rolling window calculations

%let winsize=252;

data want;
set have;
by isin;
array vals {&winsize.} _temporary_;
if first.isin then call missing(of vals{*});
vals{mod(_n_,&winsize.)+1} = x;
sd&winsize. = std(of vals{*});
run;

Untested; for tested code, supply example data in a data step with datalines.

Tom
Super User Tom
Super User

Do you have SAS/ETS licensed?  If so there is PROC for doing that.

 

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

How to Concatenate Values

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.

SAS Training: Just a Click Away

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

Browse our catalog!

Discussion stats
  • 2 replies
  • 995 views
  • 4 likes
  • 3 in conversation