A sophisticated AI financial advisor system that mimics Warren Buffett's investment philosophy and decision-making process. Built with Flask backend and React frontend, featuring RAG (Retrieval-Augmented Generation), financial analysis tools, and belief tracking.
- Chat Interface: Interactive conversation with AI Warren Buffett
- Financial Tools: DCF calculator, P/E analyzer, margin of safety calculator, Buffett score
- RAG System: Retrieval from Buffett's shareholder letters (1977-2021)
- Belief Tracking: Temporal belief system for market context
- Chain-of-Thought: Step-by-step reasoning display
- Portfolio Analysis: Multi-stock evaluation using Buffett methodology
- Backend: Flask with SQLAlchemy, OpenAI GPT-4 integration
- Frontend: React with Tailwind CSS and shadcn/ui components
- Database: SQLite for conversations, beliefs, and recommendations
- AI Integration: OpenAI API with custom prompting and tool calling
- Deployment: Render-ready with Docker support
- Python 3.11+
- OpenAI API key
- Node.js 18+ (for development)
- Clone the repository
- Set environment variable:
export OPENAI_API_KEY="your-openai-api-key"
-
Install Python dependencies:
pip install -r requirements.txt
-
Run the Flask application:
python src/main.py
-
Access the application at
http://localhost:5000
- Fork this repository to your GitHub account
- Connect your GitHub account to Render
- Create a new Web Service on Render
- Select this repository
- Configure environment variables:
OPENAI_API_KEY: Your OpenAI API keyFLASK_ENV: production
- Deploy
- Download the ZIP file
- Upload to Render as a new Web Service
- Set build command:
pip install -r requirements.txt - Set start command:
python src/main.py - Configure environment variables as above
buffett-agent/
├── src/
│ ├── models/
│ │ └── conversation.py # Database models
│ ├── routes/
│ │ └── buffett_routes.py # API endpoints
│ ├── static/ # Built React frontend
│ ├── database/
│ │ └── app.db # SQLite database
│ ├── buffett_agent.py # Main AI agent
│ ├── financial_tools.py # Financial calculations
│ ├── rag_system.py # Retrieval system
│ ├── belief_system.py # Belief tracking
│ └── main.py # Flask application
├── requirements.txt # Python dependencies
├── render.yaml # Render configuration
└── README.md # This file
POST /api/chat- Send message to Buffett agentGET /api/conversation/{session_id}- Get conversation history
POST /api/tools/dcf- Calculate DCF valuationPOST /api/tools/pe- Analyze P/E ratiosPOST /api/tools/margin- Calculate margin of safetyPOST /api/tools/buffett-score- Calculate Buffett score
GET /api/beliefs- Get current beliefsPOST /api/beliefs/update- Update beliefs from news
POST /api/portfolio/analyze- Analyze portfolio
Ask questions like:
- "Should I invest in Apple at current prices?"
- "How do you calculate intrinsic value?"
- "What's your view on the current market?"
Use the tools tab to:
- Calculate DCF for specific cash flows
- Analyze P/E ratios vs industry averages
- Determine margin of safety for investments
- Get overall Buffett score for companies
Monitor how market beliefs influence decisions:
- Fed policy changes
- Inflation trends
- Market sentiment shifts
OPENAI_API_KEY: Required for AI functionalityFLASK_ENV: Set to 'production' for deploymentPORT: Port number (default: 5000)
- Modify
src/rag_system.pyto add more Buffett content - Update
src/financial_tools.pyfor additional calculations - Extend
src/belief_system.pyfor more market factors
- Uses OpenAI GPT-4 with custom system prompts
- Implements Chain-of-Thought reasoning
- RAG system with semantic search
- Tool calling for financial calculations
- Conversations: User messages and agent responses
- Beliefs: Temporal belief states with confidence scores
- Portfolio: Investment recommendations and analysis
- Input validation and sanitization
- Rate limiting considerations
- API key protection
- CORS configuration for frontend
- OpenAI API Key: Ensure valid API key is set
- Database: SQLite file permissions
- CORS: Frontend-backend communication
- Dependencies: Check Python version compatibility
Check application logs for detailed error information:
python src/main.pyThis section documents the major improvements, refactoring, and bug fixes made to the project, with a focus on clarity, robustness, and maintainability. Each file/module is described in detail, highlighting the changes compared to the initial version.
- Refactored agent orchestration:
TheBuffettAgentclass now acts as the central orchestrator, coordinating between the RAG system, financial tools, and the belief system. - Ticker extraction with LLM:
IntegratedLangChainTools.parse_tickers_with_langchainfor robust ticker extraction from user queries, ensuring only valid tickers are processed. - Dynamic news-driven belief updates:
Added logic to fetch and process news for extracted tickers, updating the belief system automatically, evaluated by LLMs, and generated the key, summary, and confidence. - Cleaner data flow:
Ensured that all financial tool inputs are dynamically fetched and validated, reducing reliance on hardcoded or sample data.
- Belief system modularization:
TheBeliefTrackerclass now manages beliefs, confidence levels, and causal relationships in a more modular way. - LLM integration for belief updates:
Refactored to use a pluggable LLM interface (LangChainOpenAI), allowing for flexible and up-to-date language model usage. - Batch news processing:
Improved theupdate_beliefs_from_newsmethod to handle batch news updates, with robust parsing and error handling.
- Simplified DCF calculation:
Replaced the original multi-period DCF with a Gordon Growth Model (simple_gordon_dcf), using only one forward FCF and the formula FCF1/(r-g). - Per-share intrinsic value:
Updated margin of safety calculations to use per-share intrinsic value (DCF divided by shares outstanding).
- Robust financial data acquisition:
TheMultiDataAgentclass now fetches data from multiple sources (yfinance, finnhub, simfin, Alpha Vantage) with improved error handling. - PE analysis improvements:
Added methods to fetch historical PE ranges, industry average PE, and aggregate all necessary data for PE analysis. - Margin of safety automation:
Automated the process of fetching current price, FCF, and shares outstanding for margin of safety calculations.
- Centralized LLM parsing utilities:
Created a new module to house all LLM-based parsing functions, such as ticker extraction and news-to-belief conversion. - Modern LangChain usage:
Updated to usellm.invoke()instead of deprecated call patterns, ensuring compatibility with the latest LangChain versions. - Robust output parsing:
Implemented fallback logic for JSON extraction and normalization, improving reliability when parsing LLM outputs.
- Class-based data templates:
Refactored from static methods to an instantiableDataTemplateclass, supporting dynamic data population and validation. - API alignment:
Ensured that all data structures align with API requirements for seamless integration.
- Flask app configuration:
Enhanced development experience by enabling debug mode for real-time error tracking and hot reloading
- Modernized LangChain usage:
Removed deprecated patterns and ensured all LangChain calls are up-to-date. - Ticker validation:
Added a utility to validate tickers using yfinance, filtering out invalid or non-tradable symbols. - Prompt engineering:
Improved prompts for LLM-based extraction tasks, clarifying output formats and increasing reliability. - Error handling:
Enhanced error handling and logging throughout the codebase, especially for external API calls and LLM integration. - Documentation:
Added or improved code comments (in both English and Chinese) for better maintainability and onboarding.
- Use this summary to quickly understand the evolution of the codebase and the rationale behind major changes.
- Refer to the detailed comments in each file for implementation specifics and usage examples.
- For further questions or contributions, see the Contributing Guidelines and API Documentation.