Time series anomalies with Azure Anomaly Detector
This tutorial shows how to detect anomalies in time series with Azure Anomaly Detector, useful for monitoring metrics such as traffic, sales or telemetry. Learn why detections occur, how to prepare the series, send requests to the API and visualize anomalous points with a Python example.
Prerequisites
- Azure account with an Azure Anomaly Detector resource created (key and endpoint).
- Python 3.8+ installed and pip.
- Libraries: requests, matplotlib, pandas (install in step 2).
- CSV file or time series in timestamp+value format.
Step 1: Create the Azure Anomaly Detector resource
In the Azure portal create an Azure Anomaly Detector resource (resource type: Anomaly Detector). After creating it, copy the Key and the Endpoint. You will need those values to authenticate the HTTP requests.
Step 2: Install dependencies and prepare data
Install the required libraries and prepare a small example time series. The series must have timestamps in ISO 8601 and numeric values. Here we use a synthetic example embedded in the code.
pip install requests pandas matplotlib
# exemplo_dataset.py
import pandas as pd
from datetime import datetime, timedelta
# Gerar 60 dias de dados com algumas anomalias
start = datetime(2023, 1, 1)
dates = [start + timedelta(days=i) for i in range(60)]
values = [100 + (i * 0.5) for i in range(60)]
# inserir anomalias artificiais
values[10] = 200
values[35] = 40
df = pd.DataFrame({'timestamp': [d.isoformat() for d in dates], 'value': values})
print(df.head())
Step 3: Send the series to the Entire Detection endpoint
We use the Azure Anomaly Detector REST API to detect anomalies across the whole series (Entire detection). The typical endpoint is: {endpoint}/anomalydetector/v1.1/timeseries/entire/detect. Replace YOUR_ENDPOINT and YOUR_KEY with your values.
import requests
import json
import pandas as pd
ENDPOINT = "https://YOUR_ENDPOINT" # sem slash final
KEY = "YOUR_KEY"
# carregar dados do exemplo
from exemplo_dataset import df
url = f"{ENDPOINT}/anomalydetector/v1.1/timeseries/entire/detect"
headers = {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': KEY
}
body = {
'series': [{'timestamp': t, 'value': float(v)} for t, v in zip(df['timestamp'], df['value'])],
'granularity': 'daily'
}
resp = requests.post(url, headers=headers, json=body)
resp.raise_for_status()
result = resp.json()
print(json.dumps(result, indent=2))
Step 4: Interpret the response and isolate anomalies
The response for Entire detection includes arrays such as isAnomaly, isPositiveAnomaly and anomalyScore. Iterate over those arrays to find which timestamps are anomalous.
# assumir 'result' do passo anterior
is_anomaly = result.get('isAnomaly', [])
anomaly_score = result.get('anomalyScore', [])
anomalies = []
for i, flag in enumerate(is_anomaly):
if flag:
anomalies.append({'timestamp': df.at[i, 'timestamp'], 'value': df.at[i, 'value'], 'score': anomaly_score[i] if anomaly_score else None})
print('Anomalias detectadas:', len(anomalies))
for a in anomalies:
print(a)
Step 5: Visualize the series and mark anomalies
A quick visualization helps validate whether the anomalies make sense. Use matplotlib to plot the series and mark anomalous points in red.
import matplotlib.pyplot as plt
# preparar dados para plot
df['timestamp_dt'] = pd.to_datetime(df['timestamp'])
def plot_with_anomalies(df, anomalies):
plt.figure(figsize=(10,4))
plt.plot(df['timestamp_dt'], df['value'], label='valor')
if anomalies:
ann_ts = [pd.to_datetime(a['timestamp']) for a in anomalies]
ann_vals = [a['value'] for a in anomalies]
plt.scatter(ann_ts, ann_vals, color='red', label='anomalia', zorder=5)
plt.xlabel('data')
plt.ylabel('valor')
plt.title('Série temporal com anomalias detectadas')
plt.legend()
plt.tight_layout()
plt.show()
plot_with_anomalies(df, anomalies)
Verify the result
Confirm that the number of anomalies is plausible: 1) print the list of anomalies and check timestamps; 2) compare the red points on the chart with visible peaks/valleys; 3) if you get HTTP errors, check the key, endpoint and the JSON format (Content-Type).
Conclusion
With Azure Anomaly Detector you can analyze time series quickly without training models. Next steps: test different granularities (hourly, weekly), use the sliding window endpoint for streaming detection, and integrate into a pipeline with Azure Functions or Azure Machine Learning for automatic alerts. Tip: start by validating with synthetic data (as here) before connecting production telemetry — which metrics of your application do you want to monitor first?