Skip to content

Latest commit

Β 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ“Š AI Business Anomaly Detection Agent

An end-to-end analytics project that detects unusual revenue behavior, identifies the numerical drivers behind anomalies, and generates business-friendly AI explanations.

The project combines statistical anomaly detection, revenue driver analysis, Gemini AI, and an interactive Streamlit dashboard.


🎯 Project Objective

Business teams often monitor KPIs such as revenue, orders, and sales volume manually.

This project builds an automated workflow that:

  1. Cleans transaction-level retail data
  2. Calculates daily business KPIs
  3. Detects statistically unusual revenue behavior
  4. Identifies the metrics associated with each anomaly
  5. Generates grounded AI explanations
  6. Presents the results in an interactive dashboard

The statistical model determines whether an observation is anomalous.

AI is used only to interpret the detected metrics and does not decide whether an anomaly exists.


πŸ“‚ Dataset

The project uses the Online Retail II dataset.

The raw dataset contains more than one million transaction records across two years.

Dataset processing

  • Raw rows: 1,067,371
  • Rows after duplicate removal: 1,033,036
  • Valid sales rows: 1,007,914
  • Return/cancellation rows: 22,496
  • Total analysed sales revenue: Β£20,476,634.02

Operational records such as cancellations and returns are preserved separately instead of being silently deleted.


πŸ“ˆ Business KPIs

Transaction-level data is aggregated into 604 daily observations.

The main KPIs are:

  • Daily Revenue
  • Orders
  • Units Sold
  • Average Order Value
  • Cancellation Count
  • Cancelled Units
  • Cancellation Value

🚨 Anomaly Detection

Revenue anomalies are detected using two complementary historical baselines.

1. Rolling Historical Baseline

For each day, revenue is compared with the previous 7 observations.

The model calculates:

  • Rolling mean
  • Rolling standard deviation
  • Revenue deviation percentage
  • Rolling Z-score

Only previous observations are used.

2. Historical Weekday Baseline

Revenue is also compared with previous observations from the same day of the week.

For example, a Monday is compared only with earlier Mondays.

This helps account for weekly trading patterns.

Importantly, future observations are never used to score earlier dates, preventing look-ahead leakage.

Detection Rule

A day is flagged when:

|Rolling Z-score| >= 3
OR
|Historical Weekday Z-score| >= 3

Final Results

The production detector identified:

Result Count
Daily observations 604
Detected anomalies 37
Revenue Spikes 26
Critical Revenue Spikes 7
Revenue Drops 4

πŸ” Revenue Driver Analysis

Revenue is decomposed as:

Revenue
=
Orders
Γ— Units Per Order
Γ— Average Price Per Unit

For detected critical anomalies, each component is compared with its recent historical baseline.

The system identifies:

  • Primary Driver
  • Secondary Driver
  • Offsetting Factor

A 20% deviation threshold is used when assigning driver labels.

These labels represent numerical associations with the anomaly and should not be interpreted as proof of business causation.

Example

For 09 Dec 2011:

Revenue: Β£200,918.98
Revenue deviation: +221.9%

Primary Driver:
Units Per Order +666.9%

Offsetting Factor:
Orders -60.3%

The metrics therefore show that the revenue spike was associated with unusually large quantities per order despite substantially fewer orders.


πŸ€– AI Business Explanations

The project uses the Gemini API to translate anomaly metrics into concise business explanations.

The AI receives only the calculated anomaly statistics and driver information.

Prompt guardrails instruct the model to:

  • Use only supplied numerical evidence
  • Avoid inventing business causes
  • Avoid unsupported speculation
  • Clearly state when the underlying cause is unknown
  • Recommend reviewing underlying transactions when necessary

AI explanations are therefore an interpretation layer, not the anomaly detection engine.

πŸ“§ Automated Email Alerts

The project also includes an automated monitoring and alerting workflow.

When the agent runs, it:

  1. Rebuilds the daily KPI dataset
  2. Detects revenue anomalies
  3. Identifies critical revenue spikes
  4. Checks whether each anomaly has already been alerted
  5. Generates a Gemini explanation only for new anomalies
  6. Sends a Gmail alert containing the anomaly details
  7. Records successfully sent alerts to prevent duplicates

The alert history is stored locally in:

outputs/alert_log.csv

This runtime file is excluded from GitHub.

Duplicate Alert Prevention

Each anomaly is identified using its:

Date + Anomaly Type

Before sending an email, the agent checks the alert history.

If an anomaly was already processed:

Existing anomaly
      ↓
Reuse saved AI explanation
      ↓
No Gemini API call
      ↓
No duplicate email

If a new critical anomaly is detected:

New anomaly
      ↓
Generate Gemini explanation
      ↓
Send Gmail alert
      ↓
Record successful alert

This prevents unnecessary API usage and repeated notifications.


⏰ Scheduled Automation

The complete pipeline can be executed with:

python run_agent.py

For Windows automation, the repository also includes:

run_agent.bat

The batch file launches the project's virtual-environment Python interpreter and writes execution logs to:

outputs/agent_run.log

The project can be scheduled through Windows Task Scheduler.

In the current setup, the anomaly agent runs automatically every day at:

09:00 AM

This turns the project from a static analytics dashboard into an automated monitoring system.


πŸ–₯️ Streamlit Dashboard

The Streamlit dashboard provides:

KPI Overview

  • Total Revenue
  • Total Orders
  • Detected Anomalies
  • Critical Revenue Spikes

Revenue Monitoring

An interactive revenue time-series chart displays detected anomalies directly on the revenue trend.

Critical Anomaly Investigation

Users can select an anomaly and inspect:

  • Revenue
  • Revenue deviation
  • Primary driver
  • Secondary driver
  • Offsetting factor
  • AI-generated business explanation

Critical Spike Table

The dashboard also provides a summary table of all critical anomalies and their identified driver signals.

πŸ“Έ Dashboard Preview

Dashboard Overview

Dashboard Overview

Critical Anomaly Investigation

Critical Anomaly Investigation

Critical Revenue Spikes

Critical Revenue Spikes


πŸ› οΈ Technologies Used

  • Python
  • Pandas
  • NumPy
  • OpenPyXL
  • Altair
  • Streamlit
  • Google Gemini API
  • Jupyter Notebook

πŸ—οΈ Project Structure

AI_Anomaly_Agent/
β”‚
β”œβ”€β”€ data/
β”‚   └── online_retail_II.xlsx
β”‚
β”œβ”€β”€ notebooks/
β”‚   └── 01_anomaly_analysis.ipynb
β”‚
β”œβ”€β”€ outputs/
β”‚   β”œβ”€β”€ daily_kpis_final.csv
β”‚   └── anomaly_report_final.csv
β”‚
β”œβ”€β”€ screenshots/
β”‚   β”œβ”€β”€ dashboard_overview.png
β”‚   β”œβ”€β”€ anomaly_investigation.png
β”‚   └── critical_spikes.png
β”‚
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ data_processing.py
β”‚   β”œβ”€β”€ anomaly_detection.py
β”‚   β”œβ”€β”€ driver_analysis.py
β”‚   β”œβ”€β”€ ai_explanation.py
β”‚   β”œβ”€β”€ alert_log.py
β”‚   └── email_alert.py
β”‚
β”œβ”€β”€ app.py
β”œβ”€β”€ run_agent.py
β”œβ”€β”€ run_agent.bat
β”œβ”€β”€ requirements.txt
β”œβ”€β”€ .gitignore
└── README.md

βš™οΈ Installation

Clone the repository:

git clone https://github.com/Aljesh/AI_Anomaly_Agent.git
cd AI_Anomaly_Agent

Create a virtual environment:

python -m venv .venv

Activate it on Windows:

.venv\Scripts\activate

Install dependencies:

pip install -r requirements.txt

▢️ Run the Dashboard

From the project root:

python -m streamlit run app.py

Then open the local Streamlit URL shown in the terminal.

Usually:

http://localhost:8501

πŸ”‘ Gemini API Setup

The dashboard can display previously generated AI explanations from the saved anomaly report without making a new API request.

To regenerate AI explanations, create a Gemini API key and store it as an environment variable:

GEMINI_API_KEY

Never commit API keys to GitHub.


🧠 Methodology Notes

No Look-Ahead Leakage

Historical baselines only use observations available before the date being evaluated.

Rolling Window

The rolling baseline uses the previous 7 observations, not necessarily seven consecutive calendar days.

Threshold Selection

The Z-score threshold of 3 and driver threshold of 20% are heuristic business-analysis thresholds rather than statistically optimized values.

No Ground-Truth Labels

The dataset does not contain verified anomaly labels.

Therefore, metrics such as model accuracy, precision, recall, and F1-score are not claimed.

Driver Analysis β‰  Causality

The system identifies metrics associated with unusual revenue behavior.

It does not prove the underlying causal business explanation.

Transaction-level investigation is required to establish the actual cause.


πŸ’‘ Key Takeaway

This project demonstrates how traditional analytics and generative AI can work together:

Transaction Data
      ↓
Data Cleaning
      ↓
Daily KPI Calculation
      ↓
Statistical Anomaly Detection
      ↓
Revenue Driver Analysis
      ↓
Grounded AI Explanation
      ↓
Interactive Streamlit Dashboard

Statistical methods detect the anomaly.

Business decomposition explains the numerical pattern.

Generative AI communicates the findings in a manager-friendly format.


πŸš€ Possible Future Improvements

  • Add anomaly validation using labelled or synthetic anomalies
  • Investigate anomalies at product and country level
  • Add configurable anomaly thresholds
  • Add date-range filtering
  • Add automated data refresh
  • Deploy the dashboard to a cloud platform

About

AI-powered business anomaly detection system using Python, statistical baselines, Gemini AI, Streamlit, automated Gmail alerts, and scheduled monitoring.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages