AI-Powered Portfolio Optimization for the Modern Investor
PortfolioMax is a sophisticated portfolio optimization platform that combines cutting-edge AI with institutional-grade portfolio theory to deliver optimal investment allocations. Built with modern technologies and featuring advanced machine learning algorithms, it provides real-time portfolio optimization, risk management, and performance analytics.
- Machine Learning Predictions: Advanced ML models for enhanced return forecasting
- Multiple Optimization Strategies: Maximum Sharpe ratio, minimum variance, and custom targets
- Real-time Optimization: Instant portfolio optimization with live market data
- Expected Performance: Achieving 2.69 average Sharpe ratio with 40.2% expected returns
- Multi-layered Constraints: Sophisticated constraint systems for risk control
- Risk Tolerance Profiles: Conservative, Moderate, and Aggressive strategies
- Drawdown Analysis: Maximum potential loss tracking (24.14% historical worst-case)
- Cluster-based Diversification: 4-cluster asset allocation across 45+ instruments
- Interactive Portfolio Construction: Build portfolios with real-time weight validation
- Optimization Types: Improve, rebalance, or risk-adjust existing portfolios
- Template Portfolios: Quick-start with Balanced, Growth, or Conservative templates
- Core Holdings Preservation: Maintain key positions while optimizing around them
- Performance Tracking: Live portfolio performance vs benchmarks (+7.8% outperformance)
- Efficient Frontier Visualization: Interactive risk-return analysis
- Comprehensive Metrics: Sharpe ratio, volatility, max drawdown, and more
- Portfolio Comparison: Side-by-side analysis of multiple strategies
- Save & Manage Portfolios: Persistent storage with names and descriptions
- Portfolio History: Track creation and modification dates
- Export Capabilities: Download optimization results and analytics
- User Authentication: Secure JWT-based user sessions
- FastAPI - Modern, fast web framework for APIs
- Python 3.12+ - Core programming language
- scikit-learn - Machine learning library for predictions
- NumPy & Pandas - Data manipulation and analysis
- SciPy - Scientific computing and optimization algorithms
- yfinance - Real-time financial data
- Pydantic - Data validation and settings
- Passlib - Password hashing and authentication
- Python-JOSE - JWT token handling
- React 18 - Modern UI library with hooks
- Vite - Lightning-fast build tool and dev server
- TailwindCSS - Utility-first CSS framework
- Framer Motion - Smooth animations and transitions
- Recharts - Beautiful, responsive charts
- React Router - Client-side routing
- Axios - HTTP client for API communication
- Lucide React - Beautiful, customizable icons
- Uvicorn - ASGI server for FastAPI
- ESLint - JavaScript/React code linting
- PostCSS - CSS processing and optimization
- Docker - Containerization (optional)
portfolio-optimization/
βββ π backend/ # FastAPI Backend
β βββ π api/ # API Layer
β β βββ __init__.py
β β βββ auth.py # JWT Authentication
β β βββ data_utils.py # Data Processing Utilities
β β βββ endpoints.py # API Route Handlers
β β βββ models.py # Pydantic Data Models
β βββ π data/ # Data Storage
β β βββ π individual_assets/ # Stock Price Data (45 assets)
β β βββ π analytics/ # Analysis Results
β β βββ cleaned_prices.csv # Processed Price Data
β β βββ returns_matrix_latest.csv # Return Calculations
β β βββ asset_features.csv # ML Feature Engineering
β β βββ optimization_results_summary.csv # Portfolio Results
β βββ π scripts/ # Data Processing Scripts
β β βββ enhanced_portfolio_optimizer.py # Core Optimization Engine
β β βββ enhanced_ml_training.py # ML Model Training
β β βββ data_analysis_and_cleaning.py # Data Preprocessing
β β βββ feature_engineering.py # Feature Creation
β βββ π analysis_plots/ # Generated Visualizations
β βββ api_server.py # FastAPI Application Entry
β βββ requirements_api.txt # API Dependencies
β βββ requirements.txt # Core Dependencies
β βββ venv/ # Virtual Environment
βββ π frontend/frontend/ # React Frontend
β βββ π src/
β β βββ π components/ # Reusable UI Components
β β β βββ AllocationChart.jsx # Portfolio Pie Charts
β β β βββ CustomPortfolioBuilder.jsx # Portfolio Construction
β β β βββ EfficientFrontierChart.jsx # Risk-Return Visualization
β β β βββ OptimizationResults.jsx # Results Display
β β β βββ SavedPortfolios.jsx # Portfolio Management
β β β βββ StockClusterView.jsx # Asset Clustering Display
β β βββ π pages/ # Application Pages
β β β βββ Dashboard.jsx # Main Application Interface
β β β βββ LandingPage.jsx # Marketing Landing Page
β β β βββ Login.jsx # User Authentication
β β β βββ Signup.jsx # User Registration
β β βββ π contexts/ # React Context
β β β βββ AuthContext.jsx # Authentication State
β β βββ π services/ # API Integration
β β β βββ authService.js # API Client Functions
β β βββ App.jsx # Main App Component
β β βββ main.jsx # React Entry Point
β β βββ index.css # Global Styles
β βββ package.json # Node.js Dependencies
β βββ vite.config.js # Vite Configuration
β βββ tailwind.config.js # TailwindCSS Configuration
βββ README.md # This file
βββ .gitignore # Git ignore rules
- Python 3.12+ with pip
- Node.js 18+ with npm
- Git for version control
git clone https://github.com/yourusername/portfolio-optimization.git
cd portfolio-optimization# Navigate to backend directory
cd backend
# Create and activate virtual environment
python3 -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements_api.txt
pip install -r requirements.txt
# Start the FastAPI server
python3 -m uvicorn api_server:app --reload --host 0.0.0.0 --port 8000The backend API will be available at http://localhost:8000
# Navigate to frontend directory (in a new terminal)
cd frontend/frontend
# Install Node.js dependencies
npm install
# Start the development server
npm run devThe frontend will be available at http://localhost:5173 (or next available port)
- Open your browser to the frontend URL
- Use demo credentials:
- Email:
demo@portfoliomax.com - Password:
demo123
- Email:
- Start optimizing portfolios!
- US Equities: AAPL, MSFT, GOOGL, AMZN, NVDA, TSLA, META, etc.
- ETFs: SPY, QQQ, VTI, IWM, EFA, EEM, VNQ
- Bonds: TLT (Long-term Treasuries)
- Commodities: GLD (Gold), NEM (Mining)
- Sectors: Technology, Healthcare, Finance, Consumer, Energy, Utilities
- Data Collection: Real-time price data via yfinance API
- Feature Engineering: 20+ technical and fundamental features
- ML Enhancement: Return predictions using ensemble models
- Risk Modeling: Historical covariance with 2,511+ observations
- Clustering: K-means segmentation into 4 asset clusters
POST /auth/login # User login with JWT token
POST /auth/register # New user registration
GET /auth/profile # Get user profile informationGET /data/stocks # Available stocks with metrics
GET /data/clusters # Asset clustering information
GET /data/efficient-frontier # Risk-return efficient frontierPOST /optimize # Standard portfolio optimization
POST /optimize/custom # Custom portfolio optimization
GET /optimize/strategies # Available optimization strategiesPOST /portfolios/save # Save optimized portfolio
GET /portfolios # Get user's saved portfolios
GET /portfolios/{id} # Get specific portfolio details
PUT /portfolios/{id} # Update portfolio metadata
DELETE /portfolios/{id} # Delete saved portfolio
POST /portfolios/compare # Compare multiple portfolios# Backend tests (if available)
cd backend
python -m pytest
# Frontend linting
cd frontend/frontend
npm run lint# Build frontend
cd frontend/frontend
npm run build
# Frontend build output will be in frontend/frontend/dist/Create a .env file in the backend directory:
# JWT Configuration
SECRET_KEY=your-secret-key-here
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
# API Configuration
API_HOST=0.0.0.0
API_PORT=8000
# Data Configuration
DATA_UPDATE_INTERVAL=3600 # 1 hour- Update
backend/data/individual_assets/with new CSV files - Modify asset list in
backend/scripts/config.py - Re-run feature engineering:
python scripts/feature_engineering.py - Retrain ML models:
python scripts/enhanced_ml_training.py
- Extend
backend/scripts/enhanced_portfolio_optimizer.py - Add new strategy to
backend/api/endpoints.py - Update frontend UI in
frontend/src/components/OptimizationControls.jsx
- Colors: Edit
frontend/frontend/tailwind.config.js - Components: Modify
frontend/frontend/src/index.css - Layouts: Update individual component files
# Build and run with Docker Compose
docker-compose up -d- Backend: Deploy FastAPI with Gunicorn/Uvicorn on cloud platforms
- Frontend: Build and deploy static files to CDN/hosting service
- Database: Set up PostgreSQL for production data storage
- AWS: EC2 + RDS + S3 for comprehensive deployment
- Heroku: Easy deployment with buildpacks
- Vercel: Frontend hosting with serverless backend
- DigitalOcean: App Platform for full-stack deployment
- Processing Speed: < 2 seconds for standard optimization
- Accuracy: 2.69 average Sharpe ratio across strategies
- Scalability: Handles 45+ assets with 2,500+ data points
- Success Rate: 99.9% optimization convergence
- Memory: 4GB RAM minimum (8GB recommended)
- Storage: 2GB for data and models
- CPU: Multi-core processor for ML computations
- Network: Stable internet for real-time data
We welcome contributions! Please follow these steps:
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Make your changes with proper testing
- Commit:
git commit -m 'Add amazing feature' - Push:
git push origin feature/amazing-feature - Open a Pull Request
- Follow PEP 8 for Python code
- Use ESLint configuration for JavaScript/React
- Add tests for new features
- Update documentation for API changes
- Ensure responsive design for UI changes
This project is licensed under the MIT License - see the LICENSE file for details.
- Live Demo: portfoliomax.demo.com
- API Documentation: localhost:8000/docs (when running locally)
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Modern Portfolio Theory: Harry Markowitz
- Financial Data: Yahoo Finance API
- ML Libraries: scikit-learn community
- UI Inspiration: Modern fintech applications
- Icons: Lucide React icon library
Built with β€οΈ for smarter investing
PortfolioMax - Where AI meets portfolio optimization