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:
| Column | Meaning |
|---|---|
indicator_id, geography_id, period, value | Required. period is an integer year, or a date, pandas.Period, or string such as 2019Q2 for quarterly and monthly data |
indicator_name, geography_name | Optional 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:
- Fills gaps in the time index with missing values.
- Imputes missing values and records them in
is_imputed. The methods areinterpolation(default),locf,mean,ma,random,kalman(structural time series and Kalman smoother), andseadec(seasonal decomposition; setseasonfor quarterly and monthly data); thena_names of the R package work too. Imputed values are never explained. - Removes the trend with Friedman's super smoother, as
feasts::STLdoes for a series without a season. Withseason=4orseason=12the seasonal component is removed as well, by an STL decomposition. - 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
| Method | Flags | Main options |
|---|---|---|
zscore | |zscore| above a threshold | threshold=3 (2.5 moderate, 2 sensitive) |
tsoutlier | zscore outside Q1 − k·IQR and Q3 + k·IQR | threshold=3, scope="series" |
hampel | zscore far from the median of its 2k + 1 neighbours | k=5, t0=5, trim=False |
capa | collective anomalies (runs of two or more values) and point anomalies, by penalised likelihood | type="meanvar" (or "mean", "robustmean"), min_seg_len=2, robust_scale=False |
isotree | values that an isolation forest isolates in few splits | threshold=0.5, ntrees=10, features=("zscore", "period") |
outliertree | values 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:
tsoutliertakes the quartiles of each series (scope="series").macroanomalytakes 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.capakeeps a point anomaly at the first observation, whichanomaly::point_anomaliesleaves out, and flags every observation of each collective segment, wheremacroanomalyleaves out a few positions in some series. A constant run has zero variance, which the R code floors at the smallest float; rounding noise inzscorecan make a handful of such rows differ.outliertreeis a numpy/pandas implementation of the method of Cortes (2020), written from the paper;backend="outliertree"runs theoutliertreepackage (C++, as in R;pip install outliertree). The tree splits on the other columns (zscore,period,indicator_id,geography_id,is_imputed, asmacroanomalypasses them) and a value is an outlier when it lies far outside its group;outliertree_reasongives the group, for examplezscore=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 andz_outlier=6settings, and on the seeded panel both flag nothing. Atz_outlier=4and3this 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=8is strict for standardised series, which rarely reach it.tests/test_anomaly_detection_outliertree.pychecks this againstmake_outliertree_reference.R. The R package applies internal checks that are not published, and this version differs from it there.macroanomalydoes not runoutliertreeby default (.method="zscore").isotreeuses scikit-learn's isolation forest onzscoreand the period (backend="isotree"uses theisotreepackage). 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. capawithtype="robustmean"gives the same collective and point anomalies asanomaly::capaon 290 seeded runs (capa_robustmean.csv, made bymake_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 mostbeta_tilde, so an outlier inside a run does not break it.impute_method="kalman"fits the structural time series ofStructTS(a local linear trend, plus a stochastic seasonal whenseasonis set) with statsmodels'UnobservedComponentsand fills the gaps from the Kalman smoother. It is close tona_kalmanbut 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. Preferinterpolationwhen 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 needsseasonfor quarterly and monthly data. Yearly series and series shorter than two seasonal periods are interpolated, with a warning, asna_seadecdoes. On 46 seeded series (impute_seadec.csv) 37 equal R's to rounding; in the others the robustness weights of statsmodels' STL differ fromstats::stl, and the largest difference is 0.16 standard deviations of the series.
Related
- Anomaly Detection Suite notebook: an animated walkthrough from a raw table to the review payload.
- The cookbook Practical Guide to Detecting and Explaining Anomalies in Indicator Data turns the workflow into recipes for a team.
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.