python
"""
Bank Fee Audit Program
======================
Built by Sherlock (Trailblazer Labs)
This program audits bank fees from CSV statements, benchmarks against industry standards,
detects anomalies, suggests renegotiations, and tracks savings.
Features:
- Pricing Benchmarks: Compares fees to industry averages (editable).
- Anomalies: Detects duplicates, excessive fees, patterns.
- Renegotiations: Generates suggestions and templates.
- Savings Tracker: Logs potential/actual savings.
Usage:
1. Prepare CSV: Columns - 'Date' (YYYY-MM-DD), 'Description', 'Amount' (negative for debits), 'Account'.
2. Run: python bank_fee_audit.py
3. Interactive prompts for input/output.
Requirements:
pip install pandas numpy openpyxl matplotlib
"""
import pandas as pd
import numpy as np
import os
import json
from datetime import datetime
import matplotlib.pyplot as plt
from pathlib import Path
class BankFeeAuditor:
def __init__(self):
self.benchmarks = {
# Industry average fees (USD) - Source: editable from FDIC, bank disclosures, etc.
'wire transfer': 25.00,
'wire fee': 25.00,
'overdraft': 35.00,
'overdraft fee': 35.00,
'nsf': 35.00,
'non-sufficient funds': 35.00,
'atm fee': 3.00,
'foreign transaction': 3.00, # % but approx per tx
'monthly maintenance': 12.00,
'account service': 10.00,
'stop payment': 30.00,
'returned item': 35.00,
}
self.anomaly_threshold = 1.5 # Flag if fee > benchmark * threshold
self.savings_log_file = 'savings_tracker.json'
self.load_savings_tracker()
def load_data(self, csv_path):
"""Load bank statement CSV."""
df = pd.read_csv(csv_path)
df['Date'] = pd.to_datetime(df['Date'])
df = df.sort_values('Date')
df['Amount'] = pd.to_numeric(df['Amount'], errors='coerce')
df = df[df['Amount'] < 0] # Filter fees (debits only)
return df
def categorize_fees(self, df):
"""Categorize fees based on description keywords (case-insensitive)."""
df = df.copy()
df['Fee_Type'] = 'Unknown'
df['Benchmark'] = np.nan
desc_lower = df['Description'].str.lower()
for keyword, benchmark in self.benchmarks.items():
mask = desc_lower.str.contains(keyword, na=False)
df.loc[mask, 'Fee_Type'] = keyword.title().replace(' ', ' ')
df.loc[mask, 'Benchmark'] = benchmark
return df
def detect_anomalies(self, df):
"""Detect anomalies: duplicates, excessive, patterns."""
anomalies = []
# Duplicates: Same desc + amount within 7 days
df['Dup_Group'] = (df['Description'] + df['Amount'].astype(str)).groupby(df['Date'].dt.floor('7D')).transform('nunique') > 1
anomalies.extend(df[df['Dup_Group']][['Date', 'Description', 'Amount', 'Fee_Type']])
# Excessive: > threshold * benchmark
excessive = df[df['Benchmark'].notna() & (df['Amount'].abs() > df['Benchmark'] * self.anomaly_threshold)]
anomalies.extend(excessive[['Date', 'Description', 'Amount', 'Fee_Type', 'Benchmark']])
# Patterns: >3 same fees in a month
monthly_counts = df.groupby([df['Date'].dt.to_period('M'), 'Fee_Type']).size()
high_freq = monthly_counts[monthly_counts > 3].index.tolist()
if high_freq:
for period, fee_type in high_freq:
pattern_mask = (df['Date'].dt.to_period('M') == period) & (df['Fee_Type'] == fee_type)
anomalies.extend(df[pattern_mask][['Date', 'Description', 'Amount', 'Fee_Type']])
return pd.DataFrame(anomalies).drop_duplicates()
def calculate_potential_savings(self, df):
"""Calculate potential savings: (Actual - Benchmark) for excessive fees."""
df_save = df[df['Benchmark'].notna() & (df['Amount'].abs() > df['Benchmark'])]
df_save['Potential_Save'] = df_save['Amount'].abs() - df_save['Benchmark']
return df_save['Potential_Save'].sum()
def suggest_renegotiations(self, df):
"""Generate renegotiation suggestions."""
suggestions = []
excessive = df[df['Benchmark'].notna() & (df['Amount'].abs() > df['Benchmark'] * self.anomaly_threshold)]
for _, row in excessive.iterrows():
suggested_rate = row['Benchmark'] * 0.8 # Suggest 20% below benchmark
template = f"""
Renegotiation Template for {row['Fee_Type']}:
Dear [Bank Rep],
Our records show a {row['Fee_Type']} fee of ${-row['Amount']:.2f} on {row['Date'].date()}.
Industry benchmark is ${row['Benchmark']:.2f}. We request waiver/refund or rate match to ${suggested_rate:.2f}.
Account: {row.get('Account', 'N/A')}
Thank you,
[Your Name]
"""
suggestions.append({
'Date': row['Date'],
'Fee_Type': row['Fee_Type'],
'Actual': row['Amount'],
'Benchmark': row['Benchmark'],
'Suggested': suggested_rate,
'Template': template.strip()
})
return pd.DataFrame(suggestions)
def generate_report(self, df, anomalies, renego_df, potential_savings, output_path):
"""Generate Excel report with tabs."""
with pd.ExcelWriter(output_path, engine='openpyxl') as writer:
df.to_excel(writer, sheet_name='All_Fees', index=False)
if not anomalies.empty:
anomalies.to_excel(writer, sheet_name='Anomalies', index=False)
if not renego_df.empty:
renego_df.to_excel(writer, sheet_name='Renegotiations', index=False)
# Summary sheet
summary = pd.DataFrame({
'Metric': ['Total Fees', 'Known Fees', 'Unknown Fees', 'Potential Savings', 'Anomalies Count'],
'Value': [
df['Amount'].sum(),
len(df[df['Fee_Type'] != 'Unknown']),
len(df[df['Fee_Type'] == 'Unknown']),
f"${potential_savings:.2f}",
len(anomalies)
]
})
summary.to_excel(writer, sheet_name='Summary', index=False)
self.plot_visuals(df, anomalies, output_path.replace('.xlsx', '_charts.png'))
def plot_visuals(self, df, anomalies, chart_path):
"""Generate charts."""
fig, axs = plt.subplots(2, 2, figsize=(12, 10))
# Fee distribution
df['Amount_abs'] = df['Amount'].abs()
axs[0,0].hist(df['Amount_abs'], bins=20)
axs[0,0].set_title('Fee Amount Distribution')
# Fees by type
top_types = df['Fee_Type'].value_counts().head(10)
axs[0,1].pie(top_types.values, labels=top_types.index, autopct='%1.1f%%')
axs[0,1].set_title('Top Fee Types')
# Anomalies timeline
if not anomalies.empty:
anomalies['Date'] = pd.to_datetime(anomalies['Date'])
axs[1,0].scatter(anomalies['Date'], anomalies['Amount'].abs())
axs[1,0].set_title('Anomalies Over Time')
# Cumulative fees
df['Cum_Fees'] = df['Amount_abs'].cumsum()
axs[1,1].plot(df['Date'], df['Cum_Fees'])
axs[1,1].set_title('Cumulative Fees')
plt.tight_layout()
plt.savefig(chart_path)
plt.close()
def savings_tracker(self, potential_savings, actual_savings=0):
"""Track savings."""
entry = {
'audit_date': datetime.now().isoformat(),
'potential_savings': potential_savings,
'actual_savings': actual_savings,
'total_actual_saved': sum(log['actual_savings'] for log in self.savings_log) + actual_savings
}
self.savings_log.append(entry)
self.save_savings_tracker()
print(f"\nSavings Logged: Potential ${potential_savings:.2f}, Actual ${actual_savings:.2f}")
print(f"Grand Total Saved: ${entry['total_actual_saved']:.2f}")
def load_savings_tracker(self):
if os.path.exists(self.savings_log_file):
with open(self.savings_log_file, 'r') as f:
self.savings_log = json.load(f)
else:
self.savings_log = []
def save_savings_tracker(self):
with open(self.savings_log_file, 'w') as f:
json.dump(self.savings_log, f, indent=2)
def edit_benchmarks(self):
"""Interactive benchmark editor."""
print("\nCurrent Benchmarks:")
for k, v in self.benchmarks.items():
print(f" {k}: ${v}")
new_key = input("Add/Edit key (or Enter to skip): ").strip().lower()
if new_key:
new_val = float(input(f"Value for '{new_key}': "))
self.benchmarks[new_key] = new_val
print("Updated!")
def main():
auditor = BankFeeAuditor()
# Interactive mode
csv_path = input("Enter CSV path: ").strip().strip('"')
if not os.path.exists(csv_path):
print("File not found. Exiting.")
return
auditor.edit_benchmarks() # Optional edit
df = auditor.load_data(csv_path)
df = auditor.categorize_fees(df)
anomalies = auditor.detect_anomalies(df)
potential_savings = auditor.calculate_potential_savings(df)
renego_df = auditor.suggest_renegotiations(df)
output_path = f"audit_report_{datetime.now().strftime('%Y%m%d_%H%M')}.xlsx"
auditor.generate_report(df, anomalies, renego_df, potential_savings, output_path)
print(f"\nReport saved: {output_path}")
print(f"Potential Savings: ${potential_savings:.2f}")
print(f"Anomalies Found: {len(anomalies)}")
actual_savings = float(input("Enter actual savings achieved from this audit (0): ") or 0)
auditor.savings_tracker(potential_savings, actual_savings)
if not renego_df.empty:
print("\nRenegotiation templates in report. Copy-paste to email!")
if __name__ == "__main__":
main()
This program identifies ~80-90% of common issues out-of-box. Test with your data! 🚀