Skip to content

Repository files navigation

PayGuard AI

PayGuard AI is a proof-of-concept framework for explainable corporate supplier-payment anomaly detection and financial decision support. It combines deterministic business controls with an unsupervised Isolation Forest detector, interpretable logistic regression, Bayesian uncertainty estimation, and financial simulation.

All supplier and payment records in this repository are synthetic. The project is designed to demonstrate methodology and software implementation; it does not claim real-world fraud-detection performance and should not be used to make production financial decisions without organisation-specific validation and governance.

Core framework

The project contains four connected analytical layers:

  1. Hybrid detection — transparent business rules are combined with an Isolation Forest anomaly percentile to prioritise suspicious payments.
  2. Interpretable statistical analysis — L2-penalised logistic regression estimates associations between transaction features and planted anomaly labels, with odds ratios and bootstrap intervals.
  3. Bayesian uncertainty analysis — Bayesian logistic regression estimates posterior distributions and transaction-level predictive uncertainty.
  4. Financial decision support — review-exposure bootstrapping and Monte Carlo working-capital simulation translate analytical outputs into illustrative financial scenarios.

Detection logic

The rule engine evaluates payment characteristics including:

  • exact and near-duplicate invoices;
  • payments exceeding invoice amounts;
  • invoices exceeding authorised purchase-order amounts;
  • recent supplier bank-account changes;
  • invoice/payment currency mismatches;
  • unusually rapid payments; and
  • weekend-payment activity as a contextual behavioural indicator.

The Isolation Forest operates on eight engineered features:

  • log payment amount;
  • paid-to-invoice ratio;
  • invoice-to-PO ratio;
  • days to pay;
  • payment-term deviation;
  • weekend-payment indicator;
  • recent bank-change indicator; and
  • currency-mismatch indicator.

The operational hybrid score is:

Risk Score = 0.72 × Rule Score + 0.28 × Isolation Forest Percentile

Transactions with a score of 45 or above are prioritised for review. The weights and threshold are prototype design choices and would require calibration to an organisation's risk tolerance, loss profile, and investigation capacity before deployment.

The hybrid score is a prioritisation score, not a probability of fraud.

Review exposure

Flagged payments may also receive a review-exposure value for investigation prioritisation:

  • Overpayment exposure measures the observable amount paid above the invoice.
  • Duplicate-candidate exposure attributes the full payment amount to the later candidate duplicate so the same potential duplicate is not counted twice.
  • Direct exposure uses the larger directly observable amount above.
  • Scenario exposure is an explicitly illustrative amount used only when an alerted payment has no directly measurable exposure.
  • Review exposure uses direct exposure where available and otherwise uses the scenario estimate.

Review exposure is not a calibrated expected fraud loss or accounting provision.

Synthetic dataset

The canonical dataset is generated by generate_sample_data.py using:

5,600 transactions
random seed = 42

The generator creates fictional suppliers across six procurement categories and injects seven controlled anomaly scenarios:

  • exact duplicates;
  • near duplicates;
  • overpayments;
  • invoices above purchase orders;
  • recent bank-account changes;
  • currency mismatches; and
  • rapid payments.

Weekend payment is not a planted ground-truth anomaly class; it is derived from generated payment dates and used as a contextual feature/rule.

Repository structure

PayGuard_AI/
├── analysis/
│   ├── additional_figures.py      Supplementary evaluation figures
│   ├── advanced_statistics.py     Held-out statistical and simulation analysis
│   ├── build_workbooks.py         Builds Excel evaluation workbooks
│   ├── export_for_xlsx.py         Exports analysis inputs for workbooks
│   ├── charts/                    Generated research figures
│   └── results.json               Machine-readable analysis summary
├── data/
│   └── synthetic_payments.csv     Canonical synthetic dataset
├── excel/
│   ├── PayGuard_Bayesian_Evaluation.xlsx
│   ├── PayGuard_MonteCarlo_Evaluation.xlsx
│   └── PayGuard_Regression_Evaluation.xlsx
├── payguard/
│   ├── __init__.py
│   ├── data_generator.py          Synthetic payment-data generator
│   └── detector.py                Feature engineering, rules, Isolation Forest, scoring
├── tests/
│   └── test_payguard.py           Automated tests
├── app.py                         Streamlit investigation dashboard
├── generate_sample_data.py        Canonical dataset-generation entry point
├── PROJECT_REPORT.md              Technical overview
├── requirements.txt
├── Dockerfile
└── README.md

Installation with Miniforge

The project was developed and run from Miniforge Prompt. Python 3.11 is recommended.

From Miniforge Prompt:

conda create -n payguard python=3.11 -y
conda activate payguard
pip install -r requirements.txt

If you already have a working PayGuard environment, activate that environment instead of creating a new one.

Reproduce the project

From the repository root:

1. Generate the canonical dataset

python generate_sample_data.py

2. Run the automated tests

python -m pytest -q

3. Run the held-out statistical analysis

python analysis/advanced_statistics.py

This performs a stratified 70/30 training/test split, fits the Isolation Forest and supervised models using training data, and evaluates predictive performance on held-out observations where appropriate.

4. Generate supplementary figures

python analysis/additional_figures.py

5. Regenerate Excel evaluation workbooks

python analysis/export_for_xlsx.py
python analysis/build_workbooks.py

6. Launch the Streamlit dashboard

streamlit run app.py

The dashboard is an operational demonstration. The formal research evaluation is produced by the held-out analysis scripts rather than by treating the dashboard's in-sample demonstration metrics as production estimates.

Statistical analysis

analysis/advanced_statistics.py includes:

  • L2-penalised logistic regression;
  • 1,000-replication bootstrap intervals for logistic coefficients;
  • odds-ratio analysis;
  • McFadden pseudo-R² for logistic model fit;
  • ROC-AUC and average precision on held-out data;
  • Bayesian logistic regression using PyMC;
  • posterior coefficient distributions and credible intervals;
  • NUTS convergence diagnostics;
  • held-out posterior predictive probabilities;
  • Brier score for probabilistic predictions;
  • 20,000-replication bootstrap simulation of aggregate review exposure; and
  • 20,000-draw Monte Carlo working-capital scenarios for +10, +20, and +30 days of DPO.

The financial simulation parameters are illustrative assumptions. They should be replaced with authorised, organisation-specific treasury inputs before any operational use.

Key outputs

The analysis scripts produce research figures including:

  • ROC comparison;
  • logistic-regression odds ratios;
  • Bayesian posterior coefficient intervals;
  • posterior predictive probabilities;
  • bootstrap aggregate review-exposure distribution;
  • working-capital Monte Carlo distributions;
  • system architecture;
  • dataset composition;
  • confusion matrix;
  • precision-recall analysis;
  • anomaly-type detection rates;
  • threshold sensitivity; and
  • probability calibration.

Excel workbooks provide additional interactive views of the regression, Bayesian, and financial-simulation analyses.

Reproducibility and limitations

Random seeds are fixed where applicable. The synthetic design allows controlled evaluation because the planted anomaly labels are known; however, those labels are generated by the same experimental system and are cleaner than genuine fraud outcomes.

Important limitations include:

  • no use of authorised real organisational payment data;
  • synthetic anomaly scenarios may not capture the complexity of real fraud;
  • prototype rule weights and alert thresholds are not organisation-calibrated;
  • scenario exposure is illustrative rather than a calibrated loss estimate;
  • working-capital simulation parameters are placeholders;
  • the framework does not establish that a flagged transaction is fraudulent; and
  • production deployment would require temporal validation, security controls, investigator feedback, monitoring, and governance.

Responsible use

PayGuard AI is intended as an investigation-prioritisation and research prototype. Alerts are leads for human review, not accusations of misconduct. Any production use would require authorised data, privacy and security controls, auditable governance, and human oversight.

About

Explainable hybrid framework for corporate payment anomaly detection, uncertainty estimation, and financial decision support.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages