pythonadvanced60 minutes

Advanced Expense Tracker CLI with Data Persistence and Reporting

Build a command-line Python application that allows users to add, update, delete, and categorize expenses. Implement data persistence using JSON files and generate summary reports on spending by category and date range.

Challenge prompt

Create an advanced command-line expense tracker application with the following features: 1. Add expenses with fields: description, amount, category (e.g., Food, Transport, Utilities), and date. 2. Update and delete existing expense entries. 3. Persist all data in a JSON file to retain data between runs. 4. List all expenses with optional filters by category and date range. 5. Generate summary reports showing total amount spent per category and total spending within a user-specified date range. 6. Implement error handling for invalid inputs and file operations. Your solution should be modular and designed with extensibility in mind for future features.

Guidance

  • Define clear data models for expense entries and structure the JSON file accordingly.
  • Create separate functions for CRUD operations and reporting logic.
  • Use Python's datetime module for handling dates and filtering by ranges.
  • Ensure that the program reads the existing data on start and writes updates back safely after each change.

Hints

  • Structure your JSON file as a list of expense dictionaries, each containing keys like 'description', 'amount', 'category', and 'date'.
  • Use try-except blocks to handle file read/write errors and validate user inputs.
  • For date filtering, parse user input into datetime objects and compare expense dates accordingly.

Starter code

import json
from datetime import datetime

DATA_FILE = 'expenses.json'

# Load expenses from file
try:
    with open(DATA_FILE, 'r') as f:
        expenses = json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
    expenses = []

# Define functions for add_expense, update_expense, delete_expense, list_expenses, generate_report

def main():
    print('Welcome to Advanced Expense Tracker')
    # TODO: Implement CLI interaction

if __name__ == '__main__':
    main()

Expected output

A CLI where users can add, update, delete, and list expenses, and generate spending reports. For example, when listing expenses filtered by category 'Food' and date range '2023-01-01' to '2023-01-31', the output shows expenses matching those criteria and a summary total. Sample summary report output: Total spend by category: - Food: $150.00 - Transport: $70.00 - Utilities: $90.00 Total spend from 2023-01-01 to 2023-01-31: $310.00

Core concepts

file handlingdata persistencedatetime manipulationcommand line interfacedata filtering and aggregation

Challenge a Friend

Send this duel to someone else and see if they can solve it.