Standard Deviation and Mean Calculation in Rolling Window
Rolling Window Standard Deviation and Mean in Stata
In panel data, we often need to find standard deviation or mean or any other statistics in rolling window of say 4 or 5 years. There is a convenient way of doing this using program asrol that I have written recently. This program requires data to be a panel data. This program can be downloaded from SSC, type the following command in command line window:
ssc install asrol
The program requires the data to be declared as panel data, which can be done with
tsset id year
Where id is panel or firm identifier and year is time identifier. To use asrol program, we shall use an example data of grunfeld , type:
webuse grunfeld
Following are example for different statistics calculations:
Example 1. For Rolling Mean
asrol invest, stat(mean) win(4) gen(mean_4)
This command calculates mean for the variable invest using a four years rolling window and stores the results in a new variable called mean_4. The underlined letters signifies that user can abbreviate the full words only to the underlined letters.
Example 2. For Rolling standard deviation
asrol invest, stat(sd) win(6) gen(sd_6)
This command calculates standard deviation for the variable invest using a six years rolling window and stores the results in a new variable called sd_6
Example 3. For Rolling Mean with no missing values
asrol invest, stat(mean) win(4) gen(sd_4) n
This command calculates mean for the variable invest using a four years rolling window and stores the results in a new variable called mean_4. The n option forces asrol to find mean with all available observation, which results in no missing values at the start of the panel. Compare results where n is not used in example 1 above. In the example 1, asrol finds mean starting with the fourth observation of each panel, i.e. the rolling window does not start working unless it reaches the required level of 4 observations.
Example 4. What Else in a rolling window
asrol can find any statistics in a rolling window that can be calculated with egen function. Specifically, the following statistics can be calculated with asrol:
sd for standard deviation
mean for mean
total for sum or total
median
missing for counting missing values in the rolling window
min for minimum
max for maximum
count for counting number of observations
For more details and syntax description, see program help file
Page Tags:
asrol, stata, unbalanced panel data, rolling standard deviation, rolling mean, rolling median, rolling kurtosis, rolling skewness, rolling sum, rolling total, rolling mean absolute deviation,