Fraud Detection | Transaction Anomaly Analysis

2025
Python Django XGBoost scikit-learn SHAP pandas NumPy MySQL Parquet Machine Learning Fraud Detection Anomaly Detection Feature Engineering Class Imbalance Explainable AI Time Series Data Engineering

A production-shaped machine learning system for detecting fraudulent
banking transactions in real time.

The project covers the full fraud detection lifecycle: synthetic data
generation, temporal feature engineering, model training and comparison,
explainability with SHAP, and an interactive Django front-end that scores
transactions on demand.

The pipeline is trained on a 100,000-transaction synthetic banking dataset
spanning four years and 5,000 clients. Fraud is injected at 1.7% using five
distinct patterns — account takeover, card compromise, velocity attacks,
geographic anomalies, and merchant anomalies — each with its own signature
across the 82 engineered features.

The final model is an XGBoost classifier with a PR-AUC of 0.998 on a
held-out chronological test set. Every prediction is accompanied by SHAP
values showing exactly which inputs pushed the score toward fraud and which
pulled it away, so analysts can audit the reasoning instead of trusting a
black box.

This is not a notebook demo. It is a fully reproducible pipeline with
seeded randomness, a validation suite that enforces data quality, leakage-
safe feature engineering, and a live web interface.

Source
------
Fully synthetic. Generated by a purpose-built Python script that models
realistic Zambian retail banking behaviour with seeded randomness, so the
entire dataset is reproducible from a single command.

Scale
-----
  5,000 clients
  100,000 transactions
  ~4.75 years of observation (January 2022 – September 2026)
  1.7% fraud rate (1,700 fraudulent transactions)

Schema
------
Three related tables:

  clients                 17 fields
    Demographics, income, employment, credit score, risk rating,
    home province, account metadata, preferred channel.

  transactions            10 fields
    Timestamp, type, amount, currency, beginning/ending balance,
    status, and the binary fraud label.

  transaction_metadata    11 fields
    Channel, payment method, merchant, device, IP address,
    geographic location, international flag.

Fraud injection
---------------
Fraud is not random. Five distinct patterns are simulated, each with its
own behavioural signature:

  Account takeover    new device, foreign login, overnight hour, large transfer
  Card compromise     new device, POS or online, mismatched payment method
  Velocity attack     many consecutive transactions within minutes
  Geographic anomaly  transaction far from the client's home province
  Merchant anomaly    high-risk merchant category the client has never used

Additional realism
------------------
  · Client transaction volumes follow a log-normal activity distribution
    weighted by income and customer segment.
  · Transaction amounts scale with each client's own income — a K15,000
    withdrawal is normal for a Premium client and anomalous for a Mass
    Market one.
  · Balance chains are continuous: every transaction's beginning balance
    equals the previous transaction's ending balance for that client.
  · Only fraudulent transactions may overdraw an account, mirroring how
    real fraud often exhausts funds before it is caught.
  · Merchant categories are tied to transaction type — fuel stations only
    appear on card purchases, not on bank transfers.

Validation
----------
A dedicated validation suite runs 11 checks after every generation and
fails loudly if any of them break: row counts, foreign-key integrity,
amount and balance consistency, class balance, timestamp spread, and
signal checks across hour-of-day, velocity, device novelty, geography,
and international activity.

1. Temporal leakage in feature engineering
-------------------------------------------
The single biggest source of over-optimistic fraud models is computing a
feature that secretly uses future information. Every rolling, cumulative,
and expanding feature in this pipeline is computed using only prior
transactions of the same client. Rolling windows are shifted by one row;
cumulative aggregates use .shift(1).expanding(); window-based counts
subtract the current row's own contribution. This discipline is what
keeps the test metrics honest.

2. Chronological splits, not random splits
-------------------------------------------
Standard cross-validation leaks the future into training. All splits here
are strictly chronological: the model trains on the earliest 70% of
transactions, validates on the next 15%, and is tested on the most recent
15%. Fraud rates differ slightly across splits, and the test set is
genuinely out-of-time.

3. Severe class imbalance
-------------------------
Fraud is 1.7% of transactions — roughly one fraud for every 60 legitimate
ones. Accuracy is meaningless here; a model that predicts "no fraud" for
everything scores 98.3%. The evaluation framework is built around PR-AUC,
recall at precision ≥ 0.5, and best-F1 threshold selection. XGBoost is
trained with scale_pos_weight to counteract the imbalance.

4. Balance features were too easy
---------------------------------
Allowing only fraudulent transactions to overdraw the account created an
artificially clean signal — the model learned "negative balance = fraud"
almost immediately. This is documented as a limitation rather than hidden,
because a real bank's balance is far messier and the honest story is more
useful than an inflated metric.

5. Simulating realistic fraud that is not trivially detectable
--------------------------------------------------------------
Naive fraud injection (label random transactions as fraudulent) produces a
dataset where the model has nothing to learn. Each fraud pattern here is
constructed to produce a plausible but distinctive footprint across
velocity, device, geography, and merchant dimensions. The validation suite
checks that every pattern is actually present and separable.

6. Making 82 features fast enough to be practical
-------------------------------------------------
Customer-level rolling windows on 100,000 rows are slow in naive pandas —
the first merchant-feature implementation took 90 seconds. Rewriting it
with hash-based groupby aggregations and replacing Python lambdas with
built-in Cython aggregations cut the runtime by an order of magnitude.

7. Explainability that non-technical stakeholders can read
---------------------------------------------------------
A model that says "0.97 probability of fraud" is not actionable. Every
prediction carries SHAP values rendered as a ranked contributor list —
"this feature increased the risk by X, this one decreased it by Y" — so an
analyst can see the reasoning, not just the verdict.

Step 1 — Generate the dataset
-----------------------------
A single script produces the full synthetic dataset and inserts it into
MySQL via the Django ORM in batched bulk-create operations. Customer
profiles are generated first, then transaction volumes are allocated using
a weighted multinomial distribution, then fraud counts are allocated, then
each transaction is generated with full state — timestamps spread across
the observation window, balance chains preserved, device and merchant
histories tracked per client.

Step 2 — Validate the dataset
-----------------------------
Immediately after generation, a validation suite runs 11 independent
checks against the database. It verifies not just that the row counts are
right, but that the signal the model will need actually exists: fraud
rates are elevated at night, velocity bursts are present, fraudulent
transactions use novel devices more often than legitimate ones, and
balances flow continuously through time.

Step 3 — Engineer features
--------------------------
Raw tables are loaded, joined, sorted by client and timestamp, and passed
through nine families of feature transformations:

  Temporal            8 features
  Balance             5
  Behavioural        10
  Sequence            8
  Velocity           11
  Location            6
  Device              5
  Merchant            5
  Interaction         5
  Plus raw categorical and numeric columns

The output is 82 model-ready features. The result is split chronologically
into train/validation/test and written to Parquet — much faster and more
memory-efficient than CSV at scale.

Step 4 — Train and compare models
---------------------------------
Two models are trained on identical features:

  Logistic Regression   PR-AUC 0.9841
  XGBoost               PR-AUC 0.9977

Both are evaluated on the validation set using PR-AUC, ROC-AUC, precision,
recall, F1, and recall at precision ≥ 0.5. The XGBoost model is selected,
its operational threshold is set by maximising F1 on validation, and the
full bundle (model, threshold, feature list) is pickled for inference.

Step 5 — Evaluate on test data
------------------------------
The evaluation script produces the artifacts that appear on the model
performance page: precision–recall curve, ROC curve, threshold analysis,
confusion matrix at the operational threshold, score distribution,
feature importance, per-segment recall, and four SHAP visualisations
(beeswarm, bar, waterfall for true positives, waterfall for a false
negative).

Step 6 — Score transactions live
--------------------------------
The trained model is wrapped in a reusable FraudPredictor class with no
Django dependencies. The Django app loads it once at startup via an
lru_cache and calls it per request. The form collects the fields a user
can realistically provide; the rest are derived. Every response includes
the probability, a risk band (LOW / MEDIUM / HIGH / CRITICAL), and the top
five SHAP contributors.

Step 7 — Interactive demo
-------------------------
The web interface provides a form-based scorer where you enter a
transaction and see the fraud probability, risk band, and reasoning, plus
a model-performance page with all evaluation charts.

This project demonstrates that fraud detection is not primarily a machine
learning problem — it is a data engineering and temporal discipline
problem.

The machine learning itself is straightforward once the features exist.
XGBoost on a clean feature set with balanced classes is a well-understood
tool. What separates a model that scores PR-AUC 0.99 in a notebook from
one that would actually catch fraud in production is:

  · Discipline about time. Every feature must only see the past.

  · Signal design in the data. Fraud has to have a footprint the model
    can learn. Randomly-labelled fraud produces random predictions.

  · Evaluation that matches the problem. Accuracy is a lie on imbalanced
    data. PR-AUC, recall at high precision, and per-segment recall tell
    you what a fraud analyst actually needs to know.

  · Explainability as a first-class output. A probability is a number.
    A SHAP contributor list is a decision an analyst can defend.

  · Honesty about limitations. The balance features in this synthetic
    dataset are an artifact of the generator, not a real-world signal.
    Documenting that is more valuable than pretending the number is
    genuine.

The final system is reproducible end to end from four commands, runs in
under two minutes on a laptop, and exposes its reasoning to whoever is
looking at the result. That combination — correctness, reproducibility,
transparency, and a live interface — is what separates a portfolio project
from a tutorial.