## Moving averages with varying time periods

Occasional Contributor
Posts: 17

# Moving averages with varying time periods

Dear Experts,

I have the folloowing information

``````data have;
infile datalines dlm=',' dsd truncover;
input ID. Returns  year;
datalines;
1,1.01,1968
1,1.04,1969
1,1.001,1970
1,1.005,1971
1,1.02,1972
1,1.02,1973
1,1.06,1980
1,1.06,1981
1,1.0014,1982
run; ``````

ID    Date                        year

1        1.01                     1968

1        1.04                     1969

1       1.001                    1970

1       1.005   .                1971

1         1.02                    1972

1         1.02                    1973

1         1.06                    1980

1         1.06                    1981

1        1.0014                 1982

I would like to calculate the 2 yearly moving averages for group ID 1. The problem however is that the returns from 1974 to 1979 i are missing. How can one calculate moving average by year, such that for the years 1968 to 1973 and seperately for 1980 to 1982 in the same dataset? Could anyone help with the SAS code that could accomplish this task.

Regards
Akarsh91

Super User
Posts: 23,346

## Re: Moving averages with varying time periods

PROC EXPAND. Search on here or the DOCS for examples.

Posts: 4,697

## Re: Moving averages with varying time periods

@Akarsh91

The following Google search string will return quite a few helpful hits:

site:*.sas.com rick wicklin moving average

Super User
Posts: 10,699

## Re: Moving averages with varying time periods

If you don't have big table, try SQL.

``````data have;
infile datalines dlm=',' dsd truncover;
input ID Returns  year;
datalines;
1,1.01,1968
1,1.04,1969
1,1.001,1970
1,1.005,1971
1,1.02,1972
1,1.02,1973
1,1.06,1980
1,1.06,1981
1,1.0014,1982
run;
proc sql;
select *,(select mean(returns) from have
where id=a.id and year between a.year-2 and a.year) as rolling_mean
from have as a;
quit;``````
Discussion stats
• 3 replies
• 138 views
• 0 likes
• 4 in conversation