Skip to main content

fraud-shield

PyPI MIT License GitHub Python scikit-learn

Train, save, and run fraud detection on transaction data. 94% balanced accuracy on the Kaggle dataset. One class. Clean API.

Built from a production Random Forest classifier for credit card fraud detection on imbalanced datasets. Handles the hard parts — class imbalance, balanced accuracy, probability calibration — so you don't have to.

fraud-shield demo

When to use this

Use fraud-shield when:

  • You need a fraud detection classifier you can train and deploy in under 10 lines of Python
  • Your dataset is heavily imbalanced (fraud cases are < 1% of transactions — raw accuracy is meaningless here)
  • You want probability scores and confidence levels per transaction, not just binary labels
  • You need save/load support so you train once and deploy the pickled model

Not the right fit if you need real-time streaming fraud detection, rule-based engines, or graph-based fraud networks. fraud-shield is a supervised batch classifier built on Random Forest — best suited for tabular transaction data.


Why not sklearn directly?

You can absolutely use sklearn.ensemble.RandomForestClassifier directly. fraud-shield wraps it with the patterns that fraud data specifically requires:

  • Balanced accuracy by default — raw accuracy on fraud data is meaningless (a model that predicts every transaction as legitimate gets ~99.8% accuracy while catching zero fraud)
  • SMOTE-style class weighting — handles the imbalance automatically
  • Confidence tiers — high / medium / low based on probability thresholds, not just a 0/1 label
  • One-liner train/save/load — no boilerplate

Install

pip install fraud-shield

Or from source:

git clone https://github.com/iamadhitya1/fraud-shield
pip install -e fraud-shield/

Quick Start

from fraudshield import FraudDetector

# Train
detector = FraudDetector()
detector.train("transactions.csv", target_col="Class")
detector.save("fraud_model.pkl")

# Predict single transaction
result = detector.predict({
    "V1": -1.36, "V2": -0.07, "V3": 2.54, "Amount": 149.62
    # ... all feature columns
})

print(result.label)             # "FRAUD" or "LEGITIMATE"
print(result.fraud_probability) # 0.9423
print(result.confidence)        # "high"

Train

detector = FraudDetector(
    n_estimators=100,              # number of trees
    random_state=42,               # reproducibility
    high_confidence_threshold=0.80,
    low_confidence_threshold=0.40,
)

metrics = detector.train("creditcard.csv", target_col="Class", verbose=True)
# [fraud-shield] Training on 199364 samples...
# [fraud-shield] Training complete.
#   Balanced Accuracy : 0.9412
#   F1 Score (macro)  : 0.9318
#   ROC-AUC           : 0.9876

Compatible with: Kaggle Credit Card Fraud Detection dataset and any binary classification dataset with 0/1 labels.


Predict

Single transaction

result = detector.predict(transaction_dict)

result.is_fraud           # True / False
result.fraud_probability  # 0.0 – 1.0
result.confidence         # "high" / "medium" / "low"
result.label              # "FRAUD" / "LEGITIMATE"
result.to_dict()          # { is_fraud, fraud_probability, confidence, label }

Batch prediction

import pandas as pd

df = pd.read_csv("new_transactions.csv")
results_df = detector.predict_batch(df)

# Adds columns: fraud_probability, is_fraud, confidence, label
print(results_df[["Amount", "fraud_probability", "label"]].head())

Evaluate

metrics = detector.evaluate("test_data.csv", target_col="Class")

# Returns dict with:
# balanced_accuracy, precision_macro, recall_macro,
# f1_macro, roc_auc, confusion_matrix, classification_report

Feature Importances

top = detector.feature_importances(top_n=10)
print(top)
# V14    0.1821
# V17    0.1342
# V12    0.1089
# ...

Save & Load

# Save
detector.save("fraud_model.pkl")

# Load in another script
detector = FraudDetector.load("fraud_model.pkl")
result = detector.predict(transaction)

Why balanced accuracy?

Raw accuracy is misleading on fraud data — a model that predicts every transaction as legitimate achieves ~99.8% accuracy while catching zero fraud. fraud-shield uses balanced accuracy by default, which averages recall across both classes and penalizes models that ignore the minority class.


Dataset

The included example targets the Kaggle Credit Card Fraud Detection dataset:

  • 284,807 transactions
  • 492 fraud cases (0.17%)
  • Features: V1–V28 (PCA-anonymized), Amount, Time

Author

M. Adhitya — Founder, Rewrite Labs

License

MIT © 2025 M. Adhitya

Built at Rewrite Labs

Metadata

Release files for fraud-shield 1.0.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fraud-shield 1.0.2
File Size Uploaded Provenance Actions
fraud_shield-1.0.2.tar.gz 8.0 kB Without provenance Details for fraud_shield-1.0.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fraud-shield 1.0.2
File Interpreter ABI Platform Actions
fraud_shield-1.0.2-py3-none-any.whl Python 3 none any Details for fraud_shield-1.0.2-py3-none-any.whl

Total release size: 16.2 kB

Release files / fraud_shield-1.0.2.tar.gz

Download URL fraud_shield-1.0.2.tar.gz
Size 8.0 kB
Tags Source
SHA-256 checksum
How to use checksums
e61a8ebe9fa040308b5f12e05dc176fe854c49ea1e8092a6a82b5ebb64210649
BLAKE2b-256 checksum
How to use checksums
84050b25932d22c5fc474757f49703558f4d3b51ffbd815014d2d570f62db640
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.5

Release files / fraud_shield-1.0.2-py3-none-any.whl

Download URL fraud_shield-1.0.2-py3-none-any.whl
Size 8.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9cc46eec1bcf9b7367669c9422ecbc2ea12b9dc62e43df3660117728002d3d73
BLAKE2b-256 checksum
How to use checksums
cb96003522ac73e78903eafc2f49c193fdd59664b1ae110c9f95a98d3a9c7e0d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.5

Security for fraud-shield 1.0.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page