Rolling window regression
이전 댓글 표시
Hi there,
I would like to perform a simple regression of the type y = a + bx with a rolling window. That is, I have a time series for y and a time series for x, each with approximately 50 years of observations and I want to estimate a first sample period of 5 years, and then rolling that window by one observation, re-estimate, and repeat the process to obtain a time-varying series of the coefficient b.
What is the best and most simple way to do this? Does anybody have a sample of code to do that?
Thanks very much for your help
답변 (2개)
Daniel Shub
2011년 5월 22일
Since you are talking about 6000 data points (50 years x 12 months) optimization for speed is not a huge concern.
N = 50*12;
x = 1:N;
y = randn(1, N);
p = cell(1, N-60);
for ix = 1:N-60
p{ix} = polyfit(x((0:59)+ix), y((0:59)+ix), 1)';
end
p = cell2mat(p)';
Each row of p is the slope (b) and intercept (a) for a 60 month window.
댓글 수: 4
Fred
2011년 5월 22일
Daniel Shub
2011년 5월 22일
Yes, but now you are just asking me to write code for you. Why don't you try calculating p and R square values in MATLAB from a single simple regression (hint doc corrcoef). Once you have done that, see if you can figure out where it would go in the for loop I provided.
Oleg Komarov
2011년 5월 22일
use regstats instead of polyfit if you have the stats tb to easily get R^2 and p values.
cyril
2014년 5월 5일
or even use conv for shorter code
John D'Errico
2011년 5월 22일
0 개 추천
If your data series is equally spaced, then this is easy enough to do using filter. It is often called a Savitsky-Golay filter, of which a simple implementation is found in my movingslope code on the file exchange. That code uses filter to to the hard work, then patches the estimates at the ends of the series if necessary, since it uses a sliding central window.
If your data series is NOT equally spaced in time, then the solution is a bit more work since filter cannot be employed. Simplest here is just a loop, perhaps using polyfit with the appropriate data points. One can get trickier, using a QR updating scheme to add and delete points from the model, but that hardly seems worth it for a linear model, and I doubt that it would be any more efficient.
댓글 수: 2
Fred
2011년 5월 22일
John D'Errico
2011년 5월 22일
Why is using that exact code, calling it directly, complicated????? Why do you need to write it yourself, rather than using code that has already been tested and debugged to do the job?
This is like saying that using ANY built-in tool in MATLAB (backslash for example, to do a regression) is complicated, because that code is more complex than you like under the hood.
카테고리
도움말 센터 및 File Exchange에서 Resampling Techniques에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!