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?
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.
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.
Do you have SAS/ETS licensed? If so there is PROC for doing that.
Available on demand!
Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.
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.