System Architecture
This document provides visual diagrams explaining how the QuantBot financial agent system works.
1. High-Level System Overview
graph TB
subgraph "Frontend (React + TypeScript)"
UI[User Interface]
Chat[Chat Component]
Context[Chat Context]
end
subgraph "Backend (FastAPI + Python)"
API[API Endpoints]
FA[Financial Agent]
MCP[MCP Servers]
DS[Data Sources]
end
subgraph "External Services"
Gemini[Gemini AI]
YF[yfinance/Yahoo]
FINN[Finnhub API]
NEWS[NewsAPI]
DB[(PostgreSQL)]
NEO[(Neo4j)]
end
UI --> Chat
Chat --> Context
Context -->|HTTP POST| API
API --> FA
FA --> MCP
MCP --> DS
DS --> YF
DS --> FINN
DS --> NEWS
FA --> Gemini
API --> DB
style UI fill:#61dafb
style Chat fill:#61dafb
style Context fill:#61dafb
style API fill:#4ade80
style FA fill:#4ade80
style MCP fill:#4ade80
style Gemini fill:#fbbf24
style YF fill:#fbbf24
style FINN fill:#fbbf24
style NEWS fill:#fbbf24
2. Request Flow Diagram
sequenceDiagram
participant User
participant Frontend
participant Backend
participant FinancialAgent
participant Gemini
participant DataSources
User->>Frontend: Types "What's Apple stock price?"
Frontend->>Backend: POST /api/chat/
Backend->>FinancialAgent: process_question()
Note over FinancialAgent: Load conversation history
FinancialAgent->>Gemini: Create execution plan
Gemini-->>FinancialAgent: JSON plan with tools to use
Note over FinancialAgent: Execute plan steps
FinancialAgent->>DataSources: get_stock_price("AAPL")
alt Yahoo Finance works
DataSources->>DataSources: Try Yahoo Finance
DataSources-->>FinancialAgent: Stock data
else Yahoo Finance fails
DataSources->>DataSources: Try Finnhub fallback
DataSources-->>FinancialAgent: Stock data
else Both fail
DataSources-->>FinancialAgent: Error message
end
FinancialAgent->>Gemini: Analyze gathered data
Gemini-->>FinancialAgent: Financial analysis
FinancialAgent-->>Backend: Response with analysis + tools
Backend-->>Frontend: ChatResponse
Frontend-->>User: Display message + stock card
3. Financial Agent Architecture
graph TD
subgraph "Financial Agent System"
FA[FinancialAgentSystem]
CS[ConversationState]
YFS[YFinanceMCPServer]
WSS[WebSearchMCPServer]
FA --> CS
FA --> YFS
FA --> WSS
subgraph "YFinance MCP Server"
SP[get_stock_price]
HD[get_historical_data]
PA[get_portfolio_analysis]
CI[get_company_info]
YFS --> SP
YFS --> HD
YFS --> PA
YFS --> CI
end
subgraph "Web Search MCP Server"
WS[search]
GN[get_news]
WSS --> WS
WSS --> GN
end
end
style FA fill:#818cf8
style CS fill:#a78bfa
style YFS fill:#4ade80
style WSS fill:#4ade80
4. Data Source Integration
flowchart TD
Start[User query about markets]
Analyze{Analyze query type}
UseMarket[Yahoo Finance<br/>Stock prices & indices]
UseSentiment[Finnhub<br/>Social sentiment]
UseNews[NewsAPI<br/>Financial news]
Combine[Combine results]
Response[AI analysis & response]
Start --> Analyze
Analyze -->|Price query| UseMarket
Analyze -->|Sentiment query| UseSentiment
Analyze -->|News query| UseNews
Analyze -->|Complex query| UseMarket
Analyze -->|Complex query| UseSentiment
Analyze -->|Complex query| UseNews
UseMarket --> Combine
UseSentiment --> Combine
UseNews --> Combine
Combine --> Response
style Start fill:#fbbf24
style UseMarket fill:#4ade80
style UseSentiment fill:#4ade80
style UseNews fill:#4ade80
style Response fill:#818cf8
5. Multi-Agent Orchestration Process
stateDiagram-v2
[*] --> ReceiveQuestion
ReceiveQuestion --> AnalyzeContext
AnalyzeContext --> CreatePlan
CreatePlan --> DataGathering
state DataGathering {
[*] --> CheckTools
CheckTools --> CallYFinance: Need stock data
CheckTools --> CallWebSearch: Need news/search
CallYFinance --> StoreResults
CallWebSearch --> StoreResults
StoreResults --> CheckTools: More tools?
StoreResults --> [*]: Done
}
DataGathering --> AnalyzeData
AnalyzeData --> GenerateResponse
GenerateResponse --> FormatOutput
FormatOutput --> [*]
6. Frontend-Backend Integration
graph LR
subgraph "Frontend Components"
UC[UserInput Component]
CC[ChatContainer]
MC[Message Component]
SC[StockCard]
NC[NewsCard]
end
subgraph "API Layer"
POST[POST /api/chat/]
Response[ChatResponse]
end
subgraph "Data Flow"
Req[Request]
Res[Response]
end
UC -->|User types| Req
Req -->|message| POST
POST -->|Process| Response
Response -->|message object| Res
Res --> MC
MC -->|tools array| SC
MC -->|tools array| NC
style UC fill:#61dafb
style CC fill:#61dafb
style MC fill:#61dafb
style POST fill:#4ade80
7. Tool Result Processing
graph TD
subgraph "Raw Tool Results"
YFR[Yahoo Finance Result]
FINNR[Finnhub Result]
NEWSR[NewsAPI Result]
end
subgraph "Processing Layer"
TP[Tool Processor]
FM[Format Mapper]
end
subgraph "Frontend Tools"
ST[Stock Tool<br/>type: 'price']
NT[News Tool<br/>type: 'news']
PT[Portfolio Tool<br/>type: 'earnings']
end
YFR --> TP
AVR --> TP
MR --> TP
TP --> FM
FM -->|Stock data| ST
FM -->|News data| NT
FM -->|Portfolio data| PT
style YFR fill:#fbbf24
style AVR fill:#fbbf24
style MR fill:#fbbf24
style TP fill:#818cf8
style FM fill:#818cf8
style ST fill:#4ade80
style NT fill:#4ade80
style PT fill:#4ade80
8. Conversation Context Management
stateDiagram-v2
[*] --> Empty
Empty --> FirstMessage: User sends message
FirstMessage --> StoreUser: Add to history
StoreUser --> Processing: Agent processes
Processing --> StoreAssistant: Add response
StoreAssistant --> WaitingForUser
WaitingForUser --> StoreUser: New message
state "Context Window" as CW {
Recent1: Message -3
Recent2: Message -2
Recent3: Message -1
Current: Current Message
}
note right of CW: Only last 6 messages<br/>used for context
9. Error Handling Flow
flowchart TD
Request[API Request]
Validate{Valid Request?}
CheckGemini{Gemini Available?}
CheckOpenAI{OpenAI Available?}
UseMock[Use Mock Service]
Process[Process with AI]
Success[Return Response]
Error[Return Error Response]
Request --> Validate
Validate -->|No| Error
Validate -->|Yes| CheckGemini
CheckGemini -->|Yes| Process
CheckGemini -->|No| CheckOpenAI
CheckOpenAI -->|Yes| Process
CheckOpenAI -->|No| UseMock
UseMock --> Process
Process --> Success
Process -->|Exception| Error
style Success fill:#4ade80
style Error fill:#ef4444
Key Components Explained
1. Financial Agent System
- Central orchestrator that manages the entire analysis process
- Maintains conversation state for context-aware responses
- Coordinates between multiple MCP servers
2. MCP Servers
- Modular tool servers that encapsulate specific functionality
- YFinanceMCPServer: Stock market data and analysis
- WebSearchMCPServer: Web search and news gathering
3. Data Sources
- Primary Market Data: Yahoo Finance via yfinance library (real-time stock prices, market indices)
- Social Sentiment: Finnhub API (social sentiment analysis and alternative data)
- Financial News: NewsAPI (financial news aggregation and analysis)
- Memory Embeddings: OpenAI (semantic similarity for contextual memory)
- AI Models: Google Gemini 2.5 (agent reasoning and analysis)
4. Tool Processing
- Raw data from various sources is standardized
- Formatted to match frontend expectations
- Type-safe interfaces ensure compatibility
5. Conversation Management
- Maintains history for context
- Database persistence for authenticated users
- Limited context window for efficiency
Usage Flow
- User types a financial question in the chat
- Frontend sends POST request to
/api/chat/
- Backend checks for Gemini API key
- Financial Agent creates an execution plan
- Agent gathers data using appropriate tools
- Agent uses specialized tools: Market data (Yahoo Finance), Social sentiment (Finnhub), News analysis (NewsAPI)
- Gemini analyzes the gathered data
- Response is formatted with content, thinking steps, and tool results
- Frontend displays the message with interactive tool cards
- Conversation state is saved for context