Time series forecasting is a process, and the only way to get good forecasts is to practice this process.
In this tutorial, you will discover how to forecast the annual water usage in Baltimore with python.
Working through this tutorial will provide you with a framework for the steps and the tools for working through your own time series forecasting problems.
After completing this tutorial, you will know:
How to confirm your Python environment and carefully define a time series forecasting problem. How to create a test harness for evaluating models, develop a baseline forecast, and better understand your problem with the tools of time series analysis. How to develop an autoregressive integrated moving average model, save it to file, and later load it to make predictions for new time steps.Let’s get started.

Time Series Forecast Study with Python Annual Water Usage in Baltimore
Photo by Andy Mitchell , some rights reserved.
OverviewIn this tutorial, we will work through a time series forecasting project from end-to-end, from downloading the dataset and defining the problem to training a final model and making predictions.
This project is not exhaustive, but shows how you can get good results quickly by working through a time series forecasting problem systematically.
The steps of this project that we will work through are as follows.
Environment. Problem Description. Test Harness. Persistence. Data Analysis. ARIMA Models. Model Validation.This will provide a template for working through a time series prediction problem that you can use on your own dataset.
1. EnvironmentThis tutorial assumes an installed and working SciPy environment and dependencies, including:
SciPy NumPy Matplotlib Pandas scikit-learn statsmodelsIf you need help installing Python and the SciPy environment on your workstation, consider the Anaconda distribution that manages much of it for you.
This script will help you check your installed versions of these libraries.
# scipy importscipy print('scipy: %s' % scipy.__version__) # numpy importnumpy print('numpy: %s' % numpy.__version__) # matplotlib importmatplotlib print('matplotlib: %s' % matplotlib.__version__) # pandas importpandas print('pandas: %s' % pandas.__version__) # scikit-learn importsklearn print('sklearn: %s' % sklearn.__version__) # statsmodels importstatsmodels print('statsmodels: %s' % statsmodels.__version__)The results on my workstation used to write this tutorial are as follows:
scipy: 0.18.1 numpy: 1.11.2 matplotlib: 1.5.3 pandas: 0.19.1 sklearn: 0.18.1 statsmodels: 0.6.1 2. Problem DescriptionThe problem is to predict annual water usage.
The dataset provides the annual water usage in Baltimore from 1885 to 1963, or 79 years of data.
The values are in the units of liters per capita per day, and there are 79 observations.
The dataset is credited to Hipel and McLeod, 1994.
You can learn more about this dataset and download it directly from DataMarket .
Download the dataset as a CSV file and place it in your current working directory with the filename “ water.csv “.
3. Test HarnessWe must develop a test harness to investigate the data and evaluate candidate models.
This involves two steps:
Defining a Validation Dataset. Developing a Method for Model Evaluation. 3.1 Validation DatasetThe dataset is not current. This means that we cannot easily collect updated data to validate the model.
Therefore, we will pretend that it is 1953 and withhold the last 10 years of data from analysis and model selection.
This final decade of data will be used to validate the final model.
The code below will load the dataset as a Pandas Series and split into two, one for model development ( dataset.csv ) and the other for validation ( validation.csv ).
frompandasimportSeries series = Series.from_csv('water.csv', header=0) split_point = len(series) - 10 dataset, validation = series[0:split_point], series[split_point:] print('Dataset %d, Validation %d' % (len(dataset), len(validation))) dataset.to_csv('dataset.csv') validation.to_csv('validation.csv')Running the example creates two files and prints the number of observations in each.
Dataset 69, Validation 10The specific contents of these files are:
dataset.csv : Observations from 1885 to 1953 (69 observations). validation.csv : Observations from 1954 to 1963 (10 observations).The validation dataset is about 12% of the original dataset.
Note that the saved datasets do not have a header line, therefore we do not need to cater to this when working with these files later.
3.2. Model EvaluationModel evaluation will only be performed on the data in dataset.csv prepared in the previous section.
Model evaluation involves two elements:
Performance Measure. Test Strategy. 3.2.1 Performance MeasureWe will evaluate the performance of predictions using the root mean squared error (RMSE). This will give more weight to predictions that are grossly wrong and will have the same units as the original data.
Any transforms to the data must be reversed before the RMSE is calculated and reported to make the performance between different methods directly comparable.
We can calculate the RMSE using the helper function from the scikit-learn library mean_squared_error() that calculates the mean squared error between a list of expected values (the test set) and the list of predictions. We can then take the square root of this value to give us a RMSE score.
For example:
fromsklearn.metricsimportmean_squared_error frommathimportsqrt ... test = ... predictions = ... mse = mean_squared_error(test, predictions) rmse = sqrt(mse) print('RMSE: %.3f' % rmse) 3.2.2 Test StrategyCandidate models will be evaluated using walk-forward validation.
This is because a rolling-forecast type model is required from the problem definition. This is where one-step forecasts are needed given all available data.
The walk-forward validation will work as follows:
The first 50% of the dataset will be held back to train the model. The remaining 50% of the dataset will be iterated and test the model. For each step in the test dataset: A model will be trained. A one-step prediction made and the prediction stored for later evaluation. The actual observation from the test dataset will be added to the training dataset for the next iteration. The predictions made during the enumeration of the test dataset will be evaluated and an RMSE score reported.Given the small size of the data, we will allow a model to be re-trained given all available data prior to each prediction.
We can write the code for the test harness using simple NumPy and Python code.
Firstly, we can split the dataset into train and test sets directly. We’re careful to always convert a loaded dataset to float32 in case the loaded data still has some String or Integer data types.
# prepare data X = series.values X = X.astype('float32') train_size = int(len(X) * 0.50) train, test = X[0:train_size], X[train_size:]Next, we can iterate over the time steps in the test dataset. The train dataset is stored in a Python list as we need to easily append a new observation each iteration and NumPy array concatenation feels like overkill.
The prediction made by the model is called yhat for convention, as the outcome or observation is referred to as y and yhat (a ‘ y ‘ with a mark above) is the mathematical notation for the prediction of the y variable.
The prediction and observation are printed each observation for a sanity check prediction in case there are issues with the model.
# walk-forward validation history = [x for x in train] predictions = list() for i in range(len(test)): # predict yhat = ... predictions.append(yhat) # observation obs = test[i] history.append(obs) print('>Predicted=%.3f, Expected=%3.f' % (yhat, obs)) 4. PersistenceThe first step before getting bogged down in data analysis and modeling is to establish a baseline of performance.
This will provide both a template for evaluating models using the proposed test harness and a performance measure by which all more elaborate predictive models can be compared.
The baseline prediction for time series forecasting is called the naive forecast, or persistence.
This is where the observation from the previous time step is used as the prediction for the observation at the next time step.
We can plug this directly into the test harness defined in the previous section.
The complete code listing is provided below.
frompandasimportSeries fromsklearn.metricsimportmean_squared_error frommathimportsqrt # load data series = Series.from_csv('dataset.csv') # prepare data X = series.values X = X.astype('float32') train_size = int(len(X) * 0.50) train, test = X[0:train_size], X[train_size:] # walk-forward validation history = [x for x in train] predictions = list() for i in range(len(test)): # predict yhat = history[-1] predictions.append(yhat) # observation obs = test[i] history.append(obs) print('>Predicted=%.3f, Expected=%3.f' % (yhat, obs)) # report performance mse = mean_squared_error(test, predictions) rmse = sqrt(mse) print('RMSE: %.3f' % rmse)Running the test harness prints the prediction and observation for each iteration of the test dataset.
The example ends by printing the RMSE for the model.
In this case, we can see that the persistence model achieved an RMSE of 21.975. This means that on average, the model was wrong by about 22 liters per capita per day for each prediction made.
... >Predicted=613.000, Expected=598 >Predicted=598.000, Expected=575 >Predicted=575.000, Expected=564 >Predicted=564.000, Expected=549 >Predicted=549.000, Expected=538 RMSE: 21.975We now have a baseline prediction method and performance; now we can start digging into our data.
5. Data AnalysisWe can use summary statistics and plots of the data to quickly learn more about the structure of the prediction problem.
In this section, we will look at the data from four perspectives:
Summary Statistics. Line Plot. Density Plots. Box and Whisker Plot. 5.1. Summary StatisticsSummary statistics provide a quick look at the limits of observed values. It can help to get a quick idea of what we are working with.
The example below calculates and prints summary statistics for the time series.
frompandasimportSeries series = Series.from_csv('dataset.csv') print(series.describe())Running the example provides a number of summary statistics to review.
Some observations from these statistics include:
The number of observations (count) matches our expectation, meaning we are handling the data correctly. The mean is about 500, which we might consider our level in this series. The standard deviation and percentiles suggest a reasonably tight spread around the mean. count 69.000000 mean 500.478261 std 73.901685 min344.000000 25%458.000000 50%492.000000 75%538.000000 max662.000000 5.2. Line PlotA line plot of a time series dataset can provide a lot of insight into the problem.
The example below creates and shows a line plot of the dataset.
frompandasimportSeries frommatplotlibimportpyplot series = Series.from_csv('dataset.csv') series.plot() pyplot.show()Run the example and review the plot. Note any obvious temporal structures in the series.
Some observations from the plot include:
There looks to be an increasing trend in water usage over time. There do not appear to be any obvious outliers, although there are some large fluctuations. There is a downward trend for the last few years of the series.
Annual Water Usage Line Plot
There may be somebenefit in explicitly modeling the trend component and removing it. You may also explore using differencing with one or two levels in order to make the series stationary.
5.3. Density PlotReviewing plots of the density of observations can provide further insight into the structure of the data.
The example below creates a histogram and density plot of the observations without any temporal structure.
frompandasimportSeries frommatplotlibimportpyplot series = Series.from_csv('dataset.csv') pyplot.figure(1) pyplot.subplot(211) series.hist() pyplot.subplot(212) series.plot(kind='kde') pyplot.show()Run the example and review the plots.
Some observations from the plots include:
The distribution is not Gaussian, but is pretty close. The distribution has a long right tail and may suggest an exponential distribution or a double Gaussian.
Annual Water Usage Density Plots
This suggests it may be worth exploring some power transforms of the data prior to modeling.
5.4. Box and Whisker PlotsWe can group the annual data by decade and get an idea of the spread of observations for each decade and how this may be changing.
We do expect to see some trend (increasing mean or median), but it may be interesting to see how the rest of the distribution may be changing.
The example below groups the observations by decade and creates one box and whisker plot for each decade of observations. The last decade only contains 9 years and may not be a useful comparison with the other decades. Therefore only data between 1885 and 1944 was plotted.
frompandasimportSeries frompandasimportDataFrame frompandasimportTimeGrouper frommatplotlibimportpyplot series = Series.from_csv('dataset.csv') groups = series['1885':'1944'].groupby(TimeGrouper('10AS')) decades = DataFrame() for name, groupin groups: decades[name.year] = group.values decades.boxplot() pyplot.show()Running the example creates 6 box and whisker plots side-by-side, one for the 6 decades of selected data.
Some observations from reviewing the plot include:
The median values fo