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.

 

sas-innovate-2024.png

Available on demand!

Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.

 

Register now!

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

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