library(tsibble)
library(fable)
library(feasts)
library(ggtime)
library(broom)
library(tsibbledata)12 Time series data
For this chapter, we will load some additional packages designed to work with time series data. To learn more about these packages and their use in time series analysis, see Hyndman & Athanasopoulos (2021).
12.1 Time series anomaly detection paradigms
Time series data are observations that are collected over time. This book considers only time series that are observed at regular intervals, such as annually, monthly, or hourly; irregularly timed event and log data are considered in Chapter 17.
When considering time series data, we can distinguish between three different anomaly detection paradigms:
- Weird times: Identifying anomalies within a time series in historical data.
- Weird series: Identifying an anomalous time series within a collection of time series.
- Surveillance: Identifying anomalies within a time series in real time.
These can be illustrated using the following examples.
Weird times: In the top plot, we are looking for historical anomalies within time series data. This is common in quality control, or in data cleaning. The aim is to find time periods where the observations are different from the rest of the data. This can easily be extended to multivariate time series, where we look for time periods when one or more of the series may display unusual observations.
Weird series: In the middle plot, we are looking for an anomalous time series within a collection of time series. The observations within each series may all be consistent, but the series as a whole may be unusual. This is, by its nature, a multivariate problem. It is common in finance, where we look for unusual behaviour of a stock within a collection of stocks, or in health, where we look for unusual behaviour of a patient within a collection of patients.
Surveillance: In the bottom plot, we are looking for an anomaly in the next observation in the time series. This is commonly done in surveillance, when a time series is monitored in real time to identify an unusual observation, and appropriate action taken. An anomaly in this context is an observation that is very different from what was forecast. Although only a single time series is shown in this plot, the idea easily extends to multivariate time series, where we look for something unusual occurring in the next time period across a set of time series.
Each of these paradigms is discussed in turn.
12.2 Weird times
As a vehicle of illustration, we will consider French mortality rates, disaggregated by age and sex. These are obtained from the Human Mortality Database (2024). We will consider male and female data from 1816 to 1999 over ages 0 to 85, giving 172 separate time series, each of length 184. In fact, the top plot in Figure 12.1 shows the male mortality rates for 25-year-olds over this time period.
fr_mortality# A tibble: 31,648 × 4
Year Age Sex Mortality
<int> <int> <chr> <dbl>
1 1816 0 Female 0.187
2 1816 1 Female 0.0467
3 1816 2 Female 0.0339
4 1816 3 Female 0.0229
5 1816 4 Female 0.0160
6 1816 5 Female 0.0138
7 1816 6 Female 0.0121
8 1816 7 Female 0.0104
9 1816 8 Female 0.00891
10 1816 9 Female 0.00760
# ℹ 31,638 more rows
Figure 12.2 shows the data for both sexes and all ages. The mortality rates have improved over time for all ages, especially since 1950. Infant mortality (age 0) is much higher than the rest of childhood, with mortality rates at a minimum at about age 10 in most years. The highest mortality rates are for the oldest age groups. The effects of the two wars are particularly evident in the male mortality rates.
fr_mortality |>
ggplot(aes(x = Year, y = Mortality, colour = Age, group = Age)) +
geom_line() +
facet_grid(. ~ Sex) +
scale_y_log10(labels = scales::comma)
Methods for identifying weird times are usually based on fitting a smooth function m_t through the observations, estimating the spread in the series a_t, and computing the standardised residuals e_t = (y_t - m_t)/a_t. We then identify anomalies in the e_t series using one of the methods discussed in Chapter 7 or Chapter 6. To illustrate, we will consider two such approaches, but many more are possible depending on how m_t and a_t are estimated, and how anomalies are identified in e_t.
Hampel identifier
The Hampel identifier is due to a proposal of Frank Hampel (Davies & Gather, 1993), and is designed to identify anomalies in a time series based on whether an observation is very different from the neighbouring observations. Suppose we define neighbourhoods comprising observations within w time periods of time t, so each window contains 2w + 1 observations. Then the local median is given by m_t = \text{median}(y_{t-w}, \dots, y_{t+w}). This is also called a moving median, a running median or a rolling median. Similarly, the local median absolute deviation (MAD) is given by a_t = \text{median}(|y_{t-w} - m_t|, \dots, |y_{t+w} - m_t|). This measures the variation of the series in the neighbourhood of time t. The residuals e_t = (y_t - m_t)/a_t provide a measure for how different an observation y_t is from its neighbours. The Hampel identifier denotes an observation as an anomaly if |e_t| > \tau for some threshold \tau. A related idea is the Hampel filter, where each anomaly is replaced by the local median m_t.
The threshold is often set under the assumption of a Normal distribution, for which the MAD is equal to 0.6745 times the standard deviation. So it is common to set \tau = k/0.6745 where k is the number of standard deviations permitted before an observation is considered an outlier. Then an observation is an anomaly if it lies outside the band m_t \pm k a_t/0.6745.
Code
w <- 7
fr_m25 <- fr_mortality |>
filter(Sex == "Male", Age == 25) |>
arrange(Year)
y <- fr_m25$Mortality
n <- length(y)
# Moving median and moving MAD (not defined within w of either end)
m <- stats::runmed(y, 2 * w + 1, endrule = "keep")
a <- rep(NA_real_, n)
for (i in (w + 1):(n - w)) {
a[i] <- median(abs(y[(i - w):(i + w)] - m[i]))
}
fr_m25 <- fr_m25 |>
mutate(
m = m,
lower = m - 3 * a / 0.6745,
upper = m + 3 * a / 0.6745,
anomaly = hampel_anomalies(Mortality, bandwidth = w, k = 3)
)
fr_m25 |>
ggplot(aes(x = Year)) +
geom_ribbon(
data = fr_m25 |> filter(!is.na(lower)),
aes(ymin = lower, ymax = upper),
fill = "#0072B2",
alpha = 0.2
) +
geom_line(aes(y = Mortality)) +
geom_line(aes(y = m), colour = "#0072B2") +
geom_point(
data = fr_m25 |> filter(anomaly),
aes(y = Mortality),
colour = "#D55E00"
) +
labs(y = "Mortality rate")
Figure 12.3 shows the result for French males aged 25, using w = 7 and k = 3. The band is narrow when the series is smooth, and wide when it varies a lot, because a_t measures the local variation. The anomalies include the Franco-Prussian war (1870–1871), and both world wars.
Because we apply the rule repeatedly over the length of a time series, we need to be careful of the problem of multiple comparisons, where the probability of a false positive overall is much larger than the probability of a false positive for each individual test. However, it is not straightforward to adjust the probabilities because the tests are not independent, and the dependence between them is determined by the window half-width w and the characteristics of the time series. The hampel_anomalies() function implements this algorithm.
The implied statistical model is y_t \sim \text{N}(\mu_t, \sigma_t^2), where \mu_t is estimated as m_t, and \sigma_t is estimated as a_t/0.6745. Using this model, we can apply the surprisal probability approach to identify anomalies, as discussed in Chapter 7. A threshold of k = 3, for example, is equivalent to a surprisal probability threshold of \alpha = 0.0027. Rather than using the Normal distribution, we can use a GPD approximation to the tail of the distribution, as discussed in Section 7.3. That is, the Normal distribution is used to compute the surprisals, but the GPD is used to compute their probabilities. Then we would specify the threshold as a probability \alpha rather than a number of standard deviations k.
The code below applies the algorithm to all 172 time series in fr_mortality. The bandwidth argument corresponds to w, and we set w = 7 and \alpha = 0.01.
fr_anomalies <- fr_mortality |>
group_by(Age, Sex) |>
mutate(
hampel = hampel_anomalies(
Mortality,
bandwidth = 7,
alpha = 0.01,
approximation = "gpd"
)
) |>
ungroup() |>
filter(hampel) |>
arrange(Year, Age)
fr_anomalies# A tibble: 328 × 5
Year Age Sex Mortality hampel
<int> <int> <chr> <dbl> <lgl>
1 1832 40 Female 0.0167 TRUE
2 1832 42 Female 0.0171 TRUE
3 1832 43 Male 0.0162 TRUE
4 1832 44 Male 0.0171 TRUE
5 1832 45 Female 0.0174 TRUE
6 1832 47 Female 0.0191 TRUE
7 1832 49 Female 0.0206 TRUE
8 1832 50 Female 0.0217 TRUE
9 1832 50 Male 0.0229 TRUE
10 1832 51 Male 0.0240 TRUE
# ℹ 318 more rows
Figure 12.4 shows the 328 observations (out of 31648) that have been identified as anomalies. Because we set \alpha = 0.01, there will be occasional spurious anomalies; the interesting years are those with multiple anomalies, as that is unlikely to occur by chance, and usually correspond to wars or epidemics. In Figure 12.4, we only show anomalies if there are at least three anomalies in that year/sex combination.
Code
# Find years containing anomalies
yrs <- fr_anomalies |>
count(Year, Sex) |>
filter(n >= 3)
fr_anomalies_plot_male2 <- fr_anomalies |>
filter(Sex == "Male", Year %in% yrs$Year[yrs$Sex == "Male"]) |>
ggplot(aes(x = Year, y = Age)) +
facet_grid(. ~ Sex) +
scale_x_continuous(
breaks = seq(1820, 2000, by = 20),
limits = range(yrs$Year)
) +
geom_vline(
xintercept = unique(yrs$Year[yrs$Sex == "Male"]),
alpha = 0.5,
colour = "grey"
) +
geom_point(col = "#478cb2") +
ggrepel::geom_text_repel(
data = yrs[yrs$Sex == "Male", ],
#yrs |> filter(Sex == "Male", !Year %in% 1915:1918),
aes(y = 95, label = Year),
col = "#478cb2",
size = 3,
seed = 1967
) +
ylim(0, 100)
fr_anomalies_plot_female2 <- fr_anomalies |>
filter(Sex == "Female", Year %in% yrs$Year[yrs$Sex == "Female"]) |>
ggplot(aes(x = Year, y = Age)) +
facet_grid(. ~ Sex) +
scale_x_continuous(
breaks = seq(1820, 2000, by = 20),
limits = range(yrs$Year)
) +
geom_vline(
xintercept = unique(yrs$Year[yrs$Sex == "Female"]),
alpha = 0.5,
colour = "grey"
) +
labs(title = "French mortality anomalies") +
geom_point(col = "#c1653a") +
ggrepel::geom_text_repel(
data = yrs[yrs$Sex == "Female", ],
aes(y = 95, label = Year),
col = "#c1653a",
size = 3,
seed = 1967
) +
ylim(0, 100)
patchwork::wrap_plots(
fr_anomalies_plot_female2,
fr_anomalies_plot_male2,
nrow = 1
)
The following events in French history are evident in the data:
- 1832, 1849: Cholera outbreaks (Bourdelais & Raulot, 1987)
- 1870: Franco-Prussian war
- 1871: Repression of the ‘Commune de Paris’
- 1914, 1915: World War I
- 1918: Spanish flu outbreak, in the last year of World War I
- 1940: World War II
There also appear to be a couple of additional years involving significant mortality events, whose cause is unknown: there is unusually high infant and child mortality in 1834, and unusually high elder mortality in 1837. I was unable to find any information about these events, but it is possible that they were due to epidemics that have long been forgotten.
Surprisal anomalies
The Hampel identifier worked well for the annual mortality series, but the local median approach will break down when there is seasonality or other systematic patterns in the data. However, the same idea can be adapted by replacing the local median with a more sophisticated way of modelling the signal in the data. One such method is STL (Seasonal and Trend decomposition using Loess) due to Cleveland et al. (1990), and extended by Bandara et al. (2025) to handle multiple seasonal periods or series with no seasonality.
We will apply this idea to find unusual observations in US weekly mortality data between 2015 and 2025, obtained from the Human Mortality Database (2024). The us_mortality data set in the weird package contains weekly deaths and death rates by sex and age group. We use the death rates for both sexes combined, in five age groups, and convert them to a tsibble object (a special type of tibble designed for time series data).
Code
us_stmf <- us_mortality |>
filter(Sex == "Total", Age != "Total") |>
# Create time index variable
mutate(Week = yearweek(paste0(Year, "-W", Week))) |>
select(Week, `Age group` = Age, Mortality) |>
as_tsibble(index = Week, key = `Age group`)Figure 12.5 shows the data on five age groups. There appears to be no seasonality in the 0–14 age group, but all other age groups have seasonal peaks around the start of January each year due to winter illnesses, with the seasonal strength increasing with age. There is a noticeable change in mortality rates during 2020, 2021 and the start of 2022. This is due to COVID-19.
us_stmf |>
autoplot(Mortality) +
facet_grid(`Age group` ~ ., scales = "free_y")
Next, we apply an STL model to the mortality rates in each age group. This helps separate out the regular seasonality from any unusual fluctuations.
stmf_fit <- us_stmf |>
model(stl = STL(Mortality)) |>
augment() |>
as_tibble() |>
select(-.model, -.innov)
stmf_fit# A tibble: 2,865 × 5
`Age group` Week Mortality .fitted .resid
<chr> <week> <dbl> <dbl> <dbl>
1 0-14 2015 W02 0.000522 0.000536 -0.0000138
2 0-14 2015 W03 0.000537 0.000527 0.00000996
3 0-14 2015 W04 0.000532 0.000528 0.00000330
4 0-14 2015 W05 0.000526 0.000531 -0.00000537
5 0-14 2015 W06 0.000494 0.000528 -0.0000334
6 0-14 2015 W07 0.000528 0.000537 -0.00000934
7 0-14 2015 W08 0.000530 0.000539 -0.00000871
8 0-14 2015 W09 0.000522 0.000526 -0.00000372
9 0-14 2015 W10 0.000503 0.000542 -0.0000383
10 0-14 2015 W11 0.000506 0.000533 -0.0000271
# ℹ 2,855 more rows
The .fitted column contains m_t, and the .resid column contains estimates of y_t - m_t, where m_t takes account of any seasonality in the data. We will estimate the spread a_t using the robust Q_n estimator (Section 2.8), which is scaled to be equivalent to a standard deviation if the data were Normally distributed. A separate estimate of spread is needed for each age group because the mortality rates are so different.
stmf_scores <- stmf_fit |>
group_by(`Age group`) |>
mutate(e = .resid / robustbase::s_Qn(.resid)) |>
ungroup()
stmf_scores# A tibble: 2,865 × 6
`Age group` Week Mortality .fitted .resid e
<chr> <week> <dbl> <dbl> <dbl> <dbl>
1 0-14 2015 W02 0.000522 0.000536 -0.0000138 -0.684
2 0-14 2015 W03 0.000537 0.000527 0.00000996 0.493
3 0-14 2015 W04 0.000532 0.000528 0.00000330 0.163
4 0-14 2015 W05 0.000526 0.000531 -0.00000537 -0.266
5 0-14 2015 W06 0.000494 0.000528 -0.0000334 -1.65
6 0-14 2015 W07 0.000528 0.000537 -0.00000934 -0.463
7 0-14 2015 W08 0.000530 0.000539 -0.00000871 -0.431
8 0-14 2015 W09 0.000522 0.000526 -0.00000372 -0.184
9 0-14 2015 W10 0.000503 0.000542 -0.0000383 -1.90
10 0-14 2015 W11 0.000506 0.000533 -0.0000271 -1.34
# ℹ 2,855 more rows
At this point, we could identify a point as an anomaly if |e_t| is greater than some threshold, as was done with the Hampel identifier. But surprisals with probabilities calculated using a GPD are used here instead, as this is a safer calculation making fewer assumptions about the distribution of the residuals.
stmf_scores <- stmf_scores |>
mutate(
prob = surprisals_prob(
e,
distribution = dist_normal(),
approximation = "gpd"
)
) |>
filter(prob < 0.02)
stmf_scores |> arrange(prob)# A tibble: 67 × 7
`Age group` Week Mortality .fitted .resid e prob
<chr> <week> <dbl> <dbl> <dbl> <dbl> <dbl>
1 85+ 2020 W16 0.202 0.154 0.0478 9.22 0.00174
2 75-84 2020 W15 0.0617 0.0480 0.0136 8.77 0.00208
3 85+ 2020 W15 0.200 0.155 0.0451 8.71 0.00213
4 15-64 2021 W36 0.00543 0.00441 0.00102 8.30 0.00251
5 65-74 2020 W15 0.0248 0.0194 0.00535 8.23 0.00259
6 75-84 2020 W16 0.0600 0.0472 0.0128 8.20 0.00262
7 85+ 2020 W17 0.193 0.151 0.0414 8.00 0.00285
8 15-64 2021 W35 0.00538 0.00441 0.000969 7.89 0.00299
9 15-64 2021 W37 0.00528 0.00435 0.000933 7.60 0.00341
10 75-84 2020 W53 0.0696 0.0581 0.0114 7.35 0.00382
# ℹ 57 more rows
us_stmf |>
autoplot(Mortality) +
facet_grid(`Age group` ~ ., scales = "free_y") +
geom_point(data = stmf_scores)
Figure 12.6 shows the identified anomalies. A total of 67 observations have surprisal probabilities less than 0.02, with the most extreme being in weeks 15–16 of 2020, in the elderly age groups. Although the test can pick up unusually low or unusually high mortality rates, only 6 of the 67 identified anomalies are for low mortality: three in weeks 3–4 of 2020, for those aged 75 and over, and three in weeks 13 and 15 of 2021, which are discussed later in this section.
The 2020 anomalies occurred weeks before COVID-19 led to any restrictions on movement in the US, which began in March 2020. In fact, the mortality rates in those weeks were almost the same as in the same weeks of 2019. These anomalies are an artefact of the STL decomposition: the trend is pulled upwards by the very large COVID-19 peak a few weeks later, so the January observations lie well below the estimated trend. If the STL decomposition is applied only to data up to early March 2020, these weeks are no longer flagged as anomalous.
There are four anomalous peaks in the plot, each corresponding to a major wave of COVID-19 in the US:
- 2020 W14 – W18: the first wave, centred on New York in April 2020;
- 2020 W49 – 2021 W03: the winter wave of 2020–21, the deadliest of the pandemic in the US;
- 2021 W33 – W39: the Delta wave of late summer 2021;
- 2022 W02 – W05: the Omicron wave of early 2022.
These waves affected the age groups differently. The first wave produced anomalously high mortality in every adult age group, while in the winter 2020–21 wave and the Omicron wave, the anomalies were mostly in those aged 65 and over. In contrast, the Delta wave produced anomalies only in the 15–64 and 65–74 age groups. By then, most older people had been vaccinated, and deaths from the Delta variant were concentrated among younger, unvaccinated adults. No anomalies were identified in the 0–14 age group.
Multivariate time series
The above analysis treats each series separately, and seeks to find anomalies within each series, regardless of the behaviour of related series. To take account of all series simultaneously, we need to take a multivariate approach, where we are looking for time periods that are anomalous across multiple series. One way to do this is to first take principal components of the series, and then apply the preceding procedure to the series of first principal component scores.
First we convert the series to logs as they are on vastly different scales, then we transform the data to wide form. Finally, we compute the first principal component of the resulting matrix.
# Convert to wide form
us_wide <- us_stmf |>
as_tibble() |>
mutate(logm = log(Mortality)) |>
tidyr::pivot_wider(
id_cols = Week,
names_from = `Age group`,
values_from = logm
)
# Compute 1 principal component from mortality rates
pcs <- us_wide |>
select(-Week) |>
prcomp(rank = 1) |>
broom::augment(us_wide |> select(Week))The resulting series is plotted in Figure 12.7, and shows strong seasonality, along with large peaks during the periods of COVID-19 outbreaks. Now we can apply an STL model to find anomalies in this series. There is no need to scale the residuals because there is only one series.
pc_anomalies <- pcs |>
as_tsibble(index = Week) |>
model(stl = STL(.fittedPC1)) |>
augment() |>
select(-.model, -.innov) |>
mutate(
prob = surprisals_prob(
.resid,
distribution = dist_normal(),
approximation = "gpd"
)
) |>
filter(prob < 0.05)
pc_anomalies# A tsibble: 32 x 5 [1W]
Week .fittedPC1 .fitted .resid prob
<week> <dbl> <dbl> <dbl> <dbl>
1 2020 W01 0.0812 0.297 -0.215 0.0448
2 2020 W02 0.0991 0.310 -0.211 0.0477
3 2020 W03 0.0508 0.302 -0.251 0.0268
4 2020 W04 0.0468 0.277 -0.230 0.0364
5 2020 W05 0.0366 0.252 -0.216 0.0447
6 2020 W14 0.468 0.129 0.339 0.00764
7 2020 W15 0.638 0.158 0.479 0.00123
8 2020 W16 0.581 0.131 0.450 0.00177
9 2020 W17 0.494 0.110 0.383 0.00417
10 2020 W18 0.377 0.0998 0.277 0.0183
# ℹ 22 more rows
# Plot principal component scores
pcs |>
ggplot(aes(x = Week, y = .fittedPC1)) +
geom_line() +
labs(y = "First principal component scores") +
geom_point(data = pc_anomalies, colour = "#D55E00")
As expected, many of the same weeks identified earlier in an analysis of individual series have been returned. The probability of false positives increases with both the length of each series and the number of series. Because there is now only one series rather than five, we have used a larger probability threshold here (0.05) than in the analysis of individual series (0.02). Conversely, some anomalies might appear to be marginal in the individual series, but when the series are combined like this, the anomalous periods may be clearer. For example, weeks 3 and 4 of 2020 are flagged here, whereas the earlier analysis only flagged week 3 of 2020 for 85+ year olds. However, as noted above, these low values are an artefact of the STL trend being pulled upwards by the COVID-19 peak that followed a few weeks later.
Unusually low mortality rates have also been identified in weeks 13 and 15 of 2021. In those weeks, the mortality rate for 85+ year olds was lower than in the same weeks of any year from 2016 to 2019. There are several possible explanations: restricted movements, especially of older people; vaccination, as older people were among the first to be vaccinated against COVID-19 in early 2021; and mortality displacement, as many of the frailest older people had died during the COVID-19 wave of the preceding winter.
12.3 Weird series
Next we consider unusual series within a large collection of time series.
Comparing whole time series directly is awkward, because the series can have very different scales and lengths, and two series with similar behaviour may be offset in time. Instead, we summarise each series by a vector of features: statistics computed from the series, such as the strength of trend and seasonality, autocorrelations, spectral entropy, and the size of level shifts (Hyndman et al., 2015; Hyndman & Athanasopoulos, 2021, Ch. 4). Each series then becomes a single point in feature space, and finding a weird series becomes a multivariate anomaly detection problem, for which we can use any of the methods of the preceding chapters. Most of these features do not depend on the scale of the series, so a series is identified as anomalous because of its shape and dynamics, rather than its size. The choice of features determines what kind of “unusual” we can detect; a series that is unusual in some way that is not captured by any feature will not be deemed anomalous.
To illustrate the ideas, consider a data set of monthly observations on the Australian Pharmaceutical Benefits Scheme (PBS), from July 1991 to June 2008. The PBS involves the Australian government subsidising certain pharmaceutical products, to allow more equitable access to essential medicines. The data set contains monthly sales volumes of those products being subsidised, classified according to the Anatomical Therapeutic Chemical (ATC) classification system, by the type of government subsidy, and by whether the purchaser was in a concession group (such as pensioner, unemployed, etc.). There are 336 separate time series contained in the PBS data set.
Three series, chosen at random, are shown in Figure 12.8. The two “Safety net” series count scripts dispensed under the PBS safety net, which applies once a patient’s spending in a calendar year passes a threshold; so they rise through each year and drop sharply in January, when the threshold resets. The other series has a strong trend, with a jump in 2002, but little seasonality. The series are on very different scales, from a few hundred scripts a month to more than 100,000.
set.seed(1967)
pbs_sample <- PBS |>
as_tibble() |>
distinct(Concession, Type, ATC2) |>
slice_sample(n = 3)
PBS |>
semi_join(pbs_sample, by = c("Concession", "Type", "ATC2")) |>
autoplot(Scripts) +
facet_grid(vars(Concession, Type, ATC2), scales = "free_y") +
guides(colour = "none")
For each of the 336 series, we compute all the features available in the feasts package.
# Compute features
PBS_feat <- PBS |>
features(Scripts, feature_set(pkgs = "feasts"))
# Keep series with no missing features
PBS_feat_nomissing <- PBS_feat |> na.omit()
PBS_feat_nomissing# A tibble: 333 × 51
Concession Type ATC2 trend_strength seasonal_strength_year
<chr> <chr> <chr> <dbl> <dbl>
1 Concessional Co-payments A01 0.845 0.918
2 Concessional Co-payments A02 0.970 0.943
3 Concessional Co-payments A03 0.956 0.931
4 Concessional Co-payments A04 0.790 0.930
5 Concessional Co-payments A05 0.950 0.888
6 Concessional Co-payments A06 0.952 0.955
7 Concessional Co-payments A07 0.804 0.920
8 Concessional Co-payments A09 0.900 0.901
9 Concessional Co-payments A10 0.975 0.952
10 Concessional Co-payments A11 0.963 0.881
# ℹ 323 more rows
# ℹ 46 more variables: seasonal_peak_year <dbl>, seasonal_trough_year <dbl>,
# spikiness <dbl>, linearity <dbl>, curvature <dbl>, stl_e_acf1 <dbl>,
# stl_e_acf10 <dbl>, acf1 <dbl>, acf10 <dbl>, diff1_acf1 <dbl>,
# diff1_acf10 <dbl>, diff2_acf1 <dbl>, diff2_acf10 <dbl>, season_acf1 <dbl>,
# pacf5 <dbl>, diff1_pacf5 <dbl>, diff2_pacf5 <dbl>, season_pacf <dbl>,
# zero_run_mean <dbl>, nonzero_squared_cv <dbl>, zero_start_prop <dbl>, …
This gives 48 features for each series. The three series for which some features are missing are omitted for now; we return to them below. Figure 12.9 shows four of the features: the strength of the trend and of the seasonality (each between 0 and 1), the spectral entropy (close to 1 for a series with no predictable pattern), and the first autocorrelation coefficient. Most series have strong trend and seasonality, spectral entropy well below 1, and high autocorrelation. A few series are at the opposite extreme on all four features, behaving almost like white noise.
PBS_feat_nomissing |>
select(trend_strength, seasonal_strength_year, spectral_entropy, acf1) |>
GGally::ggpairs(
columnLabels = c("Trend", "Seasonality", "Spectral entropy", "ACF1"),
lower = list(continuous = GGally::wrap("points", size = 0.6, alpha = 0.5))
) +
scale_x_continuous(breaks = c(0, 0.5, 1))
With 48 features, plots like this cannot show all the information. We reduce them to the first two principal components (Section 9.4) after scaling each feature to have unit variance.
# Compute principal components
PBS_prcomp <- PBS_feat_nomissing |>
select(where(is.numeric)) |>
prcomp(scale = TRUE, rank = 2) |>
augment(PBS_feat_nomissing)# Plot the first two components
PBS_prcomp |>
ggplot(aes(x = .fittedPC1, y = .fittedPC2)) +
geom_point() +
labs(x = "Principal component 1", y = "Principal component 2")
In Figure 12.10, there are two series which are clearly separated from the rest, with principal component 2 less than -15. Although it is not necessary here, because these two anomalies are so obvious, we can confirm them using KDE surprisal probabilities.
PBS_prcomp <- PBS_prcomp |>
mutate(
prob = surprisals_prob(
PBS_prcomp |> select(.fittedPC1, .fittedPC2),
loo = TRUE,
approximation = "gpd"
)
) |>
select(Concession, Type, ATC2, .fittedPC1, .fittedPC2, prob) |>
arrange(prob)
PBS_prcomp# A tibble: 333 × 6
Concession Type ATC2 .fittedPC1 .fittedPC2 prob
<chr> <chr> <chr> <dbl> <dbl> <dbl>
1 Concessional Safety net J06 7.05 -17.9 0
2 General Co-payments C05 8.51 -23.0 0
3 General Co-payments S02 5.54 -11.5 0
4 General Co-payments R06 3.47 -6.23 0.00149
5 General Safety net D11 2.58 -3.66 0.00349
6 General Safety net V01 4.96 -2.49 0.00420
7 General Co-payments A15 -1.15 -8.86 0.00706
8 Concessional Co-payments R -4.22 -4.86 0.0175
9 General Co-payments A01 -1.10 -3.87 0.0185
10 General Co-payments D04 -3.25 -6.54 0.0249
# ℹ 323 more rows
This shows both have zero surprisal probability, along with a third series along the same line of points.
Now, let’s plot these most anomalous series in Figure 12.11, to see if we can spot what is so unusual about them.
# Pull out most unusual series using the first principal component
outliers <- PBS_prcomp |> filter(prob < 0.001)
# Visualise the unusual series
PBS |>
semi_join(outliers, by = c("Concession", "Type", "ATC2")) |>
autoplot(Scripts) +
facet_grid(vars(Concession, Type, ATC2), scales = "free_y") +
labs(title = "Outlying time series in PC space")
Two of these series contain almost all zeros, with just a few non-zero values (one of which is very large in the C05 series). The other contains almost all zeros or ones, with only two larger values. The three series we omitted may also be unusual, so let’s plot them as well in Figure 12.12.
missing <- PBS_feat |>
anti_join(PBS_feat_nomissing) |>
select(ATC2, Type, Concession)
# Visualise the series with missing features
PBS |>
semi_join(missing, by = c("Concession", "Type", "ATC2")) |>
autoplot(Scripts) +
facet_grid(vars(Concession, Type, ATC2), scales = "free_y") +
labs(title = "Time series with missing features") +
theme(panel.spacing = unit(1, "lines"))
Similarly, one of these series contains only zeros apart from in one month. The other two contain only zeros for the period when observations were recorded.
12.4 Surveillance
In surveillance, we are interested in identifying anomalies in real time, either within one series or across several time series. This is common in monitoring systems, where we want to identify unusual behaviour as soon as it occurs. For example, in a manufacturing plant, we may want to identify when a machine is not operating as expected, and take action to prevent further problems. In retail, we may want to identify when sales are unusually high or low, and adjust stock levels if necessary.
Again, we will use the PBS data. For this example, we will combine the data into the ATC level 2 groups, and look at total sales volumes (measured in thousands of scripts). The resulting data set contains 84 separate time series, one for each ATC2 value.
pbs <- PBS |>
arrange(ATC2, Month) |>
group_by(ATC2) |>
summarise(Scripts = sum(Scripts) / 1e3, .groups = "drop") |>
mutate(t = as.numeric(Month - min(Month) + 1))
pbs# A tsibble: 17,016 x 4 [1M]
# Key: ATC2 [84]
ATC2 Month Scripts t
<chr> <mth> <dbl> <dbl>
1 A01 1991 Jul 22.6 1
2 A01 1991 Aug 20.4 2
3 A01 1991 Sep 21.4 3
4 A01 1991 Oct 23.7 4
5 A01 1991 Nov 23.5 5
6 A01 1991 Dec 26.3 6
7 A01 1992 Jan 22.0 7
8 A01 1992 Feb 16.4 8
9 A01 1992 Mar 17.2 9
10 A01 1992 Apr 18.8 10
# ℹ 17,006 more rows
Let’s first look at the time series for just one ATC group: A12 (Mineral supplements). In fact, this is the same series as was shown in the bottom panel of Figure 12.1.
pbs |>
filter(ATC2 == "A12") |>
autoplot(Scripts) +
labs(title = "Scripts for ATC group A12 (Mineral supplements)")
In Figure 12.13, there has been a sudden drop in sales at the start of 2006, most likely because of some products no longer being eligible for subsidy. There can also be sudden jumps in sales when a new product becomes available, or a new class of drugs is added to the scheme.
The surveillance algorithm
The goal of surveillance is to identify these anomalies as soon as they occur. We can do this by fitting a model to the data, and then comparing the observed values to the model’s forecasts. If the observed values are very different from the forecast, then we have an anomaly.
Statistical forecasting models provide forecasts in the form of probability distributions. Let y_t denote the observation of a time series at time t. Then a forecast can be expressed as a conditional distribution f(y_{t+h} \mid y_1, \dots, y_{t}, \bm{x}_t), where y_1,\dots,y_t denotes the observed history of the series, and \bm{x}_t contains any other information available at time t that is used in the model. The forecast “horizon” is given by h, denoting the number of time periods into the future that we wish to forecast. Different forecasting methods use different conditioning information, and result in a different form of the forecast distribution. See Hyndman & Athanasopoulos (2021) for a detailed discussion of forecasting methods.
Once we observe the value of y_{t+h}, we can calculate the corresponding surprisal probability in the same way as discussed in Section 7.2. Because we are interested in real-time surveillance, we need only consider the one-step-ahead forecast density, f(y_{t+1} \mid y_1, \dots, y_{t}, \bm{x}_t). We can then calculate the surprisal as s_{t+1} = -\log f(y_{t+1} \mid y_1, \dots, y_{t}, \bm{x}_t). This needs to be done iteratively for each time period, updating the model as new data become available. Since we need some observations with which to fit a model, we can’t begin the process at time t = 1. Instead, we’ll begin at time t = I, where I is the smallest number of observations with which we can reasonably estimate the time series model. The value of I will depend on the complexity of the model being used. For simple models with few parameters, we may be able to set I to around 20, but for complex models with many parameters, I may need to be much larger.
We can summarise the anomaly detection algorithm for surveillance as follows. First, we’ll change the notation slightly to allow for more than one series. Let y_{i,t} denote the observation of the ith series at time t.
For each t = I,I + 1,\dots, and for all series i = 1,\dots,M, where M is the number of series:
- Fit a time series model to the series y_{i,1},\dots,y_{i,t}, and estimate the one-step forecast density, f_{i,t+1}(y \mid y_{i,1},\dots,y_{i,t}, \bm{x}_t).
- Compute the surprisal: s_{i,t+1} = -\log f_{i,t+1}(y_{i,t+1} \mid y_{i,1},\dots,y_{i,t}, \bm{x}_t), and the surprisal probability p_{i,t+1} = \Pr(S \ge s_{i,t+1}), where S = -\log f_{i,t+1}(Y \mid y_{i,1},\dots,y_{i,t}, \bm{x}_t) is the surprisal of a random variable Y drawn from the forecast distribution.
If the forecast distribution is the true distribution of the next observation, then the surprisal probabilities are uniformly distributed on (0,1), by the probability integral transform (Section 2.2) applied to the surprisals. So if we flag observations with p_{i,t+1} < \alpha, each series gives a false alarm with probability \alpha in each time period, and with M series we expect about M\alpha false alarms per period.
Many forecasting models, including the ETS models used below, have Normal forecast distributions. Then the observations with the largest surprisals are those furthest from the forecast mean, so p_{i,t+1} is just the p-value of a two-sided z-test applied to the one-step forecast error (see Section 7.2).
A first iteration
To illustrate, let’s apply this to the pbs data. Starting with I = 36 (3 years of data), we will fit ETS models to all available series (Hyndman & Athanasopoulos, 2021, Ch. 8), and forecast one step ahead in each case. Then we repeat the exercise using 37 observations, then 38 observations, and so on. This is known as a rolling origin forecast because the forecast origin rolls forward by one period each iteration. The process can be illustrated as in Figure 12.14. Two series start later than the others: L03 and A05 have their first non-zero values in December 1992 and November 2000, respectively. We only fit a model to a series once it has at least 36 observations, counting from its first non-zero value.
Let’s step through the process for the first iteration, with t = 36. We fit ETS models to each of the time series, with the specific ETS model selected according to the characteristics of the series. See Hyndman & Athanasopoulos (2021, Ch. 8) for details of how this is done.
pbs_fit <- pbs |>
filter(t <= 36) |>
group_by_key() |>
filter(cumsum(Scripts) > 0) |>
filter(n() >= 36) |>
ungroup() |>
model(ets = ETS(Scripts))
pbs_fit# A mable: 82 x 2
# Key: ATC2 [82]
ATC2 ets
<chr> <model>
1 A01 <ETS(M,N,A)>
2 A02 <ETS(M,A,M)>
3 A03 <ETS(M,A,M)>
4 A04 <ETS(M,N,A)>
5 A06 <ETS(M,A,M)>
6 A07 <ETS(M,N,M)>
7 A09 <ETS(M,A,M)>
8 A10 <ETS(M,A,M)>
9 A11 <ETS(M,A,M)>
10 A12 <ETS(M,N,A)>
# ℹ 72 more rows
Forecasts are produced from all fitted models by applying the forecast() function to the model table.
pbs_fc <- forecast(pbs_fit, h = 1)
pbs_fc# A fable: 82 x 5 [1M]
# Key: ATC2, .model [82]
ATC2 .model Month
<chr> <chr> <mth>
1 A01 ets 1994 Jul
2 A02 ets 1994 Jul
3 A03 ets 1994 Jul
4 A04 ets 1994 Jul
5 A06 ets 1994 Jul
6 A07 ets 1994 Jul
7 A09 ets 1994 Jul
8 A10 ets 1994 Jul
9 A11 ets 1994 Jul
10 A12 ets 1994 Jul
# ℹ 72 more rows
# ℹ 2 more variables: Scripts <dist>, .mean <dbl>
The forecasts are in the Scripts column. Note that each of them is a Normal distribution where the mean and variance have been estimated using the ETS model. The mean of the forecast distribution is given as .mean.
We can combine these forecasts with the observed values from time t = 37.
pbs_compare <- pbs_fc |>
rename(fcast = Scripts) |>
left_join(pbs |> filter(t == 37), by = c("Month", "ATC2")) |>
select(Month, ATC2, Scripts, fcast)
pbs_compare# A tsibble: 82 x 4 [?]
# Key: ATC2 [82]
Month ATC2 Scripts
<mth> <chr> <dbl>
1 1994 Jul A01 20.9
2 1994 Jul A02 516.
3 1994 Jul A03 80.5
4 1994 Jul A04 66.1
5 1994 Jul A06 29.2
6 1994 Jul A07 68.5
7 1994 Jul A09 3.32
8 1994 Jul A10 150.
9 1994 Jul A11 27.8
10 1994 Jul A12 87.9
# ℹ 72 more rows
# ℹ 1 more variable: fcast <dist>
Now we can compute the surprisal probabilities from the observed values (column Scripts) and the forecast distributions (column fcast):
pbs_compare <- pbs_compare |>
mutate(prob = surprisals_prob(Scripts, distribution = fcast)) |>
arrange(prob)
pbs_compare# A tsibble: 82 x 5 [?]
# Key: ATC2 [82]
Month ATC2 Scripts
<mth> <chr> <dbl>
1 1994 Jul S01 347.
2 1994 Jul H02 94.3
3 1994 Jul S02 63.0
4 1994 Jul D07 194.
5 1994 Jul M02 21.6
6 1994 Jul C04 0.248
7 1994 Jul V06 6.77
8 1994 Jul G01 53.7
9 1994 Jul N04 45.3
10 1994 Jul A12 87.9
# ℹ 72 more rows
# ℹ 2 more variables: fcast <dist>, prob <dbl>
The lowest probabilities indicate possible anomalies. Let’s look at the most likely anomaly (or least likely observation), from series S01, shown in Figure 12.15.
Code
s01 <- pbs |> filter(ATC2 == "S01", t <= 37)
pbs_fc |>
filter(ATC2 == "S01") |>
autoplot(s01) +
geom_point(data = s01 |> filter(t == 37), aes(x = Month, y = Scripts)) +
labs(
y = "Scripts (thousands)",
title = "Forecast of S01 scripts: Jul 1994"
) +
theme(legend.position = "none")
The shaded regions show 80% and 95% prediction intervals for the forecast distribution. The observation is outside the 95% prediction interval, indicating that it is a possible anomaly. The surprisal probability in this case is about 0.003.
Rolling forward through the data
So far, we have just produced forecasts for time t = 37, using a training set comprising data up to time t = 36. This process is repeated as we increase the size of the training set. The following code block carries out the calculations in a loop.
compute_pbs_scores <- function(pbs) {
pbs$prob <- NA_real_
# Loop over all time periods starting with I=36
for (i in seq(36, max(pbs$t) - 1)) {
# Fit ETS model to all series with at least 36 observations up to time i
# (counting from each series' first non-zero value) and compute 1-step forecasts
pbs_fc <- pbs |>
filter(t <= i) |>
group_by_key() |>
filter(cumsum(Scripts) > 0) |>
filter(n() >= 36) |>
ungroup() |>
model(ets = ETS(Scripts)) |>
forecast(h = 1) |>
rename(fcast = Scripts)
# Calculate surprisal probabilities from observations in time i+1
pbs_scores <- pbs |>
filter(t == i + 1) |>
right_join(pbs_fc, by = c("Month", "ATC2")) |>
mutate(surprisal_prob = surprisals_prob(Scripts, distribution = fcast)) |>
select(Month, ATC2, surprisal_prob)
# Add probabilities to pbs data set
pbs <- pbs |>
left_join(pbs_scores, by = c("Month", "ATC2")) |>
mutate(prob = if_else(!is.na(surprisal_prob), surprisal_prob, prob)) |>
select(-surprisal_prob)
}
return(pbs)
}pbs_scores <- compute_pbs_scores(pbs)We will identify as anomalies any observations with a surprisal probability less than 1 in 1000. With 84 series observed monthly, this would give about one false alarm a year across all the series, if the forecast distributions were correct.
pbs_anomalies <- pbs_scores |> filter(prob < 0.001)
pbs_anomalies# A tsibble: 267 x 5 [1M]
# Key: ATC2 [80]
ATC2 Month Scripts t prob
<chr> <mth> <dbl> <dbl> <dbl>
1 A01 2004 Mar 14.1 153 0.000812
2 A01 2005 Dec 18.2 174 0.000435
3 A01 2007 Dec 15.5 198 0.0000385
4 A02 2001 Nov 946. 125 0.0000351
5 A02 2008 Feb 1288. 200 0.000000144
6 A03 1998 Jan 93.9 79 0.000919
7 A03 1999 Mar 94.6 93 0.000551
8 A03 2000 Sep 81.4 111 0.000412
9 A03 2000 Dec 72.5 114 0.0000000191
10 A03 2001 Nov 58.4 125 0.00000212
# ℹ 257 more rows
There are 267 anomalies, far more than the 14 false alarms we would expect from 13,983 surprisal probabilities if the forecast distributions were correct, so most of them are likely to be real anomalies rather than false alarms.
Now let’s look at the A12 series that we started with, and consider the times when anomalies occur, as shown in Figure 12.16.
Code
pbs_plot(pbs, pbs_anomalies, "A12")
One potential anomaly is identified in 2002, and the sudden drop at the start of 2006 causes several anomalies indicating a series of unusual observations. Eventually the “new normal” leads to fewer and fewer observations being labelled as anomalies.
This process of model adjustment is much faster in the next example, shown in Figure 12.17, where the first jump leads to two anomalies, and then the second much larger jump leads to two more anomalies. After that, the model has learned to allow for large jumps in the series, so the later jump is not seen as anomalous.
Code
pbs_plot(pbs, pbs_anomalies, "N07")
The next example, shown in Figure 12.18, shows less dramatic anomalies that would be harder to identify without a model.
Code
pbs_plot(pbs, pbs_anomalies, "R05")
The first anomaly in 1994 has an unusually large peak compared to the preceding years; the next two, in December 1997 and January 1998, precede an unusually low trough compared to the previous years; and the final two in 2004 coincide with a disruption to the seasonal pattern in that year.
Figure 12.19 shows the surprisal probabilities for all 84 ATC groups at once, with one row for each group and one column for each month. Most cells are grey, but some months have many flagged groups, which show up as vertical stripes; the clearest is February 2008. These are events that affect many series at once, which we consider in the next section.
Code
groups <- sort(unique(pbs_scores$ATC2))
# Label the first group of each anatomical main group (first letter of ATC2)
first <- which(!duplicated(substr(groups, 1, 1)))
pbs_scores |>
as_tibble() |>
filter(!is.na(prob)) |>
mutate(
row = match(ATC2, groups),
level = cut(
prob,
c(0, 0.001, 0.01, 1),
right = FALSE,
include.lowest = TRUE
)
) |>
ggplot(aes(x = as.Date(Month), y = row, fill = level)) +
# Months differ in length, so fix the tile width to avoid gaps between them
geom_tile(width = 31) +
scale_fill_manual(
values = c("#D55E00", "#E69F00", "grey85"),
labels = unname(TeX(c(
"$p < 0.001$",
"$0.001 \\leq p < 0.01$",
"$p \\geq 0.01$"
))),
name = NULL
) +
scale_x_date(date_breaks = "2 years", date_labels = "%Y", expand = c(0, 0)) +
scale_y_reverse(
breaks = first,
labels = substr(groups[first], 1, 1),
expand = c(0, 0)
) +
labs(x = "Month", y = "ATC group") +
theme(
panel.grid = element_blank(),
panel.background = element_rect(fill = "white"),
legend.position = "top"
)
Surveillance across several series
So far, we have monitored each series separately. But some events affect many series at once, such as a change in the rules of the PBS, or a change in the way the data are recorded. In any one series, such an event may look only mildly unusual, but if it happens in many series in the same month, it is much more surprising.
One simple way to monitor all the series jointly is to count the number of series that are flagged as anomalous in each month. Let M_t be the number of series for which a surprisal probability is available at time t, and let N_t be the number of these with surprisal probability below 0.001. Here M_t = 82 until November 1995, M_t = 83 from December 1995, when the L03 group first has a one-step forecast, and M_t = 84 from November 2003, when the A05 group does. If the series were independent, and each observation had the same probability \pi of being flagged, then N_t would have a Binomial(M_t,\pi) distribution, and the probability of seeing at least as many flagged series as the observed number n_t would be \Pr(N_t \ge n_t). This is just a surprisal probability, computed for the count n_t under the binomial distribution rather than for an individual observation.1 We flag a month as anomalous if this probability is below 0.001.
If each forecast distribution were the true distribution of the next observation, the surprisal probabilities would be uniformly distributed on (0,1), as explained earlier, and so each observation would be flagged with probability \pi = 0.001. But 1.9% of all observations have surprisal probabilities below 0.001, because of real anomalies, or forecast distributions that are too narrow, or both. What matters here is whether a month has more flagged series than usual, so we estimate \pi in real time, using the proportion of flagged observations in all previous months. To give a reasonable estimate of \pi at the start, we only compute the joint probabilities after the first 12 months of surprisal probabilities are available.
The independence assumption is also unrealistic here, as the same events affect many series. Dependence between series makes large values of N_t more likely than the Binomial distribution suggests, so the probabilities computed this way are too small. They are still useful for ranking months by how unusual they are, and in practice the threshold for flagging a month may need to be set using experience of how often the system raises an alarm.
pbs_joint <- pbs_scores |>
as_tibble() |>
filter(!is.na(prob)) |>
group_by(Month) |>
summarise(M = n(), n = sum(prob < 0.001), .groups = "drop") |>
mutate(
# Proportion of flagged observations in all previous months
pi = (cumsum(n) - n) / (cumsum(M) - M),
# Probability of at least n flagged series
prob = pbinom(n - 1, M, pi, lower.tail = FALSE)
) |>
filter(row_number() > 12)
pbs_joint |> filter(prob < 0.001)# A tibble: 4 × 5
Month M n pi prob
<mth> <int> <int> <dbl> <dbl>
1 1997 Dec 83 12 0.0183 4.12e- 8
2 1999 Mar 83 11 0.0214 1.67e- 6
3 2001 Dec 83 9 0.0189 2.82e- 5
4 2008 Feb 84 33 0.0164 1.45e-36
pbs_joint |>
ggplot(aes(x = Month, y = n)) +
geom_col(aes(fill = prob < 0.001), show.legend = FALSE) +
scale_fill_manual(values = c(`FALSE` = "grey35", `TRUE` = "#D55E00")) +
tsibble::scale_x_yearmonth(date_breaks = "2 years", date_labels = "%Y") +
labs(y = "Number of flagged ATC groups")
Most months have between zero and three flagged series, consistent with the estimated value of \pi. The four months shown in orange in Figure 12.20 have many more flagged series than we would expect. Two are in December, at the time of the usual end-of-year spike, which occurs because patients stockpile medicines before the PBS safety-net thresholds reset at the start of each calendar year (Hyndman & Athanasopoulos, 2021, Ch. 2); in these months the size of the spike was unusual in many groups at once. There is no obvious explanation for March 1999. The most extreme month is February 2008, when 33 of the 84 groups were flagged. In that year, the usual fall in script volumes in February did not occur; total volume was about 17% higher than in February 2007. However, the combined volume for January and February 2008 was only about 4% higher than a year earlier, in line with previous years, and January 2008 was lower than January 2007. So it seems that some scripts that would usually have been recorded in January were recorded in February instead: a change in timing rather than in demand. No administrative reason for this has been found. An event like this is much easier to spot when looking across all series than in any single series.
Feature-based surveillance
Another approach to surveillance is to use features of the series, rather than the raw observations. The methods of Section 12.3 can be applied to streaming data, where the features are updated as new data arrive (possibly using a rolling window). Feature-based methods for streaming time series data are discussed by Talagala et al. (2020).
12.5 Summary
The three approaches in this chapter share a common idea: an observation, or a whole series, is anomalous if it has a small surprisal probability under a density f that describes typical behaviour. The approaches differ only in the choice of f. When f might be wrong, fitting a GPD to the largest surprisals gives approximate probabilities that are less sensitive to that choice.
- Weird times: the signal (trend, seasonality, and other structure) is first removed from the series, using a moving median (as in the Hampel identifier) or an STL decomposition, and f is the distribution of the remaining residuals. Very large anomalies can distort the estimated signal nearby, so that neighbouring observations appear anomalous in the opposite direction; such apparent anomalies should be checked before they are interpreted. When there are many related series, we can either analyse each series separately, or combine them using principal components to find periods that are unusual across all series.
- Weird series: each series is summarised by a vector of features, so a weird series is an anomaly in feature space. Then f can be a kernel density estimate of the features, or of their first few principal components, although any of the multivariate methods of earlier chapters could also be used. Anomalous series often reveal data problems, such as series that are mostly zeros; these are worth finding before modelling a large collection of series.
- Surveillance: f is the one-step forecast distribution. Because the model is refitted as each new observation arrives, a sudden change in level is flagged when it first happens, and the new level then becomes the “new normal”. If the forecast distributions are correct, the surprisal probabilities are uniformly distributed on (0,1), so a threshold \alpha gives a false-alarm rate of \alpha per series in each time period. To detect events that affect many series at once, we count the number of series flagged in each time period, and compute the surprisal probability of that count under a binomial distribution.
Once n_t is a few above the expected count M_t\pi, every count that is no more likely than n_t is at least as large as n_t, so \Pr(N_t \ge n_t) is the probability of a count at least as surprising as n_t.↩︎