agentleFS
michaelsvanbeekmichaelsvanbeek/personal-agent-skills/skills/anomaly-detection/SKILL.md

anomaly-detection

Skill1 starsChanged 7 months agoMITView on GitHub

Anomaly detection methodologies, strategy selection, and application. Use when: identifying outliers in data, detecting unusual patterns in metrics or logs, choosing between statistical and ML-based detection methods, building alerting thresholds, analyzing time series for anomalies, investigating suspicious data points, designing anomaly detection pipelines, or evaluating whether a detected "anomaly" is real or an artifact. Works on time series, tabular data, event streams, and metric dashboards.

9 other projects use a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

9 rules. 0 are common, 9 are distinctive, and 0 are very specific to this project.

  • 0

    Common

    Most of the 6 edited versions we read keep these.

  • 9

    Distinctive

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Use these when data is well-understood, roughly stationary, and you can define "normal" numerically.

    line 48
  2. Distinctive:

    Use when your data has trend, seasonality, or autocorrelation that invalidates simple statistical bounds.

    line 62
  3. Distinctive:

    Use when the data is multivariate, the patterns are complex, or statistical methods can't capture what "normal" means.

    line 77
  4. Distinctive:

    Follow this decision tree to choose a method:

    line 93
  5. Distinctive:

    Before selecting a method, understand what you're working with:

    line 123
  6. Distinctive:

    Every detection method needs calibration.

    line 191
  7. Distinctive:

    Every anomaly detection analysis should produce:

    line 230
  8. Distinctive:

    Rule of thumb: Don't combine methods to increase sensitivity — combine them to increase precision (fewer false positives).

    line 252
  9. Distinctive:

    Use the statistics skill for assumption validation (normality tests, distribution checks) before applying Tier 1 methods.

    line 269

“Common” is measured: kept by at least 6 in 10 of the 6 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Core Principles

  1. Define normal first — You cannot detect anomalies without a clear model of what "normal" looks like. Start by characterizing the baseline.
  2. Context over thresholds — A value that's anomalous in one context is expected in another. Day-of-week, seasonality, and deployment events all shift what's normal.
  3. False positives are expensive — An alerting system that cries wolf gets ignored. Optimize for precision (low false positives) before recall (catching everything).
  4. Anomaly ≠ problem — An anomaly is a statistical observation, not an automatic incident. Always pair detection with investigation.
  5. Simple methods first — Z-scores and IQR catch most anomalies. Don't reach for Isolation Forests until simple methods have failed.
  6. Stationarity matters — Most statistical methods assume your data doesn't change character over time. If it does, you need methods that handle trend, seasonality, or concept drift.

Methodology Reference

Tier 1: Statistical Methods (Start Here)

Use these when data is well-understood, roughly stationary, and you can define "normal" numerically.

MethodHow It WorksBest ForAssumptionsLimitations
Z-ScoreFlag points > k standard deviations from the meanUnivariate, roughly normal dataNormal distribution, no trendFails with skewed data, sensitive to outliers in training set
Modified Z-Score (MAD)Uses median absolute deviation instead of std devSame as Z-score but robust to existing outliersSymmetric distributionLess sensitive than Z-score for normally distributed data
IQR (Interquartile Range)Flag points outside Q1 − 1.5·IQR or Q3 + 1.5·IQRNon-normal, skewed distributionsNone (non-parametric)Misses anomalies in heavy-tailed distributions
Grubbs' TestHypothesis test for a single outlierConfirming a specific point is an outlierNormal distribution, one outlier at a timeOnly tests one point per run
Control Charts (Shewhart)Mean ± 3σ boundaries on sequential dataManufacturing, SPC, stable processesStationary processDoesn't handle seasonality or trend

When to use Tier 1: You have a single metric, the distribution is understandable, and you can eyeball what "normal" looks like. Most operational alerting starts here.

Tier 2: Time Series Methods

Use when your data has trend, seasonality, or autocorrelation that invalidates simple statistical bounds.

MethodHow It WorksBest ForAssumptionsLimitations
Moving Average ± BandRolling mean ± k · rolling stdSlow-moving metrics with noiseLocal stationarityLags behind sudden shifts
Exponential Smoothing (ETS)Weighted average favoring recent observationsTrended or seasonal univariate seriesConsistent trend/seasonality patternStruggles with abrupt regime changes
STL Decomposition + ResidualDecompose into trend + seasonal + residual; flag large residualsStrongly seasonal data (daily/weekly patterns)Additive or multiplicative seasonalityNeeds ≥ 2 full seasonal cycles
ARIMA / SARIMAFit autoregressive model; flag points outside prediction intervalStationary or differenced seriesLinear relationships, stationary residualsRequires parameter tuning (p, d, q)
ProphetAdditive model with trend, seasonality, holidaysBusiness metrics with known calendar effectsAdditive componentsCan overfit with little data; slow on large series
CUSUM / EWMA ChartsAccumulate deviations from target; signal when cumulative sum exceeds thresholdDetecting small, persistent shiftsStationary baselineNot designed for sudden spikes (better for drift)

When to use Tier 2: Your metric has daily, weekly, or seasonal patterns. A flat threshold would fire every Monday morning or every holiday.

Tier 3: Machine Learning Methods

Use when the data is multivariate, the patterns are complex, or statistical methods can't capture what "normal" means.

MethodHow It WorksBest ForProsCons
Isolation ForestRandomly partitions feature space; anomalies are isolated in fewer splitsTabular multivariate dataNo distribution assumptions, handles high dimensionalityRequires training data, not inherently temporal
Local Outlier Factor (LOF)Compares local density of a point to its neighborsClusters of varying densityDetects local anomalies that global methods missExpensive on large datasets; sensitive to k
One-Class SVMLearns a boundary around "normal" dataSmall datasets with clean normal examplesWorks in high dimensionsSensitive to kernel choice, slow on large data
Autoencoder (Neural)Learns to reconstruct normal data; high reconstruction error = anomalyComplex, high-dimensional data (images, logs, embeddings)Captures non-linear patternsNeeds significant normal data; opaque
DBSCANDensity-based clustering; points not in any cluster are anomaliesSpatial or clustered dataNo need to specify cluster countSensitive to epsilon and min_samples

When to use Tier 3: Simple methods produce too many false positives, the data is multivariate, or "normal" is a complex region in feature space — not a simple range.


Selection Strategy

Follow this decision tree to choose a method:

1. Is the data univariate (single metric)?
   ├── Yes → Is there seasonality or trend?
   │         ├── No  → Tier 1: Z-Score, IQR, or Control Chart
   │         └── Yes → Tier 2: STL + Residual, SARIMA, or Prophet
   └── No (multivariate) → 
       Is labeled anomaly data available?
       ├── Yes → Supervised classifier (beyond this skill's scope)
       └── No  → Tier 3: Isolation Forest, LOF, or Autoencoder

2. How much data is available?
   ├── < 100 points   → Tier 1 only (not enough for ML)
   ├── 100–10,000     → Tier 1 or Tier 2
   └── > 10,000       → Any tier is viable

3. What's the cost of a false positive vs. false negative?
   ├── FP is expensive (alert fatigue, manual investigation)
       → Favor higher thresholds, conservative methods (IQR, Grubbs')
   └── FN is expensive (missed fraud, missed outage)
       → Favor lower thresholds, ensemble methods

Process

Step 1: Characterize the Data

Before selecting a method, understand what you're working with:

## Data Profile

**Source**: <e.g., "Prometheus metric: api_request_latency_p99">
**Type**: <univariate | multivariate> — <time series | tabular | event stream>
**Volume**: <row/point count, time range>
**Frequency**: <per-second | per-minute | daily | irregular>
**Distribution**: <roughly normal | skewed | heavy-tailed | multimodal | unknown>
**Stationarity**: <stationary | trend | seasonal | both | unknown>
**Known patterns**: <e.g., "higher on weekdays, spikes during deploys">
**Labeled anomalies available?**: <yes (n examples) | no>

Step 2: Define What "Anomalous" Means

An anomaly is domain-specific. Define it before applying any method:

## Anomaly Definition

**Point anomaly**: A single observation that deviates significantly
  → Example: "latency > 500ms when baseline is 50ms"

**Contextual anomaly**: Normal in one context, abnormal in another
  → Example: "1000 rps is normal at 2pm, anomalous at 3am"

**Collective anomaly**: A sequence of observations that together are unusual
  → Example: "5 consecutive requests from the same IP to /admin"

**Detection goal**: <Which type(s) are we looking for?>
**Action on detection**: <Alert | Log | Auto-remediate | Queue for investigation>

Step 3: Establish the Baseline

Build a model of "normal" before looking for deviations:

  • For statistical methods: Compute mean, median, std dev, percentiles on a clean reference period (no known incidents)
  • For time series methods: Decompose into trend + seasonality + residual on historical data
  • For ML methods: Train on a dataset of known-good observations
## Baseline

**Reference period**: <date range used for baseline>
**Exclusions**: <removed known incidents, maintenance windows, deploys>
**Statistics**: mean=<X>, median=<X>, std=<X>, p50=<X>, p95=<X>, p99=<X>
**Seasonality**: <daily cycle? weekly? none?>

Step 4: Select and Apply the Method

Choose a method from the tiers above using the selection strategy. Document the choice:

## Method Selection

**Method**: <name>
**Tier**: <1 | 2 | 3>
**Why this method**: <reasoning tied to data profile>
**Parameters**: <e.g., "Z-score threshold = 3.0", "IQR multiplier = 1.5", "Isolation Forest contamination = 0.01">
**Alternatives considered**: <what else was viable and why it wasn't chosen>

Step 5: Evaluate Results

Every detection method needs calibration. Check these before trusting results:

CheckWhat to Look For
False positive rateAre flagged points actually anomalous? Manually inspect a sample.
False negative rateAre known anomalies being caught? Test against historical incidents.
Threshold sensitivityHow much do results change with ±10% threshold adjustment?
Temporal stabilityDoes the method degrade over time as data distribution shifts?
Edge behaviorDoes it flag every Monday? Every deploy? Every restart? (Contextual blindness)
## Evaluation

**Flagged anomalies**: <count>
**Manually verified (sample of N)**: <true positive rate>
**Known incidents caught**: <X of Y>
**False positive pattern**: <e.g., "flags every deploy; needs deploy-window exclusion">
**Recommended threshold adjustment**: <raise / lower / add context filter>

Step 6: Operationalize (If Building a Pipeline)

For ongoing detection (not one-time analysis):

## Operational Design

**Detection frequency**: <real-time | every 5 min | hourly | daily>
**Baseline refresh**: <static | rolling window of N days | retrain weekly>
**Alert routing**: <PagerDuty | Slack channel | log only>
**Suppression rules**: <e.g., "suppress during deploy windows", "deduplicate within 30 min">
**Escalation**: <when does a detected anomaly become an incident?>
**Dashboard**: <link to Grafana / CloudWatch / custom dashboard>

Output Format

Every anomaly detection analysis should produce:

  1. Data Profile — What the data looks like
  2. Anomaly Definition — What counts as anomalous in this domain
  3. Baseline — What "normal" looks like, with statistics
  4. Method Selection — Which method, why, and with what parameters
  5. Results — What was flagged, with evaluation of accuracy
  6. Operational Design — How to run this ongoing (if applicable)

Combining Methods

Real-world pipelines often layer methods for better results:

PatternHow It WorksWhen to Use
Decompose + ThresholdSTL/seasonal decomposition → Z-score or IQR on residualsSeasonal data where raw Z-scores fire on every peak
Ensemble votingRun 2–3 methods; flag only when ≥ 2 agreeReducing false positives when no single method is reliable
Tiered detectionTier 1 for fast screening → Tier 3 on flagged windowsHigh-volume data where ML on every point is too expensive
Context layeringStatistical method + deploy/event calendar → suppress known causesOperational alerting where deploys and maintenance cause expected spikes

Rule of thumb: Don't combine methods to increase sensitivity — combine them to increase precision (fewer false positives).


Tooling Reference

LibraryLanguageBest For
scipy.statsPythonZ-scores, Grubbs', distribution tests
statsmodelsPythonSTL decomposition, ARIMA, ETS, control charts
scikit-learnPythonIsolation Forest, LOF, One-Class SVM, DBSCAN
prophetPythonBusiness metrics with calendar seasonality
pyodPythonUnified API for 30+ anomaly detection algorithms
adtkPythonTime series anomaly detection toolkit
rupturesPythonChange point detection
Grafana MLDashboardBuilt-in anomaly detection on Prometheus/InfluxDB metrics

Use the statistics skill for assumption validation (normality tests, distribution checks) before applying Tier 1 methods.


Common Pitfalls

PitfallWhy It Fails
Training on dirty dataIf the baseline includes anomalies, the model learns them as normal
Flat thresholds on seasonal dataA fixed "alert at > 100ms" fires every peak hour and gets ignored
Ignoring concept driftA model trained 6 months ago may flag today's normal traffic as anomalous
Over-alerting50 alerts per day = zero alerts acted on. Fewer, high-confidence alerts win.
Skipping manual inspectionAuto-detected anomalies must be spot-checked. Precision matters.
Using ML when Z-scores workComplexity for its own sake adds maintenance burden and opacity
Confusing anomaly with root causeDetection tells you something is unusual, not why. Investigation is a separate step.
No baseline exclusionsIncluding Black Friday in baseline data makes next week look anomalous

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.