Editor

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 lesson

Implement 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.

import pandas as pd
import numpy as np
np.random.seed(42)
dates = pd.date_range('2024-01-01', periods=90, freq='D')
base = 1000 + np.arange(90) * 5
weekend_boost = np.where(dates.dayofweek >= 5, 200, 0)
noise = np.random.normal(0, 80, 90)
sales = np.maximum(base + weekend_boost + noise, 0)
df = pd.DataFrame({'sales': np.round(sales, 2)}, index=dates)
# Implement Z-score anomaly detection

More Time Series exercises

All Python exercises · 50 practice problems · Practical Projects quiz