# Time Series in 5-Minutes, Part 6: Modeling Time Series Data

*Written by Matt Dancho on September 9, 2020*

**Have 5-minutes? Then let’s learn time series.** In this short articles series, I highlight how you can get up to speed quickly on important aspects of time series analysis.

In this article we walk through modeling time series data using the `modeltime`

package. In part 1-5 of the series we learned how to use `timetk`

to visualize, wrangle, and feature engineer time series data, and in this article you’ll see how simple it is is to prepare the data for modeling using the `timetk`

package.

### Updates

This article has been updated. View the updated Time Series in 5-Minutes article at Business Science.

## Time Series in 5-Mintues

Articles in this Series

I just released `timetk`

2.0.0 (read the release announcement). A ton of new functionality has been added. We’ll discuss some of the key pieces in this article series:

- Part 1, Data Wrangling and Rolling Calculations
- Part 2, The Time Plot
- Part 3, Autocorrelation
- Part 4, Seasonality
- Part 5, Anomalies and Anomaly Detection
- Part 6, Modeling Time Series Data

👉 **Register for our blog to get new articles as we release them.**

# Have 5-Minutes?

Then let’s learn Time Series Modeling

Forecasting with `tidymodels`

made easy! This short tutorial shows how you can use:

**Modeltime models**like`arima_reg()`

,`arima_boost()`

,`exp_smoothing()`

,`prophet_reg()`

,`prophet_boost()`

, and more**Parsnip models**like`linear_reg()`

,`mars()`

,`svm_rbf()`

,`rand_forest()`

,`boost_tree()`

and more

To perform classical time series analysis and machine learning ** in one framework!** See

*“Model List”*for the full list of

`modeltime`

models.

## The Modeltime Workflow

Here’s the general process and where the functions fit.

Just follow the `modeltime`

workflow, which is detailed in 6 convenient steps:

- Collect data and split into training and test sets
- Create & Fit Multiple Models
- Add fitted models to a
**Model Table** **Calibrate**the models to a testing set.- Perform Testing Set
*Forecast*&*Accuracy*Evaluation **Refit**the models to Full Dataset &*Forecast*Forward

Let’s go through a guided tour to kick the tires on `modeltime`

.

Load libraries to complete this short tutorial.

## Time Series Forecasting Example

Load libraries to complete this short tutorial.

### Step 1 - Collect data and split into training and test sets.

We can visualize the dataset.

Let’s split the data into training and test sets using `initial_time_split()`

### Step 2 - Create & Fit Multiple Models

We can easily create dozens of forecasting models by combining `modeltime`

and `parsnip`

. We can also use the `workflows`

interface for adding preprocessing! Your forecasting possibilities are endless. Let’s get a few basic models developed:

- ARIMA
- Exponential Smoothing
- Linear Regression
- MARS (Multivariate Adaptive Regression Splines)

**Important note: Handling Date Features**

*Modeltime models* (e.g. `arima_reg()`

) are created with a date or date time feature in the model. You will see that most models include a formula like `fit(value ~ date, data)`

.

*Parsnip models* (e.g. `linear_reg()`

) typically should not have date features, but may contain derivatives of dates (e.g. month, year, etc). You will often see formulas like `fit(value ~ as.numeric(date) + month(date), data)`

.

#### Model 1: Auto ARIMA (Modeltime)

First, we create a basic univariate ARIMA model using “Auto Arima” using `arima_reg()`

#### Model 2: Boosted Auto ARIMA (Modeltime)

Next, we create a boosted ARIMA using `arima_boost()`

. Boosting uses XGBoost to model the ARIMA errors. Note that model formula contains both a date feature and derivatives of date

- ARIMA uses the date
- XGBoost uses the derivatives of date as regressors

Normally I’d use a preprocessing workflow for the month features using a function like `step_timeseries_signature()`

from `timetk`

to help reduce the complexity of the parsnip formula interface.

#### Model 3: Exponential Smoothing (Modeltime)

Next, create an Error-Trend-Season (ETS) model using an Exponential Smoothing State Space model. This is accomplished with `exp_smoothing()`

.

#### Model 4: Prophet (Modeltime)

We’ll create a `prophet`

model using `prophet_reg()`

.

#### Model 5: Linear Regression (Parsnip)

We can model time series linear regression (TSLM) using the `linear_reg()`

algorithm from `parsnip`

. The following derivatives of date are used:

*Trend:*Modeled using`as.numeric(date)`

*Seasonal:*Modeled using`month(date)`

#### Model 6: MARS (Workflow)

We can model a Multivariate Adaptive Regression Spline model using `mars()`

. I’ve modified the process to use a `workflow`

to standardize the preprocessing of the features that are provided to the machine learning model (mars).

OK, with these 6 models, we’ll show how easy it is to forecast.

### Step 3 - Add fitted models to a Model Table.

The next step is to add each of the models to a Modeltime Table using `modeltime_table()`

. This step does some basic checking to make sure each of the models are fitted and that organizes into a scalable structure called a ** “Modeltime Table”** that is used as part of our

*forecasting workflow.*

We have 6 models to add. A couple of notes before moving on:

- Note that some of the models have
*tunable parameters*. - It’s expected that tuning and parameter selection is performed prior to incorporating into a Modeltime Table.
- If you try to add an unfitted model, the
`modeltime_table()`

will complain (throw an informative error) saying you need to`fit()`

the model.

### Step 4 - Calibrate the model to a testing set.

Calibrating adds a new column, `.calibration_data`

, with the test predictions and residuals inside. A few notes on Calibration:

- Calibration is how confidence intervals and accuracy metrics are determined
is simply forecasting predictions and residuals that are calculated from out-of-sample data.*Calibration Data*- After calibrating, the calibration data follows the data through the forecasting workflow.

### Step 5 - Testing Set Forecast & Accuracy Evaluation

There are 2 critical parts to an evaluation.

- Visualizing the Forecast vs Test Data Set
- Evaluating the Test (Out of Sample) Accuracy

#### 5A - Visualizing the Forecast Test

Visualizing the Test Error is easy to do using the **interactive plotly visualization (just toggle the visibility of the models using the Legend).**

From visualizing the test set forecast:

**Models 1&2: ARIMA & ARIMA Boost**are performing well. Both models have “auto” components because we used Auto ARIMA. The XGBoost component has parameters that were specified. We can possibly get better accuracy by tuning, but because the ARIMA component is working well on this data, additional improvement may be low.**Model 3: ETS(M,A,A)**is performing the best. The 80% confidence interval is the most narrow of the bunch, indicating the hold out set is modeled well.**Model 4: PROPHET**is comparable to the ARIMA models, but has a slightly wider test error confidence interval.**Model 5: LM**is over-shooting the local trend. This is because the trend component is a simple linear line, which doesn’t account for the change points.**Model 6: EARTH**is overfitting the local trend. This is because we did not tune the number of change points, so the algorithm is auto-calculating the change points.

#### 5B - Accuracy Metrics

We can use `modeltime_accuracy()`

to collect common accuracy metrics. The default reports the following metrics using `yardstick`

functions:

**MAE**- Mean absolute error,`mae()`

**MAPE**- Mean absolute percentage error,`mape()`

**MASE**- Mean absolute scaled error,`mase()`

**SMAPE**- Symmetric mean absolute percentage error,`smape()`

**RMSE**- Root mean squared error,`rmse()`

**RSQ**- R-squared,`rsq()`

These of course can be customized following the rules for creating new yardstick metrics, but the defaults are very useful. Refer to `default_forecast_accuracy_metrics()`

to learn more.

To make table-creation a bit easier, I’ve included `table_modeltime_accuracy()`

for outputing results in either interactive (`reactable`

) or static (`gt`

) tables.

From the accuracy metrics:

**Model 3: ETS is clearly the winner here with MAE of 77****Model 6: MARS**is over-fitting the local trend. This comes out in the R-Squared of 0.55.

### Step 6 - Refit to Full Dataset & Forecast Forward

The final step is to refit the models to the full dataset using `modeltime_refit()`

and forecast them forward.

## Refitting - What happened?

**The models have all changed!** (Yes - this is the point of refitting)

- The
**LM**model looks much better now because the linear trend line has now been fit to new data that follows the longer term trend. - The
**EARTH**model has a trend that is more representative of the near-term trend. - The
**PROPHET**model has a trend that is very similar to the EARTH model (this is because both modeling algorithms use changepoints to model trend, and prophet’s auto algorithm seems to be doing a better job at adapting). - The
**ETS**model has changed from (M,A,A) to (A,A,A). - The
**ARIMA**model have been updated and better capture the upswing.

**This is the (potential) benefit of refitting.**

More often than not refitting is a good idea. Refitting:

- Retrieves your model and preprocessing steps
- Refits the model to the new data
- Recalculates any automations. This includes:
- Recalculating the long-term trend for Linear Model
- Recalculating the changepoints for the Earth Model
- Recalculating the ARIMA and ETS parameters

- Preserves any parameter selections. This includes:
- XGBoost Parameters in the Boosted ARIMA
`min_n = 2`

,`learn_rate = 0.015`

. - Any other defaults that are not automatic calculations are used.

- XGBoost Parameters in the Boosted ARIMA

# Have questions on using Modeltime for time series?

Make a comment in the chat below. 👇

And, if you plan on using `modeltime`

for your business, it’s a no-brainer - Join the Time Series Course.