Prerequesites

This tutorial assumes basic familiarity with StatsForecast. For a minimal example visit the Quick Start

Introduction

Anomaly detection is a crucial task in time series forecasting. It involves identifying unusual observations that don’t follow the expected dataset patterns. Anomalies, also known as outliers, can be caused by a variety of factors, such as errors in the data collection process, sudden changes in the underlying patterns of the data, or unexpected events. They can pose problems for many forecasting models since they can distort trends, seasonal patterns, or autocorrelation estimates. As a result, anomalies can have a significant impact on the accuracy of the forecasts, and for this reason, it is essential to be able to identify them. Furthermore, anomaly detection has many applications across different industries, such as detecting fraud in financial data, monitoring the performance of online services, or identifying usual patterns in energy usage.

By the end of this tutorial, you’ll have a good understanding of how to detect anomalies in time series data using StatsForecast’s probabilistic models.

Outline:

  1. Install libraries
  2. Load and explore data
  3. Train model
  4. Recover insample forecasts and identify anomalies

Important

Once an anomaly has been identified, we must decide what to do with it. For example, we could remove it or replace it with another value. The correct course of action is context-dependent and beyond this notebook’s scope. Removing an anomaly will likely improve the accuracy of the forecast, but it can also underestimate the amount of randomness in the data.

Tip

You can use Colab to run this Notebook interactively

Open In Colab

Install libraries

We assume that you have StatsForecast already installed. If not, check this guide for instructions on how to install StatsForecast

Install the necessary packages using pip install statsforecast

pip install statsforecast -U

Load and explore the data

For this example, we’ll use the hourly dataset of the M4 Competition. We’ll first import the data from datasetsforecast, which you can install using pip install datasetsforecast

pip install datasetsforecast -U
from datasetsforecast.m4 import M4

The function to load the data is M4.load. It requieres the following two arguments:

  • directory: (str) The directory where the data will be downloaded.
  • group: (str). The group name, which can be Yearly, Quarterly, Monthly, Weekly, Daily or Hourly.

This function returns multiple outputs, but only the first one with the target series is needed.

df_total, *_ = M4.load('./data', 'Hourly')
df_total.head()
unique_iddsy
0H11605.0
1H12586.0
2H13586.0
3H14559.0
4H15511.0

The input to StatsForecast is always a data frame in long format with three columns: unique_id, df and y.

  • unique_id: (string, int or category) A unique identifier for the series.
  • ds: (datestamp or int) A datestamp in format YYYY-MM-DD or YYYY-MM-DD HH:MM:SS or an integer indexing time.
  • y: (numeric) The measurement we wish to forecast.

In this case, the unique_id and y columns already have the requiered format, but we need to change the data type of the ds column.

df_total['ds'] = df_total['ds'].astype(int)

From this dataset, we’ll select the first 8 time series to reduce the total execution time. You can select any number you want by changing the value of n_series.

n_series = 8 
uids = df_total['unique_id'].unique()[:n_series]
df = df_total.query('unique_id in @uids')

We can plot these series using the plot method from the StatsForecast class. This method has multiple parameters, and the required ones to generate the plots in this notebook are explained below.

  • df: A pandas dataframe with columns [unique_id, ds, y].
  • forecasts_df: A pandas dataframe with columns [unique_id, ds] and models.
  • unique_ids: (list[str]) A list with the ids of the time series we want to plot.
  • plot_random: (bool = True) Plots the time series randomly.
  • plot_anomalies: (bool = False) Plots anomalies for each prediction interval.
  • engine: (str = plotly). The library used to generate the plots. It can also be matplotlib for static plots.
from statsforecast import StatsForecast
StatsForecast.plot(df, plot_random = False)

Train model

To generate the forecast, we’ll use the MSTL model, which is well-suited for low-frequency data like the one used here. We first need to import it from statsforecast.models and then we need to instantiate it. Since we’re using hourly data, we have two seasonal periods: one every 24 hours (hourly) and one every 24*7 hours (daily). Hence, we need to set season_length = [24, 24*7].

from statsforecast.models import MSTL

# Create a list of models and instantiation parameters 
models = [MSTL(season_length = [24, 24*7])]

To instantiate a new StatsForecast object, we need the following parameters:

  • df: The dataframe with the training data.
  • models: The list of models defined in the previous step.
  • freq: A string indicating the frequency of the data. See pandas’ available frequencies.
  • n_jobs: An integer that indicates the number of jobs used in parallel processing. Use -1 to select all cores.
sf = StatsForecast(
    df = df, 
    models = models, 
    freq = 'H', 
    n_jobs = -1
)

We’ll now predict the next 48 hours. To do this, we’ll use the forecast method, which requieres the following arguments:

  • h: (int) The forecasting horizon.
  • level: (list[float]) The confidence levels of the prediction intervals
  • fitted: (bool = False) Returns insample predictions.

It is important that we select a level and set fitted = True since we’ll need the insample forecasts and their prediction intervals to detect the anomalies.

horizon = 48
levels = [99] 

fcst = sf.forecast(h = 48, level = levels, fitted = True)
fcst = fcst.reset_index()
fcst.head()
unique_iddsMSTLMSTL-lo-99MSTL-hi-99
0H1749615.943970597.662170634.225708
1H1750559.297791531.316650587.278931
2H1751515.693542479.151337552.235718
3H1752480.719269436.241547525.197021
4H1753467.146484415.199738519.093262

We can plot the forecasts using the plot method from before.

StatsForecast.plot(df, fcst, plot_random = False)

Recover insample forecasts and identify anomalies

In this example, an anomaly will be any observation outside the prediction interval of the insample forecasts for a given confidence level (here we selected 99%). Hence, we first need to recover the insample forecasts using the forecast_fitted_values method.

insample_forecasts = sf.forecast_fitted_values().reset_index()
insample_forecasts.head()
unique_iddsyMSTLMSTL-lo-99MSTL-hi-99
0H11605.0604.924500588.010376621.838623
1H12586.0585.221802568.307678602.135925
2H13586.0589.740723572.826599606.654846
3H14559.0557.778076540.863953574.692200
4H15511.0506.747009489.832886523.661133

We can now find all the observations above or below the 99% prediction interval for the insample forecasts.

anomalies = insample_forecasts.loc[(insample_forecasts['y'] >= insample_forecasts['MSTL-hi-99']) | (insample_forecasts['y'] <= insample_forecasts['MSTL-lo-99'])]
anomalies.head()
unique_iddsyMSTLMSTL-lo-99MSTL-hi-99
168H1169813.0779.849792762.935669796.763916
279H1280692.0672.638123655.723999689.552246
289H1290770.0792.015442775.101318808.929565
308H1309844.0867.809387850.895203884.723511
336H1337853.0822.427002805.512878839.341187

We can plot the anomalies by adding the plot_anomalies = True argument to the plot method.

StatsForecast.plot(insample_forecasts, plot_random = False, plot_anomalies = True)

If we want to take a closer look, we can use the unique_ids argument to select one particular time series, for example, H10.

StatsForecast.plot(insample_forecasts, unique_ids = ['H10'], plot_anomalies = True)

Here we identified the anomalies in the data using the MSTL model, but any probabilistic model from StatsForecast can be used. We also selected the 99% prediction interval of the insample forecasts, but other confidence levels can be used as well.