Get Started

Forecasting with an AR Model

In addition to estimating the parameters of a model that you did in the last exercise, you can also do forecasting, both in-sample and out-of-sample using statsmodels. The in-sample is a forecast of the next data point using the data up to that point, and the out-of-sample forecasts any number of data points in the future. You can plot the forecasted data using the function plot_predict(). You supply the starting point for forecasting and the ending point, which can be any number of data points after the data set ends.

For the simulated data in DataFrame simulated_data_1, with \(\small \phi=0.9\), you will plot out-of-sample forecasts and confidence intervals around those forecasts.

This is a part of the course

“Time Series Analysis in Python”

View Course

Exercise instructions

  • Import the class ARIMA and also import the function plot_predict
  • Create an instance of the ARIMA class called mod using the simulated data in DataFrame simulated_data_1 and the order (p,d,q) of the model (in this case, for an AR(1)), order=(1,0,0)
  • Fit the model mod using the method .fit() and save it in a results object called res
  • Plot the in-sample data starting with data point 950
  • Plot out-of-sample forecasts of the data and confidence intervals using the plot_predict() function, starting where the data ends at the 1000th point, and ending the forecast at point 1010

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Import the ARIMA and plot_predict from statsmodels
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.graphics.tsaplots import plot_predict

# Forecast the first AR(1) model
mod = ARIMA(___, order=___)
res = mod.fit()

# Plot the data and the forecast
fig, ax = plt.subplots()
simulated_data_1.loc[950:].plot(ax=ax)
plot_predict(res, start=___, end=___, ax=ax)
plt.show()
Edit and Run Code

This exercise is part of the course

Time Series Analysis in Python

IntermediateSkill Level
4.5+
19 reviews

In this four-hour course, you’ll learn the basics of analyzing time series data in Python.

In this chapter you'll learn about autoregressive, or AR, models for time series. These models use past values of the series to predict the current value.

Exercise 1: Describe AR ModelExercise 2: Simulate AR(1) Time SeriesExercise 3: Compare the ACF for Several AR Time SeriesExercise 4: Match AR Model with ACFExercise 5: Estimating and Forecasting AR ModelExercise 6: Estimating an AR ModelExercise 7: Forecasting with an AR Model
Exercise 8: Let's Forecast Interest RatesExercise 9: Compare AR Model with Random WalkExercise 10: Choosing the Right ModelExercise 11: Estimate Order of Model: PACFExercise 12: Estimate Order of Model: Information Criteria

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free