Moving averages with varying time periods

Reply
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. 

Please write if you need more information. 

 

Regards 
Akarsh91

Super User
Posts: 19,192

Re: Moving averages with varying time periods

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

Respected Advisor
Posts: 4,138

Re: Moving averages with varying time periods

@Akarsh91

This article could be helpful to you: http://blogs.sas.com/content/iml/2016/01/27/moving-average-in-sas.html

 

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

site:*.sas.com rick wicklin moving average 

 

 

 

Super User
Posts: 9,878

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;
Ask a Question
Discussion stats
  • 3 replies
  • 122 views
  • 0 likes
  • 4 in conversation