A production-ready backend service that provides ChatGPT-like investment research capabilities using natural language processing, real-time market data, and AI-powered analysis.
- Conversational AI: Accept natural language investment queries (e.g., "How is Tesla doing this month?")
- Real-Time Market Data: Fetch current stock prices and historical trends using yfinance
- News Integration: Retrieve relevant financial news using NewsAPI
- Sentiment Analysis: Analyze news sentiment using TextBlob
- AI Summary Generation: Generate investor-friendly summaries using Hugging Face GPT-2
- Conversation History: Persist chat sessions in SQLite database
- RESTful API: FastAPI-based backend with auto-generated OpenAPI documentation
- Responsive Design: Works on desktop, tablet, and mobile
- Real-time Chat: Interactive conversation with AI
- Dashboard: Analytics and market insights
- Session History: Track and manage conversations
- Dark Mode: Toggle between light and dark themes
- Stock Data Display: Real-time prices and changes
- Sentiment Visualization: Charts and indicators
- Export Functionality: Download session data
- React 18 - Modern UI framework
- Vite - Fast build tool and dev server
- Tailwind CSS - Utility-first CSS framework
- Framer Motion - Smooth animations
- Lucide React - Beautiful icons
- Recharts - Data visualization
- Axios - HTTP client with interceptors
- Professional Design: Clean, modern interface
- Smooth Animations: Micro-interactions and transitions
- Color Scheme: Primary blue with neutral grays
- Typography: Inter font for readability
- Loading States: Skeleton screens and spinners
- Error Handling: User-friendly error messages
- Responsive Layout: Mobile-first design
- Python 3.12 or higher (fully compatible)
- Node.js 16+ and npm
- pip package manager
- NewsAPI key (get one at https://newsapi.org)
-
Navigate to project
cd investai -
Create and activate virtual environment
python -m venv venv # On Windows venv\\Scripts\\activate # On Unix/macOS source venv/bin/activate
-
Install Python dependencies
pip install -r requirements.txt
-
Set up environment variables
cp .env.example .env # Edit .env and add your NewsAPI key -
Start backend server
uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
-
Navigate to frontend directory
cd frontend -
Install Node.js dependencies
npm install
-
Start frontend development server
npm run dev
-
Start backend (Terminal 1):
cd investai source venv/Scripts/activate # Windows uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
-
Start frontend (Terminal 2):
cd investai/frontend npm run dev -
Access the application:
- Frontend: http://localhost:3000
- Backend API: http://localhost:8000
- API Documentation: http://localhost:8000/docs
-
Access the API
- API Documentation: http://localhost:8000/docs
- Health Check: http://localhost:8000/health/simple
- Root Endpoint: http://localhost:8000/
Endpoint: POST /query
Request:
{
"user_id": 1,
"query": "Analyze AAPL stock performance"
}Sample Response:
{
"response": "Apple Inc. (AAPL) is trading at $175.20, up 2.1% today. Over the past month, it gained 8.4%. Recent news shows positive sentiment around iPhone sales and AI initiatives. Overall news sentiment: Positive",
"sources": ["Yahoo Finance", "NewsAPI"],
"user_id": 1,
"timestamp": "2026-02-08T03:23:00.000Z"
}Endpoint: POST /chat/ (Enhanced version with more features)
Request:
{
"query": "How is Apple stock doing today?",
"session_id": "optional-session-id"
}Response Example:
{
"query": "How is Apple stock doing today?",
"detected_ticker": "AAPL",
"stock_data": {
"symbol": "AAPL",
"current_price": 175.43,
"change_percent": 1.25,
"volume": 52341234,
"market_cap": 2750000000000
},
"sentiment_result": {
"sentiment": "Positive",
"confidence": 0.75,
"polarity": 0.75
},
"ai_summary": "Apple (AAPL) is currently trading at $175.43, up 1.25% from the previous close. Recent news suggests positive sentiment around the company's latest product launches...",
"relevant_news": [
{
"title": "Apple Reports Strong Q4 Earnings",
"description": "Apple exceeded analyst expectations...",
"source": "TechCrunch",
"published_at": "2024-01-15T10:30:00Z",
"url": "https://..."
}
],
"timestamp": "2024-01-15T15:30:00Z",
"session_id": "generated-session-id"
}Get Chat History:
curl "http://localhost:8000/chat/sessions/{session_id}"Get All Sessions:
curl "http://localhost:8000/chat/sessions/"Delete Session:
curl -X DELETE "http://localhost:8000/chat/sessions/{session_id}"investai/
├── app/ # Backend FastAPI application
│ ├── main.py # FastAPI app entry point
│ ├── api/ # API endpoints
│ │ ├── chat.py # Enhanced chat endpoint
│ │ ├── query.py # Company-specified endpoint
│ │ └── health.py # Health checks
│ ├── core/ # Core configuration
│ │ ├── config.py # Settings management
│ │ └── logger.py # Logging setup
│ ├── services/ # Business logic services
│ │ ├── market_data.py # yfinance integration
│ │ ├── news_service.py # NewsAPI integration
│ │ ├── sentiment.py # TextBlob analysis
│ │ ├── ai_engine.py # GPT-2 generation
│ │ ├── ai_service.py # AI service wrapper
│ │ ├── data_service.py # Data service wrapper
│ │ └── analysis_service.py # Analysis service wrapper
│ ├── models/ # Database models
│ │ ├── chat.py # Chat sessions/messages
│ │ └── session.py # Session management
│ ├── schemas/ # Pydantic validation
│ │ ├── chat.py # Chat request/response models
│ │ └── query.py # Query request/response models
│ ├── db/ # Database setup
│ │ ├── base.py # SQLAlchemy configuration
│ │ └── session.py # Session management
│ └── utils/ # Utilities
│ └── ticker_parser.py # Ticker extraction
├── frontend/ # Modern React frontend
│ ├── src/
│ │ ├── components/ # React components
│ │ │ ├── ChatInterface.jsx
│ │ │ ├── Dashboard.jsx
│ │ │ ├── History.jsx
│ │ │ └── Header.jsx
│ │ ├── services/ # API services
│ │ │ └── api.js
│ │ ├── App.jsx # Main React app
│ │ ├── main.jsx # React entry point
│ │ └── index.css # Tailwind CSS
│ ├── package.json # Node.js dependencies
│ ├── vite.config.js # Vite configuration
│ ├── tailwind.config.js # Tailwind CSS config
│ └── index.html # HTML template
├── app.py # Simplified entry point
├── models.py # Consolidated models
├── schemas.py # Consolidated schemas
├── .env # Environment variables
├── .env.example # Environment template
├── requirements.txt # Python dependencies
├── README.md # This file
├── run.bat # Windows startup script
└── run.sh # Unix startup script
Create a .env file based on .env.example:
# Application Settings
APP_NAME=InvestAI
APP_VERSION=1.0.0
DEBUG=False
# Database Configuration
DATABASE_URL=sqlite:///./investai.db
# API Keys (Required for news functionality)
NEWSAPI_KEY=your_newsapi_key_here
# AI Model Settings
HUGGINGFACE_MODEL=gpt2
MAX_TOKENS=150
TEMPERATURE=0.7
# Server Configuration
API_HOST=0.0.0.0
API_PORT=8000- NewsAPI Key: Get a free key at https://newsapi.org
- Required for fetching financial news
- Free tier allows up to 1,000 requests per day
# Activate virtual environment
source venv/bin/activate # Unix/macOS
# or
venv\\Scripts\\activate # Windows
# Run with auto-reload
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000The application uses SQLite by default. The database file (investai.db) will be created automatically when you first run the application.
- New API endpoints: Add to
app/api/ - Business logic: Add to
app/services/ - Database models: Add to
app/models/ - Request/response schemas: Add to
app/schemas/
The project is structured to be containerizable. A future enhancement would include:
FROM python:3.10-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]The application can be deployed to:
- Heroku: Easy deployment with PostgreSQL
- AWS: Elastic Beanstalk or ECS
- Google Cloud: Cloud Run or App Engine
- Azure: App Service or Container Instances
cd frontend
npm run build
# Deploy dist/ folder to Netlify, Vercel, or GitHub Pages- Vercel: Connect both frontend and backend
- Netlify: Static frontend with serverless functions
- AWS Amplify: Full-stack hosting
- DigitalOcean: App Platform for full applications
# Production
DEBUG=False
API_HOST=0.0.0.0
API_PORT=8000
DATABASE_URL=postgresql://user:pass@host:port/dbname
NEWSAPI_KEY=production_api_key- User Authentication: JWT-based authentication system
- User Dashboard: Streamlit frontend for visualization
- Advanced LLMs: Support for Llama 3, Grok, xAI API
- Real-time WebSocket: Live stock price updates
- Portfolio Management: Track multiple stocks
- Advanced Analytics: Technical indicators and chart patterns
- Multi-language Support: Support for international markets
- ModuleNotFoundError: Ensure virtual environment is activated
- NewsAPI errors: Check your API key in
.env - Database errors: Ensure write permissions in the project directory
- Model loading errors: First run may take time to download GPT-2 model
Application logs are printed to console. Check for error messages during startup.
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
This project is for educational and demonstration purposes.
For issues and questions:
- Check the troubleshooting section
- Review the API documentation at
/docs - Check application logs for detailed error messages