Systems Library
/
Operations & Admin
/
How to Build an Anomaly Detection System for Business Metrics
Operations & Admin
reporting analytics
How to Build an Anomaly Detection System for Business Metrics
Detect unusual patterns in business data and alert before issues escalate.
Jay Banlasan
The AI Systems Guy
This anomaly detection system for business metrics flags unusual patterns before they become problems. I use it to catch revenue drops, traffic spikes, and support surges in real time.
What You Need Before Starting
- Python 3.8+
- Data source API access
- pandas and matplotlib installed
- SMTP for email delivery
Step 1: Connect Data Sources
Set up API connections for anomaly detection.
import requests
from datetime import datetime
def fetch_data(api_config):
results = {}
for source in api_config:
response = requests.get(source["url"], headers=source.get("headers", {}))
if response.status_code == 200:
results[source["name"]] = response.json()
results["fetched_at"] = datetime.now().isoformat()
return results
Step 2: Process and Calculate
Transform raw data into the metrics you need.
import pandas as pd
def calculate_metrics(raw_data):
df = pd.DataFrame(raw_data)
metrics = {
"total": df["value"].sum(),
"average": df["value"].mean(),
"trend": df["value"].pct_change().tail(7).mean(),
"period": datetime.now().strftime("%Y-%m-%d"),
}
return metrics
Step 3: Generate the Report
Build the report using your template.
from jinja2 import Template
REPORT = Template("""
<h2>{{ title }} - {{ date }}</h2>
<table>
{% for metric, value in metrics.items() %}
<tr><td>{{ metric }}</td><td>{{ value }}</td></tr>
{% endfor %}
</table>
""")
def build_report(metrics, title):
return REPORT.render(title=title, date=datetime.now().strftime("%Y-%m-%d"), metrics=metrics)
Step 4: Add AI Commentary
Use Claude to explain what the numbers mean.
import anthropic
def add_narrative(metrics):
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-sonnet-4-20250514", max_tokens=500,
messages=[{"role": "user",
"content": f"Write a 3-sentence analysis of these metrics. Be specific.\n{json.dumps(metrics)}"}])
return message.content[0].text
Step 5: Schedule Delivery
Automate report generation and distribution.
import smtplib
from email.mime.text import MIMEText
def send_report(html_content, recipients, subject):
msg = MIMEText(html_content, "html")
msg["Subject"] = subject
for recipient in recipients:
msg["To"] = recipient
with smtplib.SMTP("smtp.gmail.com", 587) as server:
server.starttls()
server.login("[email protected]", "app-password")
server.send_message(msg)
What to Build Next
Feed anomaly alerts into Slack so your team sees them immediately.
Related Reading
- How to Use AI for Anomaly Detection - ai anomaly detection business
- How to Build Automated Alerts That Actually Help - automated alerts that help
- Setting Up Automated Inventory Alerts - automated inventory alerts setup
Want this system built for your business?
Get a free assessment. We will map every system your business needs and show you the ROI.
Get Your Free Assessment