1. Preparing series for detection
Question: Can the series be compared on one scale?
Rationale
Indicators differ in unit and in level. Under-five mortality is counted per 1,000 live births and electricity access is a percentage of the population, so a change of five points means something different in each. A detection method that reads raw values would flag the series with the largest swings and ignore the ones whose movements are small in absolute terms. Preparation puts every series on one scale first, so that a flag means a departure from that series' own pattern.
Indicator series are also short, usually a few dozen yearly values, and they have gaps. A country may skip a survey year, and most methods need a value in every year. Preparation therefore fills the gaps and marks each filled value, so that no later step treats an invented value as a measurement. Most indicators also trend. A mortality rate that falls by one point a year would look unusual in its last year only because it is the lowest, so the trend is estimated and removed, and the methods look at the remainder.
The detection suite in ai4data.anomaly.detection performs these steps in a function called normalize, which rebuilds the preparation step of the macroanomaly R package of the World Bank. This chapter explains what each step does, how to check that it did what was intended, and which choices belong to the team. The methods that read the prepared series are the subject of Chapter 2.
Target state
- The input is one long table with one row per indicator, geography, and year, and the columns are named as the suite expects.
- Every gap in the time index is filled, and each filled value is marked as imputed, so that the value can be kept out of the explanation step.
- A report states how many rows were read, how many values were imputed, and which series were dropped for having too few observations.
- Each series has its trend removed and is standardised to mean 0 and standard deviation 1, so that series of different indicators share one scale.
Maturity levels
| Level | Steps |
|---|---|
| Foundational | Arrange the series in the long table, run the preparation, and read the report of gaps and dropped series. |
| AI-ready | Choose the imputation method on purpose, record it with the run, and keep imputed values flagged in the output so that later steps read the flag. |
| AI-native | Compare two preparation choices on series with known anomalies and keep the choice that the team can defend, with the comparison stored beside the run record. |
This chapter prepares the fictional panel that the whole guide uses: four indicators, eight fictional countries, and the years 2000 to 2024, with jumps, runs of shifted values, and constant tails planted in half of the series. All values and country names are invented. The panel is the file indicator_panel.csv, and the planted anomalies are listed in planted_anomalies.csv. Neither file belongs to the shared running example of the other guides, and no value here describes a real country.
Recipes
1.1 Arrange the series in one long table
- Level
- Foundational
- Skills
- Data analyst
- Indicative time
- 30 minutes
Result: A CSV file holds one row per indicator, geography, and year, with the four required columns and two optional name columns, and a report confirms that the suite can read it.
The suite reads data in the long format, in which every observation is a row and the series are identified by two columns. This layout differs from the wide layout of many statistical releases, where each year is a column. The long layout lets one table hold any number of indicators and countries, and a missing year is a missing row, which the preparation step can detect.
The following table lists the columns of the example file.
| Column | Meaning |
|---|---|
indicator_id | The code of the indicator, such as EG.ELC.ACCS. Required. |
geography_id | The code of the country or region, such as FFF. Required. |
period | The year, as an integer. Required. The suite also reads quarterly and monthly periods, but only yearly data can be explained in Chapter 3. |
value | The observed value. Required. |
indicator_name, geography_name | Optional labels. The explanation step puts them in its prompts, and the codes are used when the labels are missing. |
- Export or reshape the source data to the long format. A table in the wide format is reshaped with the melt operation of the dataframe library, which turns one column per year into rows.
- Name the columns as in the table above. Where the source uses other names, the suite takes a mapping from its names to the source columns, or guesses the mapping from the headers when
mapping="auto"is used, as the scripts of this guide do. A guess is checked by reading the report of the next recipe, because a wrong guess usually shows as a series count that differs from the expected one. - Keep missing years as missing rows or empty values. Filling them in the source file would hide them, because the suite marks the values it fills and cannot mark a value that arrived already filled.
- Run the report of Recipe 1.2 and compare the number of series with the number of indicators times the number of geographies.
Worked example. The file indicator_panel.csv has 780 rows. Four indicators and eight geographies give 32 series, and 25 years give 800 possible rows, so 20 rows are missing. The report in Recipe 1.2 confirms the same numbers from the suite's side.
What this does not do. The check confirms the layout. It does not check that a code means what the label says, that two sources use the same definition of an indicator, or that the units agree across geographies.
1.2 Fill the gaps and mark the imputed values
- Level
- AI-ready
- Skills
- Data analyst
- Indicative time
- 30 minutes
Result: Every series has a value in every year of its range, each filled value is marked in the column is_imputed, and the run report states how many were filled and by which method.
A gap is a year inside a series that has no value. Methods that compare each value with its neighbours need a value in every year, so the preparation step fills the gaps. The step is called imputation, and the value it writes is an estimate and not a measurement. The suite therefore writes True in is_imputed for every estimated value. A flagged value that is imputed is never sent for explanation, because a language model asked to explain an invented number would invent an explanation.
The default method is linear interpolation between the neighbouring observed values. Other methods carry the last observed value forward, replace a gap with the series mean, replace it with a moving average, or draw a random value. The choice changes the filled values and, because the series is standardised afterwards, it also changes every later score in the series. Interpolation is the usual choice for slowly moving indicators, and carrying the last value forward suits a series that holds its level until the next release.
The script prepare_series.py runs the preparation and prints the report.
"""Prepare indicator series for detection and report what the preparation did.
Purpose: run the preparation step of the detection suite (gap filling,
imputation, trend removal, and standardisation) on a long-format CSV file, print
what changed, and optionally show one series before and after. The report is
the check that the series can be compared on one scale before any method runs.
Usage:
python prepare_series.py indicator_panel.csv
python prepare_series.py indicator_panel.csv --series EG.ELC.ACCS FFF --years 2005 2009
python prepare_series.py indicator_panel.csv --impute-method locf --output prepared.csv
Requires ai4data[anomaly]. Exit status: 0 when every series was prepared;
1 when the input cannot be read or lacks the required columns; 2 when a series
was dropped for having too few observed values (the others are still reported).
What this does not check: whether the imputed values are plausible, or whether
a trend that was removed is a real change of level. Preparation treats a
permanent shift of level like any other trend, and the report does not judge it.
"""
import argparse
import sys
from pathlib import Path
import pandas as pd
from ai4data.anomaly.detection import normalize
REQUIRED = ["indicator_id", "geography_id", "period", "value"]
def main(argv: list[str] | None = None) -> int:
"""Prepare the series and print the report.
Parameters
----------
argv : list[str] | None, optional
Command arguments, or the process arguments when omitted.
Returns
-------
int
Zero when every series was prepared.
"""
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
parser.add_argument("input", type=Path)
parser.add_argument("--impute-method", default="interpolation")
parser.add_argument("--series", nargs=2, metavar=("INDICATOR", "GEOGRAPHY"))
parser.add_argument("--years", nargs=2, type=int, default=[2000, 2024])
parser.add_argument("--output", type=Path)
args = parser.parse_args(argv)
try:
df = pd.read_csv(args.input)
except (OSError, ValueError) as error:
print(f"Cannot read the input: {error}", file=sys.stderr)
return 1
missing = [c for c in REQUIRED if c not in df.columns]
if missing:
print(f"Missing columns: {', '.join(missing)}", file=sys.stderr)
return 1
prepared = normalize(df, "auto", impute_method=args.impute_method)
info = prepared.attrs
dropped = info.get("dropped_series", [])
keys = ["indicator_id", "geography_id"]
print(
f"rows read: {len(df)}; rows after gap filling: {len(prepared)}; "
f"series: {prepared.groupby(keys).ngroups}"
)
print(
f"gaps filled: {info.get('total_gaps')}; "
f"imputed observations: {int(prepared['is_imputed'].sum())} "
f"({args.impute_method})"
)
print(f"series dropped for too few observations: {len(dropped)}")
scale = prepared.groupby("indicator_id").agg(
value_min=("value", "min"),
value_max=("value", "max"),
zscore_min=("zscore", "min"),
zscore_max=("zscore", "max"),
)
print("scale of each indicator, before and after standardising:")
print(scale.round(1).to_string())
if args.series:
indicator, geography = args.series
one = prepared[
(prepared["indicator_id"] == indicator)
& (prepared["geography_id"] == geography)
& prepared["period"].between(*args.years)
]
print(f"\n{indicator} {geography}, {args.years[0]}-{args.years[1]}:")
columns = ["period", "value", "is_imputed", "zscore"]
print(one[columns].round(2).to_string(index=False))
if args.output:
prepared.to_csv(args.output, index=False)
print(f"\nwrote {args.output}")
return 2 if dropped else 0
if __name__ == "__main__":
raise SystemExit(main())
- Run the script on the table and read the three lines of the report: the rows read and the rows after gap filling, the number of imputed values, and the number of dropped series.
- A series with fewer than three observed values cannot be detrended and is dropped with a warning. The script then exits with status 2, so that a scheduled run stops where a series has disappeared.
- Inspect one series around a gap with
--seriesand--years, and confirm that the filled value lies where a person would expect it. - Record the imputation method with the run, as described in Chapter 4.
Worked example. The command reads the example panel and fills 20 gaps by interpolation.
python prepare_series.py indicator_panel.csv --series EG.ELC.ACCS DDD --years 2013 2015
rows read: 780; rows after gap filling: 800; series: 32
gaps filled: 20; imputed observations: 20 (interpolation)
series dropped for too few observations: 0
scale of each indicator, before and after standardising:
value_min value_max zscore_min zscore_max
indicator_id
EG.ELC.ACCS 33.0 100.0 -4.5 4.5
SE.PRM.NENR 45.8 92.2 -2.9 2.2
SH.MORT.U5 12.0 69.0 -4.0 4.3
SI.POV.HEAD 0.5 55.4 -3.4 1.9
EG.ELC.ACCS DDD, 2013-2015:
period value is_imputed zscore
2013 67.95 False -1.07
2014 69.60 True -0.53
2015 71.25 False -0.01
The year 2014 of electricity access in Dovenia (code DDD) is missing in the source. Interpolation writes 69.60, the midpoint of 67.95 and 71.25, and marks it as imputed. With --impute-method locf the same year is filled with 67.95, the value of 2013, and its standardised score changes from -0.53 to -2.15. The second choice makes an ordinary year look unusual, which is why the method is recorded with every run.
What this does not do. Imputation fills a gap with a value that follows from the neighbours. It does not know why the value is missing. A missing year that stands for a break in the series, for a change of definition, or for a suppressed value is not recovered by any method. Further imputation options are listed in the detection reference.
1.3 Remove the trend and standardise each series
- Level
- AI-ready
- Skills
- Data analyst or statistician
- Indicative time
- 45 minutes
Result: Each series has a column zscore with its trend removed and its remainder standardised to mean 0 and standard deviation 1, and the scale table of the report shows that the series of different indicators share one range.
A trend is the slow movement of a series, such as the steady decline of a mortality rate. The suite estimates it with the super smoother of Friedman (1984), a smoother that adapts its span to the data, which matches the choice of feasts::STL for a series without a season in the R packages that the suite follows. The estimated trend is subtracted from the series, and what remains is the departure from the series' own course. The mean of the remainder is set to zero, and the remainder is divided by its standard deviation. The result is the z-score. A value of 4.5 means that the observation lies 4.5 standard deviations from the series' own pattern, whatever the unit of the indicator. For quarterly or monthly data, the option season=4 or season=12 also removes a seasonal component, with the seasonal-trend decomposition by loess (STL) of Cleveland and others (1990).
The standardisation within each series is what makes series of different indicators comparable. It also has a consequence for interpretation. One extreme value inflates the standard deviation of its own series, so that the other values of the series look more ordinary than they would without it, and a short series gives a poor estimate of the standard deviation. Chapter 2 returns to this when it sets thresholds.
- Run the report of Recipe 1.2 and read the table of scales. After standardising, the minimum and maximum of every indicator should lie within a few standard deviations of zero, whatever the original range.
- Inspect a series that has a known jump with
--seriesand--years, and confirm that the jump stands out and its neighbours do not. - Where the series has a seasonal pattern, set the seasonal period for the run. The scripts of this guide use yearly data and do not set one.
- Keep the trend removal on for indicators that trend. It can be turned off with
detrend=Falsefor a series that has no trend, in which case the standardised value itself is scored.
Worked example. The table in Recipe 1.2 shows the effect on the example panel. Electricity access ranges from 33.0 to 100.0 percent, and poverty headcount from 0.5 to 55.4 percent, while the standardised scores of both lie between about -4.5 and 4.5. The planted jump in the electricity series of Fenmark (code FFF) in 2007 shows the effect on one series.
python prepare_series.py indicator_panel.csv --series EG.ELC.ACCS FFF --years 2005 2009
rows read: 780; rows after gap filling: 800; series: 32
gaps filled: 20; imputed observations: 20 (interpolation)
series dropped for too few observations: 0
scale of each indicator, before and after standardising:
value_min value_max zscore_min zscore_max
indicator_id
EG.ELC.ACCS 33.0 100.0 -4.5 4.5
SE.PRM.NENR 45.8 92.2 -2.9 2.2
SH.MORT.U5 12.0 69.0 -4.0 4.3
SI.POV.HEAD 0.5 55.4 -3.4 1.9
EG.ELC.ACCS FFF, 2005-2009:
period value is_imputed zscore
2005 55.59 False -0.35
2006 57.58 False -0.31
2007 71.42 False 4.51
2008 61.49 False -0.16
2009 62.67 False -0.33
The value of 71.42 in 2007 follows 57.58 in 2006 and precedes 61.49 in 2008. After trend removal and standardising, it has a score of 4.51 while its neighbours lie between -0.35 and -0.16. The suite writes the scores to the column zscore, and every detection method of Chapter 2 reads that column.
What this does not do. A smoother follows the data, so that a permanent change of level is partly absorbed into the trend and is flagged weakly or not at all. Preparation does not distinguish a real break from an error. The options of the preparation step, including the trend window and the minimum number of observations, are listed in the detection reference.
Implementation options
- The suite is part of the
ai4datapackage and installs withpip install ai4data[anomaly]. Its preparation step is a Python rebuild of the first step of themacroanomalyR package of the World Bank, and teams that already run the R package can compare its output with the suite's on the same file. The agreement and the known differences are described in the detection reference. - A team with its own detector can leave out the suite's detection and pass its scores to the adapters of the explanation pipeline, which Chapter 3 mentions. Preparation is then the team's own.
- Other imputation methods and trend options exist, and the choice between them is a modelling decision. The default of interpolation with trend removal suits yearly indicators that move slowly.
World Bank examples
- The
macroanomalyR package of the World Bank, by L. Perfetti Villa, D. Newhouse, and O. Dupriez, defines the three-step workflow of prepare, detect, and report that the suite rebuilds in Python. - The anomaly detection documentation of the program describes the whole pipeline from detection to review.
Resources
- The detection reference lists the options of the preparation step and is used in Recipes 1.2 and 1.3.
- Friedman, J. (1984), A variable span smoother, Stanford University technical report, is the source of the trend estimate.
- Cleveland, R., Cleveland, W., McRae, J., and Terpenning, I. (1990), STL: a seasonal-trend decomposition procedure based on loess, Journal of Official Statistics 6, is the source of the seasonal decomposition for quarterly and monthly data.
- The demonstration notebook shows the preparation steps as pictures on the same fictional panel.
Common mistakes
- Filling gaps in the source file before the run removes the
is_imputedmarks, and the explanation step then asks the model about invented values. - Comparing raw values across indicators ranks the series by their unit and not by how unusual they are.
- Reading the standardised score of a short series as a precise measure overstates it, because the standard deviation of a handful of values is itself uncertain.
- Changing the imputation method between two runs without recording it makes the flags of the two runs impossible to compare.
Verification
- Count the series. The report states the number of series. It equals the number of indicators times the number of geographies, unless the source lacks some combinations.
- Count the imputed values. The imputed count equals the number of missing years inside the series ranges. For the example, both numbers are 20.
- Check the scale. After standardising, the scores of every indicator lie within a few units of zero, as in the table of Recipe 1.2.
- Check the dropped series. The report states zero dropped series, or the dropped series are known and accepted.
Checklist
Ticks are saved in this browser only.