Skip to content

anshul23102/cashclock

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

53 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

NatWest Hackathon License: Apache 2.0 Python React FastAPI DCO Compliant


🙋‍♂️ Overview

CashClock is a full-stack web application that gives Indian small and medium enterprises (SMEs) real-time visibility into their cash position — and early warning of when they might run out of money. It uses Holt-Winters statistical forecasting and Claude AI to predict cash flow 30 days ahead, detect anomalies in transactions, and surface pre-approved loan offers to businesses at risk of a cash crisis.

The platform serves two types of users: business owners, who see a personalised dashboard of their cash health, forecast, anomalies, and loan options; and bank managers, who see a portfolio-wide view of all SME clients with risk classification, lending pipeline, and approval tools. The AI component is optional — the app falls back to rule-based summaries if no API key is configured, so it runs fully offline.

Hackathon: NatWest Group — Code for Purpose India Hackathon
Problem it solves: Most Indian SMEs lack the financial tooling to anticipate cash shortfalls. CashClock gives them the same forecasting capability that large enterprises pay enterprise software for — at zero cost.


✅ Features

All features listed below are implemented and functional in the current codebase.

📊 Business Owner Dashboard

  • 30-day cash flow forecast — three confidence paths (likely / optimistic / pessimistic) using Holt-Winters Exponential Smoothing
  • No-Cash Zone detection — automatically identifies future dates when projected balance drops below ₹15,000
  • Balance tracker — week-over-week trend with percentage change
  • Forecast minimum — shows the lowest projected balance and the exact date it occurs
  • Daily cash calendar — colour-coded calendar (green / yellow / red) showing each day's cash health
  • Anomaly feed — unusual transactions flagged with severity (warning / high / critical), probable cause, and a suggested action
  • What-if scenario builder — model a revenue change (±50%) or a one-off cash injection, with live chart update showing impact vs baseline
  • AI Ask Box (UI present — not yet functional; planned for a future release)
  • PDF report download — multi-page formal business report including forecast chart, anomaly summary, and health score
  • In-app loan application — business owners can apply for a pre-approved loan directly from the dashboard

🏦 Bank Manager Dashboard

  • Portfolio overview — total clients, at-risk count, pre-approved count, and accepted-offer rate as KPI cards
  • Risk distribution panel — healthy / watch / urgent / declining breakdown with counts and colour coding
  • Industry distribution pie chart — breakdown of portfolio across SME sectors
  • Health score histogram — distribution of runway scores (0–100) across all businesses
  • Loan pipeline funnel — tracks offer sent → applied → approved → accepted
  • Forecasted dip timeline — which businesses will hit a cash crisis and when
  • Business list with search and filter — search by name, filter by industry and risk level
  • Bulk loan offer dispatch — send pre-approved offers to all at-risk businesses with one click
  • Per-business detail view — manager can drill into any business, see its full forecast, and manually approve a loan

🤖 AI & Analytics Engine

  • Holt-Winters ETS forecasting — triple exponential smoothing with weekly aggregation and day-of-week redistribution
  • Rolling z-score anomaly detection — severity classification relative to each business's own baseline, not a fixed threshold
  • Runway score (0–100) — composite score combining balance coverage, trend direction, volatility, and dip severity
  • Dynamic per-business thresholds — calibrated from each business's own 365-day transaction history
  • Claude AI integration — plain-English summaries via claude-haiku-4-5 (free-text Q&A not yet functional)
  • Loan risk scoring — three tiers (low / medium / high) that determine interest rate and loan size

🛠️ Tech Stack

Backend

My Skills

Category Technology
Language Python 3.10+
Web Framework FastAPI + Uvicorn
Forecasting statsmodels (Holt-Winters Exponential Smoothing)
Data Processing pandas, numpy
AI / LLM Anthropic Claude API (claude-haiku-4-5) — optional
PDF Generation ReportLab
Database SQLite (Python built-in sqlite3)
Config python-dotenv

Frontend

My Skills

Category Technology
Language JavaScript (ES2022)
Framework React 18
Build Tool Vite 5
Styling Tailwind CSS 3
Charts Recharts 2
HTTP Client Axios
Icons Lucide React

Infrastructure

My Skills

Category Detail
Database SQLite file — no external database required
AI API Anthropic Claude API (optional — rule-based fallback included)
Environment Runs fully on localhost — no cloud account needed

🗂️ Folder Structure

cashclock/
├── backend/                    # FastAPI Python server
│   ├── main.py                 # API routes and server entry point
│   ├── forecaster.py           # Holt-Winters 30-day cash flow forecast
│   ├── anomaly.py              # Rolling z-score anomaly detection
│   ├── health_insights.py      # Runway score and health classification
│   ├── ai_coach.py             # Claude AI summaries and free-text Q&A
│   ├── loan.py                 # Loan sizing, risk scoring, repayment schedule
│   ├── pdf_report.py           # ReportLab PDF report generation
│   ├── database.py             # SQLite schema creation and queries
│   ├── data_generator.py       # Realistic SME transaction data generator
│   ├── generate_sample.py      # Script to seed the database with sample data
│   ├── seed_data.sql           # Pre-generated SQL seed data (10 SME businesses)
│   ├── requirements.txt        # Python dependencies
│   └── .env.example            # Environment variable template
│
├── frontend/                   # React + Vite web application
│   ├── src/
│   │   ├── App.jsx             # Root component and routing
│   │   ├── main.jsx            # Entry point
│   │   ├── index.css           # Global styles (Tailwind directives)
│   │   └── components/
│   │       ├── Landing.jsx                    # Role selection screen
│   │       ├── Dashboard.jsx                  # Manager portfolio dashboard
│   │       ├── CustomerDashboard.jsx          # Business owner dashboard
│   │       ├── CustomerView.jsx               # Business list selector
│   │       ├── ManagerBusinessPage.jsx        # Per-business detail (manager)
│   │       ├── LoanOfferPage.jsx              # Loan offer detail and application
│   │       ├── LoanOfferCard.jsx              # Loan offer summary card
│   │       ├── CashBalanceForecastChart.jsx   # 30-day forecast line chart
│   │       ├── CashFlowBreakdownChart.jsx     # Monthly inflow/outflow bar chart
│   │       ├── CashCalendar.jsx               # Daily colour-coded calendar
│   │       ├── PatternDrivers.jsx             # Trend sparkline + seasonality bars
│   │       ├── AnomalyBandMini.jsx            # Mini anomaly indicator
│   │       ├── WhatIfPanel.jsx                # Scenario builder UI
│   │       ├── TrainingProgress.jsx           # Loading animation screen
│   │       ├── LoginPage.jsx                  # Login screen
│   │       └── ChartLegendBaseline.jsx        # Chart legend component
│   ├── package.json
│   ├── vite.config.js          # Vite config — proxies /api/* to backend :8000
│   ├── tailwind.config.js
│   └── postcss.config.js
│
├── datasets/                   # Raw SME dataset files used for data generation
└── README.md

⚙️ Installation & Setup

These instructions set up the project to run entirely on your local machine. No cloud accounts, no deployment needed.

Prerequisites

Before you begin, make sure you have the following installed:

Tool Minimum Version Download
Python 3.10 python.org
Node.js 18 nodejs.org
npm bundled with Node.js
Git any recent version git-scm.com

An Anthropic API key is optional. The app works fully without it — it will use rule-based text summaries instead of AI-generated ones.


Step 1 — Clone the repository

git clone https://github.com/anshul23102/cashclock.git
cd cashclock

Step 2 — Set up the backend

cd backend

Create and activate a virtual environment:

# macOS / Linux
python3 -m venv venv
source venv/bin/activate

# Windows (Command Prompt)
python -m venv venv
venv\Scripts\activate

You should see (venv) appear at the start of your terminal prompt.

Install Python dependencies:

pip install -r requirements.txt

This installs FastAPI, statsmodels, pandas, ReportLab, anthropic, and all other dependencies.

Configure environment variables:

cp .env.example .env

Start the backend server:

uvicorn main:app --reload --port 8000

You should see output like:

INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process

The backend API is now running at http://localhost:8000. Keep this terminal open.


Step 3 — Set up the frontend

Open a new terminal window (keep the backend terminal running), then from the project root:

cd frontend
npm install
npm run dev

You should see:

  VITE v5.x.x  ready in XXX ms

  ➜  Local:   http://localhost:5173/

The Vite dev server automatically proxies all /api/* requests to the backend on port 8000. No CORS configuration or manual URL changes needed.


Step 4 — Open the app

Navigate to http://localhost:5173 in your browser.

You will see the CashClock landing page with two role options:

Role What you see
I'm a Bank Manager Portfolio view of all 10 SME clients with KPIs, charts, and loan tools
I'm a Business Owner Business selector → personal dashboard with forecast, anomalies, and loan offer

Troubleshooting

Problem Fix
ModuleNotFoundError on backend start Make sure your venv is activated — you should see (venv) in your prompt
npm install fails Check Node.js version: node --version must be 18+
Backend starts but frontend shows blank Confirm backend is running on port 8000 and frontend on 5173
AI summaries say "rule-based fallback" Either no API key is set, or the key in .env is invalid — this is expected behaviour

🚀 Usage Examples

Viewing a business dashboard

  1. Click "I'm a Business Owner" on the landing page
  2. Select a business from the list (e.g. Ravi Electronics)
  3. The dashboard loads with:
    • Current balance and week-over-week change
    • 30-day forecast chart with three confidence bands
    • No-cash zone warnings (if any)
    • Recent anomalies with severity labels

Running a what-if scenario

  1. Open any business dashboard and scroll to "What-If Scenario"
  2. Drag the Revenue Change slider (e.g. to −30%)
  3. Optionally enter a one-off cash injection (e.g. ₹50,000)
  4. Click "Run Scenario" — the forecast chart updates to show projected vs baseline

Asking the AI coach

Note: The AI Ask Box button is present in the UI but is not yet functional. Free-text Q&A is planned for a future release.

Downloading a PDF report

On any business dashboard, click "Download Report". A multi-page PDF is generated and downloaded, containing:

  • Business summary and current health score
  • 30-day forecast chart (image embedded)
  • Anomaly table with severity and causes
  • Loan eligibility summary

Manager: sending loan offers

  1. Log in as Bank Manager
  2. On the dashboard, click "Send Offers to All At-Risk" to bulk-send pre-approved offers
  3. Or search for a specific business → expand it → click "Approve Loan" to approve individually

Example API call

curl http://localhost:8000/api/businesses/1/forecast
{
  "runway_score": 67,
  "classification": "temporary_dip",
  "loan_eligible": true,
  "no_cash_zones": [
    { "date": "2025-05-03", "projected_balance": 8200, "severity": "critical" }
  ],
  "forecast": [
    { "date": "2025-04-13", "likely": 142500, "low": 118000, "high": 167000 }
  ]
}

📡 API Reference

Method Endpoint Description
GET /api/health Server health check
GET /api/businesses List all businesses with summary stats
GET /api/businesses/{id} Full business data + 365 days of transactions
GET /api/businesses/{id}/forecast 30-day forecast, health score, anomaly summary
GET /api/businesses/{id}/anomalies Detailed anomaly report with z-scores
GET /api/businesses/{id}/breakdown Monthly cash flow + expense composition
POST /api/businesses/{id}/scenario What-if scenario analysis
POST /api/businesses/{id}/ask AI Q&A endpoint (not yet wired to the UI)
GET /api/businesses/{id}/report/pdf Download multi-page PDF report
POST /api/businesses/{id}/apply-loan Business owner submits loan application
POST /api/businesses/{id}/approve-loan Manager approves a loan
GET /api/businesses/{id}/loan-status Poll current loan application status
GET /api/portfolio/manager Full manager portfolio with all KPIs
POST /api/portfolio/send-offers Bulk send pre-approved loan offers
POST /api/offer/accept Business owner accepts a loan offer

🧠 Technical Depth

Why Holt-Winters Exponential Smoothing?

Indian SME cash flows are strongly seasonal — festivals (Diwali, Holi), monsoon slowdowns, and quarterly GST cycles create recurring patterns that simpler models miss. Holt-Winters Triple Exponential Smoothing (ETS) was chosen because it explicitly models level, trend, and seasonality as separate components, producing personalised forecasts from each business's own 365-day history rather than industry averages.

Key engineering detail: Raw daily data is aggregated to weekly before fitting, which removes noise from zero-revenue weekends and public holidays. The fitted weekly forecast is then redistributed back to daily values using each business's observed day-of-week pattern — preserving weekly cycle accuracy while giving granular daily output.

Why rolling z-score for anomaly detection?

A fixed rupee threshold fails across SMEs with vastly different transaction scales — ₹50,000 is routine for one business and extraordinary for another. Rolling z-scores normalise each transaction against that business's own recent history window. A spike that is 2.5σ above this business's typical pattern is flagged regardless of absolute value, making the detector equally sensitive for a micro-SME and a mid-size manufacturer.

System Architecture

┌──────────────────────────────────────────────────────────────┐
│                      Browser (React 18)                       │
│   Landing Page → Manager Dashboard / Business Dashboard       │
│       Recharts · Tailwind CSS · Lucide Icons · Axios          │
└───────────────────────────┬──────────────────────────────────┘
                            │  HTTP / REST
                            │  (Vite proxy: /api/* → :8000)
                            ▼
┌──────────────────────────────────────────────────────────────┐
│                    FastAPI Backend (:8000)                     │
│                                                              │
│   ┌─────────────┐  ┌──────────────┐  ┌──────────────────┐   │
│   │ forecaster  │  │   anomaly    │  │ health_insights   │   │
│   │Holt-Winters │  │ rolling z-   │  │ runway score 0-  │   │
│   │ETS, 30-day  │  │ score detect │  │ 100, classif.    │   │
│   └─────────────┘  └──────────────┘  └──────────────────┘   │
│                                                              │
│   ┌─────────────┐  ┌──────────────┐  ┌──────────────────┐   │
│   │  ai_coach   │  │     loan     │  │   pdf_report     │   │
│   │ Claude API  │  │ risk scoring │  │   ReportLab      │   │
│   │ + fallback  │  │ + repayment  │  │   multi-page     │   │
│   └─────────────┘  └──────────────┘  └──────────────────┘   │
└───────────────────────────┬──────────────────────────────────┘
                            │
             ┌──────────────┴──────────────┐
             ▼                             ▼
  ┌─────────────────────┐      ┌────────────────────┐
  │      SQLite DB      │      │   Anthropic API    │
  │  businesses table   │      │   claude-haiku-4-5 │
  │  daily_data table   │      │   [optional]       │
  └─────────────────────┘      └────────────────────┘

Data flow for a forecast request:

Browser GET /api/businesses/{id}/forecast
  → main.py route handler
  → database.py: fetch 365 days of daily_data
  → forecaster.py: aggregate weekly → fit ETS → project 30 days → redistribute daily
  → anomaly.py: compute rolling z-scores → classify severity
  → health_insights.py: compute runway score → classify risk tier
  → ai_coach.py: generate summary (Claude API or rule-based)
  → JSON response → React renders charts

⚠️ Limitations

Limitation Detail
Simulated data 10 SME businesses are generated from realistic statistical templates — not real bank transaction data
No authentication The role selection screen has no passwords or session management; anyone can switch roles
SQLite only The database is a local file; it is not designed for concurrent multi-user access
India-only patterns All businesses are modelled with INR, Indian seasonal events, and Indian tax cycles
No live bank feed Cash flow data is pre-loaded; the app is not connected to any live transaction API or account aggregator
Forecast accuracy ETS works well for the patterns in the generated data; accuracy on real-world data would require re-calibration

🔮 Future Improvements

These are features that would be built with more time — they are not currently implemented.

  • Open Banking integration — connect to RBI account aggregator APIs for live transaction data
  • User authentication — secure login with JWT tokens and role-based access control
  • PostgreSQL migration — replace SQLite with a production-grade database for multi-user scale
  • Push notifications — alert business owners via SMS or email when a no-cash zone is predicted
  • 90-day forecast horizon — extend beyond the current 30-day window
  • Mobile app — React Native client for on-the-go cash health monitoring

📁 Configuration Reference

Variable Required Description
ANTHROPIC_API_KEY Optional Claude API key for AI-generated forecast summaries. Q&A feature not yet functional. Omit for rule-based fallbacks.
# Copy the example file and edit it
cp backend/.env.example backend/.env

Security: Never commit your .env file. It is already in .gitignore. Only commit .env.example with placeholder values.


📄 License & Compliance

This project is submitted under the Apache License 2.0, in compliance with NatWest Group Code for Purpose — India Hackathon requirements.

  • All commits are DCO-compliant (Developer Certificate of Origin)
  • A single email address (anshul23102@iiitd.ac.in) is used for all commits and hackathon communication
  • All third-party libraries are used under their respective open-source licences (MIT, Apache 2.0, BSD-3)
  • No confidential, proprietary, or real customer data is included in this repository
  • No API keys, passwords, or secrets are hard-coded anywhere in the codebase

Built with ❤️ for the NatWest Group Code for Purpose — India Hackathon

Helping Indian SMEs see their financial future clearly.

GitHub GitHub GitHub

About

Full-stack AI financial dashboard for Indian SMEs using Holt-Winters forecasting and Claude AI for cash flow prediction and loan modeling.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors