A useful anomaly score compares an observation with the expectation for its own context, not with one global average.
Contextual anomaly baselines: seasonality, exposure and missing periods
Segment the calendar
Compare Monday morning with comparable Monday mornings before comparing it with Saturday night. Include a known release or holiday marker only when that marker was available at the decision point. Thin segments need a broader fallback and an uncertainty range; a perfectly fitted mean from two prior hours creates noisy alerts. The observation calendar determines which periods genuinely existed.
Separate count from opportunity
Thirty receipts may be normal for a tenant with 40 active users and alarming for one with 4,000. Use an exposure measure such as active sessions or eligible orders when it is reliable and timely. If exposure is missing or late, report that condition explicitly. A ratio with a near-zero denominator can explode even when the numerator is ordinary.
Score residuals
A residual is observed volume minus expected volume. A scale-adjusted residual can compare tenants of different sizes, but the scale must be estimated from past comparable periods and bounded away from zero. Keep the raw count and expected count alongside the score so an investigator can explain the alert without decoding a model embedding.
Run a fixture
Use prior comparable counts of 43, 47, 45 and 49; their median is 46. A new count of 5 has residual minus 41. A missing observation has no residual. Add a holiday marker with a separate history of 6 and 8, and check that a new count of 5 is much less surprising in that context.
Implementation
from statistics import median
def contextual_residual(observed_count, comparable_counts):
if observed_count is None or not comparable_counts:
return None
expected_count = median(comparable_counts)
return observed_count - expected_countPerformance and operating cost
Finding the median of H comparable observations is O(H log H) time with a sort-based implementation and O(H) memory. Precomputed seasonal summaries reduce request cost, but their version and cutoff must be recorded with each alert.
Common Mistakes
- Do not turn a missing period into an observed zero.
- Do not compare dissimilar calendar periods through one global threshold.
- Do not divide by an exposure measure that is late, zero or untrusted.
