Skip to content

Repository files navigation

Fraud Detection System

A production-ready fraud detection system combining rule-based and ML-based approaches for real-time transaction evaluation.

Architecture Overview

Transaction → FraudDecisionEngine
                    ↓
            ┌───────┴───────┐
            ↓               ↓
      RuleService       MLService
      (Fast, Explainable)  (Pattern Detection)
            ↓               ↓
            └───────┬───────┘
                    ↓
              Final Decision
         (DECLINE/STEP_UP/APPROVE)

Features

  • Hybrid Detection: Combines deterministic rules with ML scoring
  • Fast Response: Rules evaluated first for quick decisions
  • Explainable: Returns matched rules as reasons for decisions
  • Configurable: Thresholds and rules can be updated without code changes
  • Production Ready: Docker support, health checks, structured logging
  • 35+ Features: Comprehensive transaction analysis

Quick Start

1. Setup Environment

# Create virtual environment
python -m venv .venv
.\.venv\Scripts\Activate.ps1

# Install dependencies
pip install -r requirements.txt

2. Generate Training Data

python training_data/sample_data_generator.py
# Output: training_data/rule_compatible_fraud_data.csv (1M rows)

3. Train the Model

python run_time/ml_engine/model_trainer.py
# Output: models/fraud_xgboost_model.joblib

4. Run Tests

pytest tests/ -v
# Expected: 33 passed

5. Start the API Server

uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

6. Test the API

# Health check
curl http://localhost:8000/health

# Evaluate a transaction
curl -X POST http://localhost:8000/api/v1/fraud/evaluate -H "Content-Type: application/json" -d "{\"transaction_id\": \"test_001\", \"amount\": 500, \"txn_count_5m\": 1}"

Docker Deployment

# Build the image
docker build -t fraud-detection-api:latest .

# Run with docker-compose
docker-compose up -d

# Check status
docker-compose ps

# View logs
docker-compose logs -f fraud-api

# Stop
docker-compose down

Project Structure

fraud-detection-system/
├── app/                    # FastAPI application
│   ├── main.py            # API entry point
│   ├── dependencies.py    # Dependency injection
│   ├── schemas/           # Pydantic models
│   │   ├── transaction.py # Input schema (35+ features)
│   │   └── decision.py    # Output schema
│   └── routers/           # API endpoints
│       └── fraud.py       # /api/v1/fraud/*
├── run_time/              # Core fraud detection
│   ├── decision_engine/   # Combined decision logic
│   ├── ml_engine/         # ML model and training
│   │   ├── ml_service.py  # Inference service
│   │   └── model_trainer.py # Training script
│   └── rule_engine/       # Rule evaluation
│       ├── rule_loader.py # JSON rule loader
│       └── rule_service.py # Rule evaluation
├── artifacts/             # Rule definitions
│   └── rule_engine_rules.json # 18 fraud detection rules
├── models/                # Trained ML models
│   ├── fraud_xgboost_model.joblib
│   └── model_metadata.json
├── training_data/         # Data generation
│   └── sample_data_generator.py
├── tests/                 # Unit and integration tests
├── config.py              # Configuration management
├── Dockerfile
├── docker-compose.yml
└── requirements.txt

API Endpoints

Method Endpoint Description
POST /api/v1/fraud/evaluate Evaluate single transaction
POST /api/v1/fraud/batch Batch evaluation (max 100)
GET /api/v1/fraud/rules List active rules
GET /api/v1/fraud/status Engine status
GET /health Health check
GET /ready Readiness probe
GET /docs Swagger UI documentation

Example Request/Response

Request:

{
  "transaction_id": "txn_12345",
  "amount": 150.00,
  "txn_count_5m": 1,
  "new_merchant_flag": false,
  "geo_distance_km": 5.0,
  "hour_of_day": 14,
  "otp_result": true
}

Response:

{
  "transaction_id": "txn_12345",
  "decision": "APPROVE",
  "fraud_score": 0.12,
  "reasons": [],
  "source": "RULE_ENGINE + ML",
  "matched_rules_count": 0,
  "processing_time_ms": 5.23
}

Decision Flow

  1. Transaction Received: API receives transaction with 35+ features
  2. Rule Engine First: 18 deterministic rules evaluated (fast, explainable)
    • If DECLINE: Return immediately (no ML needed)
    • If STEP_UP: Flag for additional authentication
  3. ML Scoring: XGBoost model predicts fraud probability
    • Score >= 0.85: DECLINE
    • Score >= 0.65: STEP_UP
    • Score < 0.65: APPROVE
  4. Decision Combination: Merge rule + ML decisions
  5. Response: Return decision with score and reasons

Configuration

Environment variables (.env file):

# Model paths
MODEL_PATH=models/fraud_xgboost_model.joblib
RULES_PATH=artifacts/rule_engine_rules.json

# ML thresholds
ML_DECLINE_THRESHOLD=0.85
ML_STEP_UP_THRESHOLD=0.65

# API settings
API_HOST=0.0.0.0
API_PORT=8000
DEBUG=false

Testing

# Run all tests
pytest tests/ -v

# Run specific test file
pytest tests/test_api.py -v

# Run with coverage
pytest tests/ -v --cov=run_time --cov=app

Git Workflow

Tags for version management:

  • v1-data-ingestion: Data generator ready
  • v2-feature-engineering: Config management
  • v3-model-training: Model trained
  • v4-model-serialization: Model validated
  • v5-fastapi-inference: API ready
  • v6-dockerized-deployment: Docker ready

Performance

  • Training: ~2 minutes for 1M rows
  • Inference: <10ms per transaction
  • Model AUC: 1.0 (synthetic data with clear fraud patterns)
  • API Throughput: ~200 requests/second

License

MIT License

d3e0170 (feat(model): Train and Deploy Models)

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages