Get startedGet started for free

Estimating and Forecasting AR Model

1. Estimating and Forecasting an AR Model

Statsmodels has another module for estimating the parameters of a given AR model.

2. Estimating an AR Model

The statsmodels class ARMA has been deprecated and replaced with the slightly more general ARIMA class. After importing ARIMA, create an instance of that class called mod, with the arguments being the data that you're trying to fit, and the order of the model. The order (1,0,0) means you're fitting the data to an AR(1) model. An order (2,0,0) would mean you're fitting the data to an AR(2) model. The middle number, d, relates to whether you take first differences of the data to make the time series stationary, like you would do with a random walk. For now, we'll assume there are no first differences so the middle number will be zero. In the last chapter, we will give an example where we do take first differences. The third number, q, is the MA part, which will be discussed in the next chapter. Once you instantiate the class, you can use the method fit to estimate the model, and store the results in result.

3. Estimating an AR Model

To see the full output, use the summary method on result. The coefficients for the mean mu and AR(1) parameter phi are highlighted in red. In the simulated data, mu was zero and phi was 0-point-9, and you can see that the estimated parameters are very close to the true parameters.

4. Estimating an AR Model

If you just want to see the coefficients rather than the entire regression output, you can use the params property, which returns an array of the fitted coefficients, mu and phi in this case.

5. Forecasting With an AR Model

To plot forecasts, both in-sample and out-of-sample, you have to import a new statsmodels function called plot_predict. The first argument in the plot_predict function is the result from the fitted model that we just talked about. You also give plot_predict the starting and ending data points for forecasting. If the index of the data is a DatetimeIndex object as it is here, you can pick dates for the start and end date. The alpha argument sets the darkness of the shaded confidence interval region, and if you don't want a confidence interval at all, set alpha equal to None. You also need to set ax equal to ax so that the data and the predictions are on the same axes. In this plot, notice how the confidence interval gets wider the farther out the forecast is.

6. Let's practice!

Time to put this into practice.