Flag Anomalous Days
Advanced · Write the code · from Time Series: Detect Trends and Anomalies in Business Data
From the lesson: Step 5: Detect Anomalies
An anomaly is a data point that doesn't fit the expected pattern. Maybe a marketing campaign caused a sales spike, or a server outage caused a drop. Detecting anomalies automatically lets you investigate unusual events without manually scanning hundreds of data points.
Read this part of the lessonImplement Z-score anomaly detection:
1. Calculate the mean and standard deviation of sales.
2. Add a z_score column: (sales - mean) / std.
3. Add an is_anomaly column: True if abs(z_score) > 2.
4. Print "=== ANOMALY DETECTION ===" as header.
5. Print the total number of anomalies found.
6. For each anomaly, print the date, sales value, and z-score: "{date}: ${sales:.2f} (z={z_score:.2f})".
7. If no anomalies at threshold 2, try threshold 1.5 and note the change.
More Time Series exercises
- Build the Time Series DataFrameAdvanced
- Compute Moving AveragesAdvanced
- Measure the TrendAdvanced
- Discover Seasonal PatternsAdvanced
- The Complete Trend ReportAdvanced
All Python exercises · 50 practice problems · Practical Projects quiz