A sophisticated Python web application that minimizes debt settlements between multiple parties using graph-based algorithms and data structures.
- Add Transactions: Record who owes money to whom
- View Balances: See net balances for all participants
- Optimize Settlements: Calculate minimum number of payments needed
- Graph Visualization: Interactive directed weighted graph showing debt relationships
- Algorithm Animation: Step-by-step visualization of the greedy matching algorithm
- Set Theory Display: Visual representation of creditor and debtor set partitioning
- Mathematical Process: Detailed explanation of discrete mathematics concepts used
- Responsive UI: Works on desktop, tablet, and mobile devices
- Real-time Updates: Instant calculation and visualization
- Smart Algorithm: Uses heap-based greedy algorithm for O(n log n) complexity
cashflow-optimizer/
โ
โโโ app.py # Main Flask application with algorithms
โโโ requirements.txt # Python dependencies
โโโ README.md # This file
โ
โโโ templates/
โ โโโ index.html # Main HTML template
โ
โโโ static/
โโโ style.css # Responsive CSS styles
โโโ script.js # Frontend JavaScript logic
- Python 3.8 or higher
- pip (Python package manager)
-
Create Project Directory
mkdir cashflow-optimizer cd cashflow-optimizer -
Create Folder Structure
# On Windows mkdir templates static # On Linux/Mac mkdir -p templates static
-
Create All Required Files
Create the following files with their respective content:
app.py- Main application filerequirements.txt- Dependenciestemplates/index.html- HTML templatestatic/style.css- CSS stylesstatic/script.js- JavaScript code
-
Set Up Virtual Environment (Recommended)
# Create virtual environment python -m venv venv # Activate it # On Windows: venv\Scripts\activate # On Linux/Mac: source venv/bin/activate
-
Install Dependencies
pip install -r requirements.txt
-
Run the Application
python app.py
-
Access the Application Open your web browser and navigate to:
http://localhost:5000
- Enter the name of the person who owes money (Debtor)
- Enter the name of the person who should receive money (Creditor)
- Enter the amount
- Click "Add Transaction"
- Watch the Transaction Graph update in real-time
Example:
- Alice owes Bob $50
- Bob owes Charlie $30
- Charlie owes Alice $20
Transaction Graph (Directed Weighted Graph)
- Each person is a vertex (circle)
- Each debt is a directed edge (arrow)
- Edge weights represent the amount owed
- Green nodes = net creditors
- Red nodes = net debtors
- Blue nodes = balanced
Set Theory Visualization
- Creditors Set (C): People who should receive money (balance > 0)
- Debtors Set (D): People who owe money (balance < 0)
- Shows the partition: C โฉ D = โ and C โช D = V
The "Net Balances" section shows:
- Green values: Amount to receive (positive balance)
- Red values: Amount to pay (negative balance)
- Formula: balance(v) = ฮฃ(incoming) - ฮฃ(outgoing)
- Add all your transactions
- Click "Calculate Optimal Settlements"
- Watch the Algorithm Visualization animate each step
- View the minimized list of payments needed
The visualization shows:
- Heap initialization
- Greedy matching process
- Each settlement step with mathematical formulas
- Final optimized payment list
1. Graph Theory
- Models debt relationships as a directed weighted graph G = (V, E)
- V = set of all people (vertices)
- E = set of debt edges where e = (u, v, w) means u owes v amount w
- Reduces multi-edge graph to simple graph through edge weight summation
2. Set Theory
- Partitions vertex set V into two disjoint sets:
- C (Creditors): C = {v โ V | balance(v) > 0}
- D (Debtors): D = {v โ V | balance(v) < 0}
- Properties: C โฉ D = โ , C โช D = V
- Conservation law: ฮฃ(balance โ C) = -ฮฃ(balance โ D)
3. Optimization Problem
- Goal: Minimize |E'| where E' is the set of settlement edges
- Constraint: Must preserve all net balances
- Approach: Greedy algorithm with priority queues
-
DefaultDict (Hash Map)
- Stores net balances for each person
- O(1) lookup and update time
-
Min/Max Heaps
- Efficiently finds largest debtor and creditor
- O(log n) insertion and extraction
-
List (Dynamic Array)
- Stores all transactions
- Maintains history of settlements
-
Calculate Net Balances
- For each transaction, update debtor (subtract) and creditor (add)
- Time Complexity: O(n)
-
Create Heaps
- Separate people into debtors (owe money) and creditors (receive money)
- Time Complexity: O(n log n)
-
Greedy Settlement
- Match largest debtor with largest creditor
- Settle maximum possible amount
- Re-add remaining balances to heaps
- Time Complexity: O(n log n)
Overall Time Complexity: O(n log n) Space Complexity: O(n)
- Backend: Flask (Python)
- Frontend: Vanilla JavaScript (no frameworks)
- Styling: Custom CSS with responsive design
- Data Structures:
- Heaps (priority queues)
- Hash maps (dictionaries)
- Lists
The application is fully responsive and works on:
- Desktop computers (1200px+)
- Tablets (768px - 1199px)
- Mobile phones (< 768px)
Edit app.py line:
app.run(debug=True, host='0.0.0.0', port=5000) # Change port hereapp.run(debug=False) # Set to False for production-
Port Already in Use
Error: Address already in useSolution: Change the port in
app.pyor kill the process using port 5000 -
Module Not Found
ModuleNotFoundError: No module named 'flask'Solution: Install requirements:
pip install -r requirements.txt -
Template Not Found
TemplateNotFound: index.htmlSolution: Ensure
templates/folder exists withindex.htmlinside -
Static Files Not Loading Solution: Ensure
static/folder containsstyle.cssandscript.js
Alice paid $100 for hotel (Bob and Charlie split)
Bob paid $60 for food (Alice and Charlie split)
Charlie paid $30 for gas (Alice and Bob split)
Result: 2-3 optimized payments instead of 6 transactions
John owes Sarah $200 (rent)
Sarah owes Mike $150 (utilities)
Mike owes John $100 (groceries)
Result: 1-2 optimized payments instead of 3 transactions
- This is a demo application without authentication
- Data is stored in memory (resets on restart)
- For production use, add:
- User authentication
- Database persistence
- Input sanitization
- HTTPS/SSL
- Rate limiting
This project is open source and available for educational purposes.
- Persistence: Add SQLite or PostgreSQL database
- User Accounts: Implement authentication system
- Groups: Allow multiple debt groups
- History: Track settlement history
- Export: Generate PDF reports
- Advanced Visualization: Add D3.js for more interactive graphs
- Matrix Representation: Show adjacency matrix view
- Path Analysis: Display shortest debt chains
- app.py: Contains
CashFlowOptimizerclass and Flask routes - index.html: Single-page application template
- style.css: Modern, responsive styling
- script.js:
CashFlowUIclass handles all frontend logic
Feel free to fork, modify, and improve this project!
For issues or questions, refer to:
- Flask documentation: https://flask.palletsprojects.com/
- Python heapq: https://docs.python.org/3/library/heapq.html
Happy Optimizing! ๐ฐโจ