Time Series Anomaly Detection: Finding Unusual Patterns in Temporal Data
Detect anomalies in time series — point, contextual, and collective anomalies; statistical and ML methods; changepoint detection; and best practices.
Time Series Anomaly Detection: Finding Unusual Patterns in Temporal Data
Time series anomaly detection identifies observations or segments that deviate from expected behavior. This guide covers types of anomalies, statistical and machine learning methods, changepoint detection, and how to use them in practice.
---
What Are Time Series Anomalies?
| Type | Definition | Example |
|---|---|---|
| Point anomalies | Single value is unusual | Spike in CPU usage at 2:00 AM |
| Contextual anomalies | Unusual in context (e.g., for that day of week) | Sales drop on a Monday that is normally busy |
| Collective anomalies | A subsequence is unusual as a whole | Sudden level shift for several days |
| Changepoints | Structural break; the generating process changes | Regime change in stock volatility |
---
Use Cases
| Domain | What You Detect |
|---|---|
| Server / application monitoring | Spikes, drops, prolonged outages |
| Fraud | Unusual transactions, login patterns |
| Sensor / IoT | Malfunction, tampering, environmental shocks |
| Retail / demand | Stock-outs, demand shocks, promo effects |
| Finance | Flash crashes, unusual volatility |
Statistical Methods
Moving Average Deviation
- Compute a rolling mean (and optionally std) over a window.
- Flag points that exceed k standard deviations from the rolling mean.
- Pros: Simple, fast. Cons: Lag; sensitive to window size and k.
| Parameter | Effect |
|---|---|
| Window size | Longer = smoother baseline, less sensitive to spikes |
| k (threshold) | Higher = fewer alerts; lower = more false positives |
STL Residuals
- Decompose series with STL (Seasonal-Trend decomposition using LOESS).
- Residual = observed − (trend + seasonal).
- Flag residuals that exceed a threshold (e.g., z-score > 3).
- Pros: Handles trend and seasonality. Cons: Needs enough data for stable decomposition.
Z-Score on Residuals
- After removing trend/season (e.g., via STL or differencing), compute z-score of residuals.
- Flag |z| > 2 or 3.
- Pros: Simple, interpretable. Cons: Assumes residuals are roughly normal; sensitive to outliers in std estimate (use MAD or robust stats if needed).
Machine Learning Methods
Isolation Forest on Features
- Build features from the TS: rolling mean, std, lagged values, day-of-week, etc.
- Train Isolation Forest (or similar) on normal data.
- Anomalies are points that require few splits to isolate — they are "far" from the rest.
- Pros: No distribution assumption; handles multivariate features. Cons: Needs feature engineering; threshold is tunable.
LSTM Reconstruction Error
- Train an LSTM autoencoder to reconstruct the series.
- Reconstruction error = |actual − reconstructed|.
- High error → anomaly (model couldn't predict it).
- Pros: Captures complex temporal structure. Cons: Needs lots of data; computationally heavy.
Prophet Anomaly Detection
- Fit Prophet to the series.
- Prophet can mark points as anomalies where the residual exceeds a threshold.
- Pros: Built-in; handles trend + seasonality. Cons: Tuned for daily data; threshold choice matters.
Detecting Changepoints
Changepoints are times when the underlying process changes (mean, variance, trend).
CUSUM (Cumulative Sum)
- Tracks cumulative deviation from a target (e.g., mean).
- A changepoint is signaled when CUSUM exceeds a control limit.
- Pros: Fast, online. Cons: Assumes known baseline; single changepoint focus.
PELT (Pruned Exact Linear Time)
- Finds multiple changepoints by minimizing a cost (e.g., negative log-likelihood) plus penalty.
- Pros: Multiple changepoints; efficient. Cons: Penalty tunes number of changepoints.
Bayesian Changepoint Detection
- Models changepoints with a prior; infers posterior over their locations.
- Pros: Uncertainty quantification. Cons: More complex; slower.
Choosing a Method
| Situation | Recommended Approach |
|---|---|
| Simple series, few patterns | Moving average + z-score |
| Clear trend/seasonality | STL + residuals or Prophet |
| Multivariate / rich features | Isolation Forest |
| Complex long-range structure, lots of data | LSTM autoencoder |
| Need changepoints | CUSUM, PELT, or Bayesian |
| Little data | Simple stats; avoid heavy ML |
Evaluation Challenges
- No ground truth: Anomalies are often labeled by experts; incomplete or biased.
- Class imbalance: Anomalies are rare; accuracy is misleading; use precision, recall, F1, or AUC-PR.
- Temporal leakage: Train only on past data; validate with time-based splits.
- Threshold sensitivity: Same method with different thresholds gives different precision/recall; tune on validation set.
Handling Seasonality
| Step | Action |
|---|---|
| 1 | Decompose (STL, classical, or Prophet) |
| 2 | Work on residuals (or use methods that model seasonality) |
| 3 | Or use contextual features (hour, day-of-week) so "normal" depends on context |
| 4 | For daily data, consider day-of-week adjustments before flagging |
---
Using in the Platform
- Load your time series (date + value columns).
- Select anomaly detection method (e.g., STL residuals, Prophet, Isolation Forest).
- Configure window, threshold, or other parameters.
- Run and inspect flagged points.
- Export or feed results into dashboards and alerts.
---
Common Pitfalls
| Pitfall | Fix |
|---|---|
| Ignoring seasonality | Decompose first or use seasonal models |
| Threshold too low | Too many false positives; tune on validation |
| Threshold too high | Miss real anomalies; review missed cases |
| Training on contaminated data | Remove known anomalies before training, or use robust methods |
| Leaking future into past | Strict temporal splits; no future data in training |
| Treating all anomalies alike | Different severity; consider scores and post-filtering |
Quick Reference
| Method | Best For | Key Parameter |
|---|---|---|
| Moving average + z-score | Simple, fast | Window, k |
| STL residuals | Trend + seasonal | Decomposition window |
| Prophet | Daily, with holidays | Residual threshold |
| Isolation Forest | Feature-rich | Contamination / threshold |
| LSTM autoencoder | Complex patterns, big data | Architecture, threshold |
| CUSUM / PELT | Changepoints | Control limit / penalty |
What's Next?
- [Time Series Overview](ts-overview) — Platform workflow
- [Anomaly Detection Guide](anomaly-detection-guide) — General anomaly detection
- [Time Series Analysis Tools](ts-analysis-tools) — Decomposition, stationarity
- [Statistics Overview](statistics-overview) — Foundational statistics
Related Articles
Time Series Overview: What It Is and How to Use It
A beginner-friendly guide to time series data: what it is, key concepts like trend and seasonality, the full workflow, choosing algorithms, and real-world examples.
Anomaly Detection: Finding Outliers and Unusual Patterns
Learn how to detect anomalies and outliers using statistical and ML methods. Covers Z-score, IQR, Isolation Forest, LOF, and best practices for imbalanced anomaly data.
Time Series Analysis Tools
Understand decomposition, stationarity tests, ACF/PACF analysis, and resampling for time series data.
Statistics Overview: What Are Statistics and How to Use Them
A beginner-friendly introduction to statistics, descriptive vs inferential analysis, the Statistics workspace layout, and running your first analysis.
Was this helpful?