Skip to content

wasim-505/cfo-ai

Repository files navigation

CFO.ai Banner

🏦 CFO.ai

Autonomous Financial Intelligence Operating System

TypeScript React Node.js Tailwind CSS tRPC License

Transform raw financial data into actionable intelligence with AI-powered forecasting, anomaly detection, and conversational insights.

Features · Architecture · Quick Start · Tech Stack · API Reference · Contributing


🎯 Overview

CFO.ai is an enterprise-grade financial intelligence platform that combines advanced statistical modeling, machine learning, and conversational AI to deliver real-time financial insights. Built for startups and growing businesses, it serves as your autonomous AI-powered Chief Financial Officer.

"The goal is not to replace human judgment, but to augment it with data-driven intelligence that surfaces patterns, risks, and opportunities humans might miss."


✨ Features

📊 Real-Time Dashboard

Interactive financial dashboard with live KPI tracking, cash flow visualization, revenue forecasting with confidence intervals, and expense breakdown charts.

🤖 AI Forecasting Engine

Advanced time-series forecasting using ARIMA, Exponential Smoothing, and Monte Carlo simulations with automatic model selection and backtesting.

🔍 Anomaly Detection

Multi-method anomaly identification using Isolation Forest, Z-score analysis, frequency outlier detection, payroll spike detection, and vendor duplication checks.

📥 Data Ingestion

Robust data pipeline supporting CSV, Excel, and API imports with automatic validation, normalization, double-entry accounting verification, and deduplication.

🧠 AI CFO Assistant

Natural language financial advisor powered by RAG (Retrieval-Augmented Generation) providing strategic insights, answering business questions, and generating executive summaries.

📈 Scenario Modeling

Interactive what-if analysis tools for simulating business decisions, stress testing financial models, and comparing multiple strategic scenarios side-by-side.

📋 Automated Reports

Generate professional P&L statements, balance sheets, and cash flow statements with one click. Export to PDF or Excel for stakeholder presentations.

🏢 Multi-Company Support

Manage multiple business entities with role-based access control, tenant isolation, and collaborative workflows for teams and advisors.


🏗 Architecture

┌─────────────────────────────────────────────────────────────────┐
│                        CLIENT LAYER                             │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────────┐   │
│  │Dashboard │  │Forecasts │  │ Anomaly  │  │  AI Chat     │   │
│  │  & KPIs  │  │& Scenar. │  │  Alerts  │  │  Assistant   │   │
│  └────┬─────┘  └────┬─────┘  └────┬─────┘  └──────┬───────┘   │
│       └──────────────┴─────────────┴───────────────┘           │
│                    React 19 + Tailwind 4                        │
└───────────────────────────┬─────────────────────────────────────┘
                            │ tRPC v11 (Type-Safe RPC)
┌───────────────────────────┴─────────────────────────────────────┐
│                        SERVER LAYER                             │
│  ┌──────────────────────────────────────────────────────────┐   │
│  │                   Express + tRPC Router                   │   │
│  ├──────────┬──────────┬──────────┬──────────┬─────────────┤   │
│  │  Data    │Financial │Forecast  │ Anomaly  │   Report    │   │
│  │Ingestion │Modeling  │ Engine   │Detection │ Generator   │   │
│  │ Service  │ Service  │ Service  │ Service  │  Service    │   │
│  └────┬─────┴────┬─────┴────┬─────┴────┬─────┴──────┬──────┘   │
│       └──────────┴──────────┴──────────┴────────────┘          │
│                    Node.js + TypeScript                          │
└───────────────────────────┬─────────────────────────────────────┘
                            │
┌───────────────────────────┴─────────────────────────────────────┐
│                        DATA LAYER                               │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────────────┐  │
│  │   MySQL /    │  │  S3 Object   │  │    LLM Service       │  │
│  │   TiDB       │  │   Storage    │  │  (AI Completions)    │  │
│  │  (17 tables) │  │  (Files/CSV) │  │                      │  │
│  └──────────────┘  └──────────────┘  └──────────────────────┘  │
│                  Drizzle ORM + Migrations                       │
└─────────────────────────────────────────────────────────────────┘

🗄 Database Schema

The platform uses a comprehensive 17-table relational schema designed for financial data integrity:

Table Purpose
users Authentication, roles, and profile management
companies Multi-tenant company entities with fiscal settings
companyMembers Role-based access control per company
accounts Chart of accounts (assets, liabilities, equity, revenue, expenses)
transactions Double-entry journal entries with full audit trail
invoices / invoiceItems Accounts receivable tracking
expenses Categorized expense management
budgets Budget planning and variance analysis
payroll Employee compensation tracking
forecasts / forecastSnapshots AI-generated predictions with versioning
anomalies Detected irregularities with risk scoring
reports Generated financial statements
scenarios What-if analysis configurations
aiConversations / aiMessages AI CFO chat history and context

🧮 Financial Models

Forecasting Engine

Model Method Best For
ARIMA Autoregressive Integrated Moving Average Stationary time series with trends
Exponential Smoothing Holt-Winters triple smoothing Seasonal patterns in revenue/expenses
Monte Carlo 10,000-iteration stochastic simulation Risk quantification and confidence intervals

All models include walk-forward validation, drift detection, and automatic backtesting with MAE/RMSE metrics.

Anomaly Detection

Method Detection Type Sensitivity
Isolation Forest Multi-dimensional outlier isolation High — catches complex patterns
Z-Score Analysis Statistical deviation from mean Medium — best for amount outliers
Frequency Analysis Temporal pattern irregularities Medium — detects timing anomalies
Payroll Spike IQR-based compensation outliers High — flags unusual payroll
Vendor Duplication Levenshtein string similarity Low — catches naming variations
Category Drift Distribution shift detection Medium — monitors spending patterns

KPI Calculations

Profitability          Liquidity             Leverage              Efficiency
─────────────         ──────────            ─────────             ──────────
• Gross Margin         • Current Ratio       • Debt-to-Equity      • DSO
• Operating Margin     • Quick Ratio         • Interest Coverage    • DIO
• Net Margin           • Working Capital     • Equity Multiplier    • DPO
• ROA / ROE            • Cash Ratio          • Debt Ratio           • CCC
                                                                    
                       DuPont Analysis: ROE = Margin × Turnover × Leverage

🚀 Quick Start

Prerequisites

  • Node.js ≥ 22.x
  • pnpm ≥ 10.x
  • MySQL or TiDB database

Installation

# Clone the repository
git clone https://github.com/wasim-505/cfo-ai.git
cd cfo-ai

# Install dependencies
pnpm install

# Configure environment variables
cp .env.example .env
# Edit .env with your database URL and API keys

# Push database schema
pnpm db:push

# Start development server
pnpm dev

The application will be available at http://localhost:3000.

Environment Variables

Variable Description
DATABASE_URL MySQL/TiDB connection string
JWT_SECRET Session cookie signing secret
VITE_APP_ID OAuth application ID
OAUTH_SERVER_URL OAuth backend base URL

🛠 Tech Stack

Frontend Backend Database AI/ML DevOps
  • React 19
  • Tailwind CSS 4
  • Recharts
  • Framer Motion
  • shadcn/ui
  • Node.js 22
  • Express 4
  • tRPC 11
  • TypeScript 5.9
  • Zod
  • MySQL / TiDB
  • Drizzle ORM
  • S3 Storage
  • Migrations
  • ARIMA
  • Monte Carlo
  • Isolation Forest
  • LLM Integration
  • RAG Pipeline
  • Vitest
  • ESBuild
  • Vite 7
  • pnpm
  • CI/CD Ready

📁 Project Structure

cfo-ai/
├── client/                     # Frontend application
│   ├── src/
│   │   ├── components/         # Reusable UI components
│   │   │   ├── ui/             # shadcn/ui primitives
│   │   │   └── FinancialDashboard.tsx
│   │   ├── pages/              # Route-level pages
│   │   │   ├── Home.tsx        # Landing page + Dashboard
│   │   │   └── NotFound.tsx
│   │   ├── contexts/           # React contexts (Theme, Auth)
│   │   ├── hooks/              # Custom hooks
│   │   ├── lib/trpc.ts         # tRPC client binding
│   │   ├── App.tsx             # Router & layout
│   │   └── index.css           # Global styles & design tokens
│   └── index.html
│
├── server/                     # Backend application
│   ├── services/
│   │   ├── financialModeling.ts    # KPI engine (margins, ratios, DuPont)
│   │   ├── dataIngestion.ts        # CSV/Excel parser & validator
│   │   ├── forecasting.ts          # ARIMA, smoothing, Monte Carlo
│   │   ├── anomalyDetection.ts     # Isolation Forest, Z-score, fraud
│   │   ├── financialModeling.test.ts
│   │   └── dataIngestion.test.ts
│   ├── _core/                  # Framework plumbing (auth, context, LLM)
│   ├── db.ts                   # Database query helpers
│   ├── routers.ts              # tRPC procedure definitions
│   └── storage.ts              # S3 file storage helpers
│
├── drizzle/                    # Database schema & migrations
│   └── schema.ts               # 17-table financial data model
│
├── shared/                     # Shared types & constants
└── package.json

📡 API Reference

CFO.ai exposes a fully type-safe API via tRPC. All endpoints are accessible under /api/trpc.

Authentication

Procedure Type Auth Description
auth.me Query Public Get current user session
auth.logout Mutation Public Clear session cookie

Financial Data (Planned)

Procedure Type Auth Description
transactions.list Query Protected List transactions with filters
transactions.create Mutation Protected Create new transaction
dashboard.kpis Query Protected Get real-time KPI metrics
forecasts.generate Mutation Protected Run forecasting models
anomalies.scan Mutation Protected Trigger anomaly detection
reports.generate Mutation Protected Generate financial report
ai.chat Mutation Protected Send message to AI CFO

🧪 Testing

The project includes a comprehensive test suite powered by Vitest:

# Run all tests
pnpm test

# Run tests in watch mode
pnpm test -- --watch
Test Suite Tests Coverage
Financial Modeling 21 Profitability, liquidity, leverage, efficiency, DuPont, edge cases
Data Ingestion 23 Validation, normalization, idempotency, double-entry, batch processing
Authentication 1 Session logout and cookie clearing
Total 45 All passing

🗺 Roadmap

  • Database schema design (17 tables)
  • Financial modeling service (KPIs, ratios, DuPont analysis)
  • Data ingestion pipeline (CSV/Excel, validation, normalization)
  • Forecasting engine (ARIMA, exponential smoothing, Monte Carlo)
  • Anomaly detection (Isolation Forest, Z-score, frequency, vendor duplication)
  • Real-time financial dashboard with interactive charts
  • Professional landing page
  • Comprehensive test suite (45 tests)
  • Scenario modeling & stress testing
  • AI CFO chatbot with RAG
  • Automated report generation (P&L, balance sheet, cash flow)
  • Multi-company management & RBAC
  • PDF/Excel export
  • Webhook integrations (Stripe, QuickBooks, Xero)
  • Mobile-responsive dashboard

🤝 Contributing

Contributions are welcome! Please read the Contributing Guidelines before submitting a pull request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📄 License

This project is licensed under the MIT License — see the LICENSE file for details.



Built with precision for financial excellence.

Made with ❤️ by wasim-505

Releases

No releases published

Packages

 
 
 

Contributors