Skip to main content

Detecting Anomalies in Indicator Series

ai4data.anomaly.detection finds unusual values in social and economic time series and hands them to the explanation pipeline. It rebuilds in Python the three-step workflow of the World Bank's macroanomaly R package (L. Perfetti Villa, D. Newhouse, and O. Dupriez): prepare the series, detect with several methods, and report what they flag.

Indicator series are short (a few dozen points), have gaps, and trend. The preparation step removes the trend so that the methods look at departures from it, and the use of several methods gives each value a count of the methods that flag it. A value that three methods flag deserves more attention than one that a single method flags.

from ai4data.anomaly.detection import detect_anomalies

result = detect_anomalies(df, mapping="auto") # one row per indicator, geography, and year
print(result.summary())
result.plot("KEN", "SE.PRM.ENRR") # one series, with its flags
result.flagged(min_count=3) # the values at least three methods flag

Input​

One row per indicator, geography, and period, in long format. The columns are the canonical names of the explanation pipeline:

ColumnMeaning
indicator_id, geography_id, period, valueRequired. period is an integer year, or a date, pandas.Period, or string such as 2019Q2 for quarterly and monthly data
indicator_name, geography_nameOptional labels; the ids are used when they are missing

Any other layout takes a mapping from canonical names to source columns, mapping={"indicator_id": "Indicator.Code", "geography_id": "Country.Code", "period": "Year", "value": "Value"}, or mapping="auto" to guess it from the headers.


Step 1: Prepare​

normalize (called by detect_anomalies) does four things to each series:

  1. Fills gaps in the time index with missing values.
  2. Imputes missing values and records them in is_imputed. The methods are interpolation (default), locf, mean, ma, random, kalman (structural time series and Kalman smoother), and seadec (seasonal decomposition; set season for quarterly and monthly data); the na_ names of the R package work too. Imputed values are never explained.
  3. Removes the trend with Friedman's super smoother, as feasts::STL does for a series without a season. With season=4 or season=12 the seasonal component is removed as well, by an STL decomposition.
  4. Standardises the remainder within the series to mean 0 and standard deviation 1. This is zscore, the input of every method.

A series with fewer than three observed values (two when not detrending) is dropped with a warning and listed in result.normalization["dropped_series"]; on_insufficient="raise" fails instead.


Step 2: Detect​

MethodFlagsMain options
zscore|zscore| above a thresholdthreshold=3 (2.5 moderate, 2 sensitive)
tsoutlierzscore outside Q1 − k·IQR and Q3 + k·IQRthreshold=3, scope="series"
hampelzscore far from the median of its 2k + 1 neighboursk=5, t0=5, trim=False
capacollective anomalies (runs of two or more values) and point anomalies, by penalised likelihoodtype="meanvar" (or "mean", "robustmean"), min_seg_len=2, robust_scale=False
isotreevalues that an isolation forest isolates in few splitsthreshold=0.5, ntrees=10, features=("zscore", "period")
outliertreevalues that are extreme given the period, indicator, or geography, with the conditions as an explanation (not run by default)z_outlier=8, z_norm=2.67, max_depth=4, targets=None, backend="numpy"
result = detect_anomalies(
df, mapping="auto",
methods=["zscore", "capa", "hampel", "isotree"],
params={"isotree": {"threshold": 0.7}, "hampel": {"trim": True}},
)

Each method adds a column outlier_<method> (0 or 1), and some add a score (isotree_score, capa_strength, hampel_replacement, outliertree_reason). Two columns summarise them, and the explanation pipeline reads both:

  • outlier_count: the number of methods that flag the row;
  • anomaly_score: |zscore|, which ranks the flagged values.

capa reads its input as a baseline with mean 0 and variance 1. A series that has a long departure from the trend has a narrower baseline than that, and long runs can come out as collective anomalies; robust_scale=True centres and scales each series by its median and MAD first. The hampel filter does not test the first and last k observations of a series, nor series of 2k or fewer.

Adding a method​

from ai4data.anomaly.detection import register_detector

@register_detector("big_jump")
def big_jump(table, threshold=4.0):
d = table.groupby(["indicator_id", "geography_id"])["zscore"].diff().abs()
return table.assign(outlier_big_jump=(d > threshold).astype(int))[["outlier_big_jump"]]

A method receives the prepared table and returns the column outlier_<name> and any extra columns, with the same index.


Step 3: Report​

result.summary() # counts by method, by number of methods in agreement, by geography and indicator
result.flagged(3) # most flagged and most extreme first
result.shortlist(3) # the series to explain, ranked by the sum of anomaly_score
result.to_csv("detections.csv")
result.plot("KEN", "SE.PRM.ENRR") # needs matplotlib

The same steps run from a terminal:

python -m ai4data.anomaly.detection data.csv --output detections.csv --methods zscore,capa,hampel \
--batch batch.jsonl --provider openai

Into the explanation pipeline​

The table is already in the canonical format of ai4data.anomaly.explanation, so nothing sits between the two steps:

path, count = result.build_explanation_batch("batch.jsonl", provider="openai", min_outlier_count=3)
# run the batch (run_batch), then:
explanations = result.parse_explanations("batch_output.jsonl", "openai", batch_path=path)
result.export_for_review(explanations, "review.json") # for the reviewer app

build_explanation_batch takes the series that at least min_outlier_count methods flag, leaves out imputed values, and calls build_batch_file. For finer control, result.explanation_inputs() returns the arguments of build_batch_file (shortlist, source_df, and the two name maps), and result.to_canonical() returns the table. Only yearly data can be explained, because the contexts and prompts read integer years.


Agreement with the R package​

The preparation step, the zscore, tsoutlier, and hampel methods, and capa give the same flags as macroanomaly and anomaly on seeded test data; tests/test_anomaly_detection_parity.py compares them with outputs that tests/fixtures/anomaly_detection/make_reference.R regenerates. The differences:

  • tsoutlier takes the quartiles of each series (scope="series"). macroanomaly takes them over all series at once, and with series standardised to unit variance those fences are far out and flag little; scope="pooled" reproduces it.
  • capa keeps a point anomaly at the first observation, which anomaly::point_anomalies leaves out, and flags every observation of each collective segment, where macroanomaly leaves out a few positions in some series. A constant run has zero variance, which the R code floors at the smallest float; rounding noise in zscore can make a handful of such rows differ.
  • outliertree is a numpy/pandas implementation of the method of Cortes (2020), written from the paper; backend="outliertree" runs the outliertree package (C++, as in R; pip install outliertree). The tree splits on the other columns (zscore, period, indicator_id, geography_id, is_imputed, as macroanomaly passes them) and a value is an outlier when it lies far outside its group; outliertree_reason gives the group, for example zscore=0.92 where period in [2010, 2010] (usual range 4.22..4.61). The agreement is on strong outliers, not on every flag: on a planted panel (all series share a 2010 shock but two) the R package and this version flag the same two values at the default and z_outlier=6 settings, and on the seeded panel both flag nothing. At z_outlier=4 and 3 this version also flags 3 to 5 borderline values that R does not (Jaccard 0.4 and 0.29, R's flags all found). z_outlier=8 is strict for standardised series, which rarely reach it. tests/test_anomaly_detection_outliertree.py checks this against make_outliertree_reference.R. The R package applies internal checks that are not published, and this version differs from it there. macroanomaly does not run outliertree by default (.method="zscore").
  • isotree uses scikit-learn's isolation forest on zscore and the period (backend="isotree" uses the isotree package). The R version splits on every column of the table, and the two give similar but not equal scores.
  • Seasonal decomposition uses the STL of statsmodels, which differs a little from stats::stl.
  • capa with type="robustmean" gives the same collective and point anomalies as anomaly::capa on 290 seeded runs (capa_robustmean.csv, made by make_extras_reference.R; tests/test_anomaly_detection_extras.py). The cost of a run is the least squared error about one mean in which an observation counts at most beta_tilde, so an outlier inside a run does not break it.
  • impute_method="kalman" fits the structural time series of StructTS (a local linear trend, plus a stochastic seasonal when season is set) with statsmodels' UnobservedComponents and fills the gaps from the Kalman smoother. It is close to na_kalman but not equal: the optimiser differs, and so does the initial state covariance, which matters most with a season. On 40 seeded series (impute_kalman.csv) the largest difference per series, relative to the series' standard deviation, has a median of 0.01 and a maximum of 0.21 without a season, and a median of 0.13 and a maximum of 0.61 with a season of 4 or 12. Prefer interpolation when values must be reproducible across tools.
  • impute_method="seadec" interpolates, splits the series with a robust STL (s.window=11), interpolates the series without its season, and adds the season back. It needs season for quarterly and monthly data. Yearly series and series shorter than two seasonal periods are interpolated, with a warning, as na_seadec does. On 46 seeded series (impute_seadec.csv) 37 equal R's to rounding; in the others the robustness weights of statsmodels' STL differ from stats::stl, and the largest difference is 0.16 standard deviations of the series.

References​

  • Fisch, A., Eckley, I., and Fearnhead, P. (2022). A linear time method for the detection of collective and point anomalies. Statistical Analysis and Data Mining 15(4).
  • Friedman, J. (1984). A variable span smoother. Stanford University technical report.
  • Liu, F., Ting, K., and Zhou, Z. (2008). Isolation forest. IEEE ICDM.
  • Hampel, F. (1974). The influence curve and its role in robust estimation. Journal of the American Statistical Association 69.