Data Automation & Cleaning
Intermediate
Benford's Law Forensic Accounting & Invoice Fraud Detector in Python
Detect fabricated invoices and accounting manipulation in ledger CSVs by testing leading-digit distributions against Benford's Law and Chi-Square in Python.
#pandas#numpy#scipy
Problem Statement
When humans fabricate expense claims or fake ledger entries, they overuse digits like 5, 6, and 7. Benford's Law proves that in natural financial datasets, the leading digit '1' appears 30.1% of the time.
Formula / Core Logic
P(d) = log10(1 + 1/d) for d in {1..9}
Compares observed first-digit frequencies against Benford expectations via Chi-Square goodness-of-fit.
Installation
pip install pandas numpy scipy
benfords-law-forensic-accounting-fraud-detector-python.py
import numpy as np
import pandas as pd
from scipy.stats import chisquare
def benford_forensic_audit(amount_series: pd.Series):
clean = amount_series.dropna().abs()
clean = clean[clean >= 10]
first_digits = clean.astype(str).str.lstrip('0.').str[0].astype(int)
first_digits = first_digits[first_digits.between(1, 9)]
obs_counts = first_digits.value_counts().reindex(range(1, 10), fill_value=0)
obs_pct = obs_counts / len(first_digits)
benford_pct = pd.Series([np.log10(1 + 1/d) for d in range(1, 10)], index=range(1, 10))
stat, p_val = chisquare(obs_counts, f_exp=benford_pct * len(first_digits))
return {'Chi2_Stat': round(stat, 2), 'P_Value': round(p_val, 4), 'Suspicion_Flag': p_val < 0.05}
Get the Complete 100+ Python Quant & Automation Bundle
Instant lifetime access to all production-ready scripts, valuation models, and trading bots ($19).
Buy Full Bundle on Gumroad ($19) →Frequently Asked Questions
Q: What does `Suspicion_Flag: True` indicate?
A p-value below 0.05 indicates the ledger's leading digits deviate significantly from natural financial distributions, warranting manual voucher inspection.