CodeForFinance
PythonBeginner

Automate Your Savings with Python

Build Python scripts to track savings goals, parse bank statements, and generate spending reports automatically. Take control of your finances with code.

Savings Goal Tracker

A class that tracks multiple savings goals, calculates monthly targets, and persists data to JSON.

import json
from datetime import datetime
import pandas as pd

class SavingsAutomator:
    def __init__(self, filename="savings.json"):
        self.filename = filename
        self.goals = self._load()

    def _load(self):
        try:
            with open(self.filename, "r") as f:
                return json.load(f)
        except FileNotFoundError:
            return []

    def _save(self):
        with open(self.filename, "w") as f:
            json.dump(self.goals, f, indent=2)

    def add_goal(self, name, target, deadline):
        months_left = max(1, (pd.to_datetime(deadline) - datetime.now()).days // 30)
        monthly_needed = target / months_left

        self.goals.append({
            "name": name,
            "target": target,
            "deadline": deadline,
            "saved": 0,
            "monthly_needed": round(monthly_needed, 2)
        })
        self._save()
        print(f"Goal: {name}")
        print(f"  Target: £{target:,.0f} by {deadline}")
        print(f"  Monthly savings needed: £{monthly_needed:,.2f}")

    def add_saving(self, goal_name, amount):
        for goal in self.goals:
            if goal["name"] == goal_name:
                goal["saved"] += amount
                pct = (goal["saved"] / goal["target"]) * 100
                self._save()
                print(f"+ £{amount:.2f} to {goal_name} ({pct:.1f}% complete)")
                return
        print(f"Goal not found: {goal_name}")

Progress Reports

Generate visual progress reports with progress bars and summaries across all your goals.

    def report(self):
        print("\n" + "=" * 50)
        print("SAVINGS REPORT")
        print("=" * 50)

        for goal in self.goals:
            pct = (goal["saved"] / goal["target"]) * 100
            remaining = goal["target"] - goal["saved"]
            filled = int(pct // 5)
            bar = "█" * filled + "░" * (20 - filled)

            print(f"\n{goal['name']}:")
            print(f"  [{bar}] {pct:.1f}%")
            print(f"  Saved: £{goal['saved']:,.2f} / £{goal['target']:,.2f}")
            print(f"  Remaining: £{remaining:,.2f}")
            print(f"  Monthly target: £{goal['monthly_needed']:,.2f}")

        total_saved = sum(g["saved"] for g in self.goals)
        total_target = sum(g["target"] for g in self.goals)
        print(f"\nTotal saved across all goals: £{total_saved:,.2f}")
        print(f"Total target: £{total_target:,.2f}")

# Usage
tracker = SavingsAutomator()
tracker.add_goal("Emergency Fund", 5000, "2025-12-31")
tracker.add_goal("Holiday", 2000, "2025-08-01")
tracker.add_goal("House Deposit", 30000, "2027-06-01")

tracker.add_saving("Emergency Fund", 500)
tracker.add_saving("Emergency Fund", 500)
tracker.add_saving("Holiday", 300)
tracker.add_saving("House Deposit", 1000)

tracker.report()

Auto-Categorise Bank Statements

Parse bank statement CSVs and automatically categorise transactions to understand where your money goes.

# Auto-categorise bank statement spending
def analyse_spending(csv_path):
    """Parse a bank statement CSV and categorise transactions."""
    df = pd.read_csv(csv_path)

    categories = {
        "Groceries": ["tesco", "sainsbury", "asda", "aldi", "lidl"],
        "Eating Out": ["mcdonald", "nando", "deliveroo", "just eat"],
        "Transport": ["tfl", "uber", "shell", "bp", "trainline"],
        "Subscriptions": ["netflix", "spotify", "amazon prime", "gym"],
        "Utilities": ["water", "electric", "gas", "broadband"],
        "Housing": ["rent", "mortgage", "council tax"],
    }

    def categorise(desc):
        for cat, keywords in categories.items():
            if any(kw in desc.lower() for kw in keywords):
                return cat
        return "Other"

    df["Category"] = df["Description"].apply(categorise)

    # Spending summary
    expenses = df[df["Amount"] < 0].copy()
    expenses["Amount"] = expenses["Amount"].abs()

    summary = expenses.groupby("Category")["Amount"].agg(["sum", "count"])
    summary.columns = ["Total", "Transactions"]
    summary = summary.sort_values("Total", ascending=False)

    print("\nSPENDING ANALYSIS")
    print("-" * 45)
    for cat, row in summary.iterrows():
        print(f"  {cat:<20} £{row['Total']:>8,.2f}  ({int(row['Transactions'])} txns)")
    print(f"  {'TOTAL':<20} £{summary['Total'].sum():>8,.2f}")

    # Savings rate
    income = df[df["Amount"] > 0]["Amount"].sum()
    spending = summary["Total"].sum()
    savings_rate = ((income - spending) / income) * 100
    print(f"\nIncome: £{income:,.2f}")
    print(f"Spending: £{spending:,.2f}")
    print(f"Savings rate: {savings_rate:.1f}%")

    return summary

Developer Essentials

As an Amazon Associate we may earn from qualifying purchases.