Skip to content

SmartWise represents the future of personalized financial guidance - making sophisticated investment strategies accessible to everyone, regardless of their experience level. 🎯

Notifications You must be signed in to change notification settings

smattaparthy/SmartWise

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

20 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

SmartWise Investment Assistant

Production-Ready Personal Investment Platform with AI-Powered Insights

SmartWise is an intelligent investment assistant that provides personalized guidance through a sophisticated persona-based system. Built with FastAPI, Next.js 14, and Claude 3.5 Sonnet AI, it delivers tailored investment strategies from beginner-friendly index fund recommendations to advanced research-driven insights.

Python FastAPI Next.js TypeScript License


🎯 Key Features

Intelligent Persona System

  • Dynamic Risk Assessment: 10-question onboarding questionnaire analyzes investment experience, goals, risk tolerance, and preferences
  • Three Specialized Personas: Each with tailored features and interfaces
  • Persona Reassessment: Update your profile as circumstances change
  • AI-Powered Classification: Confidence scoring and reasoning for persona assignments

Persona A - Starter 🌱

For new investors seeking simplicity

  • Curated Index Fund Recommendations: VOO, VTI, VXUS, BND, VNQ with detailed analysis
  • Three Portfolio Strategies: Conservative (80/20), Balanced (60/40), Growth (90/10)
  • Educational Content: Expense ratios, asset classes, investment principles
  • Getting Started Guide: Step-by-step investment approach

Persona B - Rebalance βš–οΈ

For portfolio owners seeking optimization

  • CSV Portfolio Upload: Import holdings from any brokerage
  • Comprehensive Analysis:
    • Total value calculation
    • Sector allocation breakdown
    • Diversification scoring (0-1 scale)
    • Concentration risk detection (>30% threshold)
  • AI-Powered Rebalancing:
    • Claude 4.5 Sonnet generates personalized reasoning
    • Three model portfolios (Conservative/Balanced/Growth)
    • Buy/sell recommendations with trade-by-trade guidance
    • Dollar amounts and share quantities

Persona C - Moonshot πŸš€

For advanced investors seeking research insights

  • RAG-Powered Research Assistant: Vector search across curated investment documents
  • Interactive Chatbot: Conversational AI for investment questions
  • Source Citations: Relevance scores and document references
  • Research Library: Browse and explore investment materials
  • Context Maintenance: Multi-turn conversations with history

πŸ“Έ Screenshots

Landing Page

Home Page

Clean, professional landing page with clear call-to-action and feature highlights

Onboarding Questionnaire

Onboarding

Interactive 10-question assessment to determine your investor persona with card-based UI

Portfolio Upload Interface

Portfolio Upload

CSV portfolio upload for comprehensive analysis and rebalancing recommendations

Portfolio Ready for Analysis

Portfolio Uploaded

File uploaded successfully - analyze your holdings for sector allocation and concentration risks

Persona A - Starter Dashboard

Persona A Dashboard

Index fund recommendations with three-fund portfolio allocation (VOO 50%, BND 30%, VTI 20%) and getting started guide

Persona B - Portfolio Analysis

Persona B Analysis

Comprehensive portfolio analysis showing total value, sector breakdown, diversification metrics, and concentration alerts

Persona B - Rebalancing Suggestions

Persona B Rebalancing

AI-powered rebalancing recommendations with specific buy/sell suggestions and reasoning for reducing Healthcare overweight

Persona C - Moonshot Investment Ideas

Persona C Moonshot

High-risk investment ideas including ARKK, COIN, CRSP, PLTR, TSLA with research sources and time horizons


πŸ—οΈ Architecture

Technology Stack

Backend

  • FastAPI: High-performance REST API with automatic OpenAPI documentation
  • Python 3.11+: Modern Python with type hints and async support
  • SQLAlchemy 2.0: ORM for database operations
  • Anthropic Claude: AI reasoning generation via Claude 4.5 Sonnet
  • ChromaDB: Vector database for RAG system
  • JWT Authentication: Secure token-based auth with bcrypt password hashing
  • Pytest: Comprehensive test suite (40+ tests)

Frontend

  • Next.js 14: React framework with App Router and Server Components
  • TypeScript: Type-safe development
  • Tailwind CSS: Utility-first styling for rapid UI development
  • React Context: State management for authentication

Infrastructure

  • Docker: Containerized deployment
  • Docker Compose: Multi-container orchestration
  • SQLite: Development database (PostgreSQL-ready)
  • Uvicorn: ASGI server with hot reload

System Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚          Presentation Layer                  β”‚
β”‚      Next.js 14 (TypeScript + React)        β”‚
β”‚         Tailwind CSS + App Router           β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                     ↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚            API Gateway                       β”‚
β”‚         FastAPI + CORS + JWT                β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                     ↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚          Business Logic                      β”‚
β”‚   Auth β€’ Onboarding β€’ Portfolio β€’ RAG       β”‚
β”‚   Market Data β€’ LLM Service                 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                     ↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚            Data Layer                        β”‚
β”‚   SQLAlchemy ORM β€’ Chroma Vector Store      β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                     ↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚          External Services                   β”‚
β”‚   Alpha Vantage β€’ Anthropic Claude          β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸš€ Quick Start

Prerequisites

  • Docker and Docker Compose
  • (Optional) Alpha Vantage API key
  • (Recommended) Anthropic API key for AI features

1. Clone and Configure

git clone https://github.com/yourusername/smartwise-ai.git
cd smartwise-ai

# Create .env file
cat > .env << EOF
# Backend Configuration
SECRET_KEY=your-secret-key-change-in-production
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=60

# External APIs
ALPHA_VANTAGE_API_KEY=your-alpha-vantage-key
ANTHROPIC_API_KEY=your-anthropic-key

# Database
DATABASE_URL=sqlite:///./investing_assistant.db

# Chroma Vector Store
CHROMA_PERSIST_DIRECTORY=./chroma_db

# Frontend Configuration
NEXT_PUBLIC_API_URL=http://localhost:8200
EOF

2. Launch Application

# Start all services
docker-compose up -d --build

# View logs
docker-compose logs -f

# Check status
docker-compose ps

3. Access Application

4. Create Your First Account

  1. Navigate to http://localhost:3200
  2. Click "Sign Up"
  3. Enter email and password
  4. Complete 10-question onboarding
  5. Get your persona assignment
  6. Access persona-specific dashboard

πŸ“ Project Structure

smartwise_ai/
β”œβ”€β”€ backend/                    # FastAPI backend
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ main.py            # FastAPI application
β”‚   β”‚   β”œβ”€β”€ models.py          # SQLAlchemy models
β”‚   β”‚   β”œβ”€β”€ schemas.py         # Pydantic schemas
β”‚   β”‚   β”œβ”€β”€ auth.py            # Authentication logic
β”‚   β”‚   β”œβ”€β”€ onboarding.py      # Persona classification
β”‚   β”‚   β”œβ”€β”€ portfolio.py       # Portfolio analysis
β”‚   β”‚   β”œβ”€β”€ market_data.py     # Alpha Vantage integration
β”‚   β”‚   β”œβ”€β”€ rag.py             # RAG system
β”‚   β”‚   β”œβ”€β”€ llm_service.py     # Claude API integration
β”‚   β”‚   β”œβ”€β”€ database.py        # Database configuration
β”‚   β”‚   └── routers/           # API route handlers
β”‚   β”‚       β”œβ”€β”€ auth.py
β”‚   β”‚       β”œβ”€β”€ onboarding.py
β”‚   β”‚       β”œβ”€β”€ portfolio.py
β”‚   β”‚       β”œβ”€β”€ market.py
β”‚   β”‚       └── rag.py
β”‚   β”œβ”€β”€ tests/                 # Backend tests (40+ tests)
β”‚   β”‚   β”œβ”€β”€ test_auth.py
β”‚   β”‚   β”œβ”€β”€ test_onboarding.py
β”‚   β”‚   β”œβ”€β”€ test_portfolio.py
β”‚   β”‚   └── test_market.py
β”‚   β”œβ”€β”€ Dockerfile
β”‚   └── requirements.txt
β”œβ”€β”€ frontend/                  # Next.js frontend
β”‚   β”œβ”€β”€ app/                   # App Router pages
β”‚   β”‚   β”œβ”€β”€ page.tsx          # Landing page
β”‚   β”‚   β”œβ”€β”€ register/
β”‚   β”‚   β”œβ”€β”€ login/
β”‚   β”‚   β”œβ”€β”€ onboarding/
β”‚   β”‚   β”œβ”€β”€ reassess-persona/
β”‚   β”‚   └── dashboard/
β”‚   β”‚       β”œβ”€β”€ page.tsx      # Dashboard hub
β”‚   β”‚       β”œβ”€β”€ starter/      # Persona A
β”‚   β”‚       β”œβ”€β”€ rebalance/    # Persona B
β”‚   β”‚       └── moonshot/     # Persona C
β”‚   β”œβ”€β”€ components/
β”‚   β”‚   β”œβ”€β”€ AppShell.tsx      # Layout with header
β”‚   β”‚   β”œβ”€β”€ OnboardingStep.tsx
β”‚   β”‚   β”œβ”€β”€ CardOption.tsx
β”‚   β”‚   └── ...
β”‚   β”œβ”€β”€ lib/
β”‚   β”‚   └── api.ts            # API utilities
β”‚   β”œβ”€β”€ Dockerfile
β”‚   └── package.json
β”œβ”€β”€ docs/                      # Documentation
β”‚   β”œβ”€β”€ ARCHITECTURE.md       # System architecture
β”‚   β”œβ”€β”€ API.md                # Complete API reference
β”‚   β”œβ”€β”€ USER_GUIDE.md         # User documentation
β”‚   β”œβ”€β”€ screenshots/          # Application screenshots
β”‚   └── ...
β”œβ”€β”€ docker-compose.yml         # Container orchestration
β”œβ”€β”€ .env                       # Environment variables
└── README.md                  # This file

πŸ”§ Development

Backend Development

cd backend

# Create virtual environment
python3.11 -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

# Run database migrations
python -c "from app.database import engine; from app.models import Base; Base.metadata.create_all(bind=engine)"

# Start development server
uvicorn app.main:app --host 0.0.0.0 --port 8200 --reload

Frontend Development

cd frontend

# Install dependencies
npm install

# Start development server
npm run dev

# Build for production
npm run build

# Start production server
npm start

Running Tests

# Backend tests
cd backend
pytest tests/ -v --cov=app --cov-report=html

# Test results will show:
# - 40+ total tests
# - Authentication tests (9)
# - Onboarding tests (9)
# - Portfolio tests (12)
# - Market data tests (10)

# View coverage report
open htmlcov/index.html

πŸ“š Documentation

Comprehensive documentation available in the docs/ directory:

Document Description
ARCHITECTURE.md Complete system architecture, technology stack, design patterns, scalability considerations
API.md Full API reference with request/response examples, error codes, authentication
USER_GUIDE.md End-user documentation, workflows, FAQs, troubleshooting
FEATURES.md Detailed feature descriptions and implementation notes
QUICK_START.md Fast setup guide for new developers

πŸ” Security Features

Authentication & Authorization

  • Bcrypt Password Hashing: Automatic salt generation, secure password storage
  • JWT Tokens: 60-minute expiry, Bearer token authentication
  • Protected Routes: Middleware validation on all authenticated endpoints
  • CORS Configuration: Restricted origins, secure headers

Input Validation

  • Pydantic Schemas: Type checking, required field enforcement
  • SQL Injection Prevention: SQLAlchemy ORM with parameterized queries
  • Email Validation: RFC-compliant email format checking

API Key Management

  • Environment Variables: All secrets in .env files
  • Graceful Degradation: Fallback to mock data when APIs unavailable
  • Rate Limiting Ready: Built-in support for production rate limiters

🎨 Key Features Deep Dive

AI-Powered Portfolio Rebalancing

The portfolio rebalancing feature uses Claude 4.5 Sonnet to generate personalized reasoning:

# Example rebalancing recommendation with AI reasoning
{
  "ticker": "AAPL",
  "action": "sell",
  "shares": 75,
  "amount": 12375.00,
  "reasoning": "Your portfolio is heavily concentrated in Technology at 100%
               versus the balanced target of 25%. Reducing AAPL position helps
               diversify sector exposure and manage concentration risk. This
               rebalancing aligns with a balanced growth strategy while maintaining
               exposure to quality tech names.",
  "ai_generated": true
}

Rebalancing Algorithm:

  1. Calculate current sector allocations
  2. Compare against target model (Conservative/Balanced/Growth)
  3. Identify >5% deviations
  4. Generate buy/sell recommendations
  5. Call Claude API for personalized reasoning
  6. Return prioritized action plan

RAG-Powered Research System

Built on ChromaDB with sentence-transformers embeddings:

Pipeline:

Question β†’ Embedding β†’ Vector Search β†’
Top-5 Chunks β†’ Context Formatting β†’
Response Generation β†’ Source Citations

Example Query:

Q: "What factors should I consider for semiconductor stocks?"

Response:
- Technology leadership (process nodes)
- Customer diversification
- Capital intensity
- Cyclicality patterns
- Geopolitical risks

Sources:
- "Semiconductor Industry Analysis 2024" (0.89 relevance)
- "Technology Sector Deep Dive" (0.76 relevance)

Persona Classification Algorithm

Risk-based scoring system with multi-factor analysis:

Risk Score = Ξ£ (question_answer_value Γ— question_weight)

Persona Assignment:
- A (Starter):   score ≀ 30 OR advice_pref = "simple"
- B (Rebalance): 31 ≀ score ≀ 60 OR (advice = "analysis" AND has_portfolio)
- C (Moonshot):  score β‰₯ 61 OR advice_pref = "ideas"

Confidence = answer_consistency_score

πŸ§ͺ Testing

Test Coverage

pytest tests/ -v --cov=app

# Coverage Report:
# Name                          Stmts   Miss  Cover
# -------------------------------------------------
# app/auth.py                      45      2    96%
# app/onboarding.py                78      4    95%
# app/portfolio.py                125      8    94%
# app/market_data.py               89      6    93%
# app/rag.py                       67      5    93%
# app/llm_service.py               34      3    91%
# -------------------------------------------------
# TOTAL                           438     28    94%

Test Categories

Authentication Tests (9 tests)

  • User registration
  • Login validation
  • JWT token generation
  • Protected route access

Onboarding Tests (9 tests)

  • Questionnaire retrieval
  • Answer validation
  • Persona A classification
  • Persona B classification
  • Persona C classification
  • Reassessment flow

Portfolio Tests (12 tests)

  • CSV parsing
  • Portfolio analysis
  • Sector allocation
  • Diversification scoring
  • Rebalancing recommendations

Market Data Tests (10 tests)

  • Ticker search
  • Symbol lookup
  • API fallback to mock data
  • Caching behavior

🚒 Deployment

Production Checklist

Security:

  • Change SECRET_KEY to cryptographically secure value
  • Use environment-specific .env files
  • Enable HTTPS/TLS
  • Add rate limiting (slowapi or nginx)
  • Configure CORS for production domains only

Database:

  • Migrate to PostgreSQL
  • Set up automated backups
  • Enable connection pooling
  • Create database indexes

Caching:

  • Deploy Redis for distributed caching
  • Configure cache expiry policies
  • Set up cache warming

Infrastructure:

  • Use container orchestration (Kubernetes, ECS, Cloud Run)
  • Deploy frontend to CDN (CloudFlare, CloudFront)
  • Set up monitoring (Prometheus, Grafana)
  • Configure logging (ELK stack, CloudWatch)
  • Add health check endpoints

Performance:

  • Enable response compression (gzip)
  • Implement API response caching
  • Optimize database queries
  • Add CDN for static assets

Recommended Production Architecture

Internet
   ↓
CloudFlare CDN (SSL/TLS, DDoS Protection)
   ↓
Load Balancer (nginx/ALB)
   ↓
Backend Instances (FastAPI Γ— 3)
   ↓
PostgreSQL (Primary + Read Replicas)
   ↓
Redis (Caching) + Chroma (Vectors)

πŸ“Š API Endpoints

Authentication (/auth)

  • POST /auth/register - Create account
  • POST /auth/login - Get JWT token
  • GET /auth/me - Get current user

Onboarding (/onboarding)

  • GET /onboarding/questionnaire - Get questions
  • POST /onboarding/submit - Initial persona assignment
  • POST /onboarding/reassess - Update persona
  • GET /onboarding/persona - Get current persona

Market Data (/market)

  • GET /market/search?q={query} - Search tickers
  • GET /market/ticker/{symbol} - Get ticker details

Portfolio (/portfolio) - Persona B Only

  • POST /portfolio/upload - Upload CSV
  • POST /portfolio/analyze - Analyze portfolio
  • POST /portfolio/rebalance?model_type={model} - Get recommendations

RAG (/rag) - Persona C Only

  • POST /rag/query - Ask research question
  • GET /rag/documents - List documents
  • GET /rag/stats - Get system stats

Complete API documentation: http://localhost:8200/docs


🀝 Contributing

Development Workflow

  1. Fork and clone:
git clone https://github.com/yourusername/smartwise-ai.git
cd smartwise-ai
  1. Create feature branch:
git checkout -b feature/your-feature-name
  1. Make changes:
  • Follow existing code style
  • Add tests for new features
  • Update documentation
  1. Test changes:
cd backend && pytest tests/ -v
cd frontend && npm test
  1. Submit PR:
  • Clear description of changes
  • Reference any related issues
  • Include screenshots for UI changes

Code Style

Python:

  • Follow PEP 8
  • Use type hints
  • Document functions with docstrings
  • Maximum line length: 100 characters

TypeScript/React:

  • Follow React best practices
  • Use functional components and hooks
  • Type all props and state
  • Use descriptive component names

πŸ› Troubleshooting

Common Issues

"Connection refused" on http://localhost:3200

# Check if containers are running
docker-compose ps

# Restart if needed
docker-compose restart frontend

"Invalid token" errors

# Token expired (60-minute TTL)
# Solution: Log out and log in again

CSV upload fails

# Verify format: symbol,shares,purchase_price
# Use correct column names (symbol or ticker)
# Ensure no spaces in headers

No rebalancing suggestions

# Portfolio is already balanced (<5% deviation)
# Try a different model (conservative/balanced/growth)
# Upload a more concentrated portfolio to test

For more troubleshooting, see docs/TROUBLESHOOTING.md


πŸ“ˆ Roadmap

Q1 2025

  • Real-time market data integration
  • Portfolio performance tracking
  • Tax-loss harvesting suggestions
  • Enhanced AI reasoning with streaming responses

Q2 2025

  • Mobile app (React Native)
  • Dividend reinvestment planning
  • Multi-currency support
  • Social features and community insights

Q3 2025

  • Advanced portfolio analytics
  • Options and derivatives support
  • Automated rebalancing execution
  • Integration with major brokerages

Q4 2025

  • Machine learning price predictions
  • Custom portfolio strategies
  • Crypto asset support
  • International markets

πŸ“„ License

This project is for educational purposes only.

Disclaimer: This is not financial advice. SmartWise Investment Assistant is an educational tool designed to help users explore investment concepts. All investment decisions should be made in consultation with a licensed financial advisor who understands your complete financial situation, goals, and risk tolerance.


πŸ™ Acknowledgments

  • FastAPI: High-performance async Python framework
  • Next.js: React framework for production
  • Anthropic: Claude 4.5 Sonnet AI model
  • Alpha Vantage: Market data API
  • ChromaDB: Vector database for RAG
  • Tailwind CSS: Utility-first CSS framework

πŸ“ž Support


⭐ Star History

If you find this project helpful, please consider giving it a star! ⭐


Built with ❀️ by the SmartWise Team

Empowering smart investment decisions through AI and personalization

About

SmartWise represents the future of personalized financial guidance - making sophisticated investment strategies accessible to everyone, regardless of their experience level. 🎯

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •