Abid Ali Awan commited on
Commit
d9e6f5f
Β·
1 Parent(s): 869dd38

Enhance financial agent capabilities: Integrate OpenAI function calling for improved extraction of stock symbols, budget data, and portfolio information from natural language inputs. Update example queries in app.py and README.md to reflect new features and support for additional stocks.

Browse files
Files changed (3) hide show
  1. README.md +59 -17
  2. agents/financial_agent.py +141 -21
  3. app.py +10 -3
README.md CHANGED
@@ -19,7 +19,7 @@ short_description: Financial analysis, investments, budget planning, and more.
19
 
20
  # AI Financial Advisory Agent
21
 
22
- An intelligent financial advisory agent powered by OpenAI's GPT-4.1 and specialized financial tools. This agent provides comprehensive financial analysis, investment recommendations, budget planning, and market insights through an intuitive web interface.
23
 
24
  **Watch the demo video:** [Financial Advisory Agent Demo (Hugging Face Hackathon)](https://youtu.be/vGOSAXyrQgM)
25
 
@@ -29,16 +29,18 @@ An intelligent financial advisory agent powered by OpenAI's GPT-4.1 and speciali
29
  ## πŸš€ Features
30
 
31
  ### Core Financial Tools
32
- - **πŸ“Š Investment Analyzer**: Real-time stock analysis with technical indicators, risk assessment, and investment recommendations
33
- - **πŸ’° Budget Planner**: Personalized budget creation using the 50/30/20 rule with optimization suggestions
34
- - **πŸ“ˆ Portfolio Analyzer**: Portfolio diversification analysis and performance optimization
35
- - **πŸ“° Market Trends Analyzer**: Real-time market news, sector analysis, and economic insights
36
 
37
  ### Advanced Features
 
38
  - **🎯 Smart Response Type Detection**: Automatically detects if users want short summaries or detailed reports
39
  - **⚑ Real-time LLM Streaming**: Live token-by-token response generation from OpenAI API
40
  - **πŸ“‹ Interactive Tool Results**: Collapsible sections for clean data presentation
41
  - **πŸ” Comprehensive Data Analysis**: Enhanced insights for all financial data
 
42
 
43
  ## πŸ› οΈ Installation
44
 
@@ -83,37 +85,48 @@ The system automatically detects your preference:
83
 
84
  - **Frontend**: Gradio web interface with real-time streaming
85
  - **Backend**: LangChain agents with OpenAI GPT-4.1
 
86
  - **Data Sources**:
87
- - Yahoo Finance API for stock data
88
  - Tavily Search API for market news
89
  - Real-time financial calculations
90
  - **Streaming**: Direct LLM token streaming from OpenAI API
91
- - **Tools**: Specialized financial analysis functions
92
 
93
  ## πŸ“Š Tool Capabilities
94
 
95
- ### Investment Analyzer
 
 
 
96
  - Real-time stock prices and historical data
97
  - Technical indicators (RSI, MACD, Bollinger Bands, Moving Averages)
98
  - Risk assessment (volatility, VaR, beta analysis)
99
  - Fundamental analysis (P/E, P/B ratios, dividend yield)
100
  - Buy/Hold/Sell recommendations with confidence scores
101
 
102
- ### Budget Planner
 
 
103
  - 50/30/20 rule implementation
104
  - Emergency fund calculations
105
  - Debt-to-income ratio analysis
106
  - Savings optimization recommendations
107
  - Expense category warnings
108
 
109
- ### Market Trends Analyzer
 
 
110
  - Real-time market news via Tavily Search
111
  - Major index tracking (S&P 500, NASDAQ)
112
  - Market sentiment analysis
113
  - Key theme extraction
114
  - Economic trend identification
115
 
116
- ### Portfolio Analyzer
 
 
 
117
  - Diversification scoring
118
  - Sector allocation analysis
119
  - Concentration risk assessment
@@ -123,6 +136,17 @@ The system automatically detects your preference:
123
 
124
  ## πŸš€ Recent Updates
125
 
 
 
 
 
 
 
 
 
 
 
 
126
  - βœ… **Smart Response Detection**: Automatically detects if users want short or detailed responses
127
  - βœ… **Real LLM Streaming**: Genuine token-by-token streaming from OpenAI API
128
  - βœ… **Improved Data Analysis**: Comprehensive insights
@@ -134,12 +158,30 @@ The system automatically detects your preference:
134
  - **OpenAI API Key**: For language model
135
  - **Tavily API Key**: For real-time market news and trends
136
 
137
- ## Issues to Resolve
138
- The problem is in the current flow:
139
- 1. Agent executor runs all tools
140
- 2. We collect ALL results
141
- 3. Then display everything at once
142
- 4. Then stream the final response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
 
144
  ## 🀝 Contributing
145
 
 
19
 
20
  # AI Financial Advisory Agent
21
 
22
+ An intelligent financial advisory agent powered by OpenAI's GPT-4.1 and specialized financial tools. This agent provides comprehensive financial analysis, investment recommendations, budget planning, and market insights through an intuitive web interface with **advanced natural language processing**.
23
 
24
  **Watch the demo video:** [Financial Advisory Agent Demo (Hugging Face Hackathon)](https://youtu.be/vGOSAXyrQgM)
25
 
 
29
  ## πŸš€ Features
30
 
31
  ### Core Financial Tools
32
+ - **πŸ“Š Investment Analyzer**: Analyze ANY stock using natural language - "Tell me about NVIDIA" or "How is Tesla doing?"
33
+ - **πŸ’° Budget Planner**: Create budgets from conversational input - "I make 6k monthly, rent is 1800, food 600"
34
+ - **πŸ“ˆ Portfolio Analyzer**: Analyze portfolios from natural descriptions - "My portfolio: Apple 100 shares, Google 50 shares"
35
+ - **πŸ“° Market Trends Analyzer**: Get optimized market research from simple queries - "What's happening in tech?"
36
 
37
  ### Advanced Features
38
+ - **🧠 OpenAI Function Calling**: All tools use intelligent input extraction from natural language
39
  - **🎯 Smart Response Type Detection**: Automatically detects if users want short summaries or detailed reports
40
  - **⚑ Real-time LLM Streaming**: Live token-by-token response generation from OpenAI API
41
  - **πŸ“‹ Interactive Tool Results**: Collapsible sections for clean data presentation
42
  - **πŸ” Comprehensive Data Analysis**: Enhanced insights for all financial data
43
+ - **🌐 Universal Stock Support**: Supports analysis of ANY publicly traded stock, not just predefined ones
44
 
45
  ## πŸ› οΈ Installation
46
 
 
85
 
86
  - **Frontend**: Gradio web interface with real-time streaming
87
  - **Backend**: LangChain agents with OpenAI GPT-4.1
88
+ - **AI Integration**: OpenAI function calling for intelligent input processing across all tools
89
  - **Data Sources**:
90
+ - Yahoo Finance API for stock data (supports ALL publicly traded stocks)
91
  - Tavily Search API for market news
92
  - Real-time financial calculations
93
  - **Streaming**: Direct LLM token streaming from OpenAI API
94
+ - **Tools**: Specialized financial analysis functions with natural language processing
95
 
96
  ## πŸ“Š Tool Capabilities
97
 
98
+ ### Investment Analyzer 🧠
99
+ - **Natural Language Input**: "Tell me about NVIDIA", "How is Tesla doing?", "Analyze AMZN"
100
+ - **Universal Stock Support**: Works with ANY publicly traded stock symbol
101
+ - **OpenAI-Powered Extraction**: Intelligently extracts stock symbols from company names
102
  - Real-time stock prices and historical data
103
  - Technical indicators (RSI, MACD, Bollinger Bands, Moving Averages)
104
  - Risk assessment (volatility, VaR, beta analysis)
105
  - Fundamental analysis (P/E, P/B ratios, dividend yield)
106
  - Buy/Hold/Sell recommendations with confidence scores
107
 
108
+ ### Budget Planner 🧠
109
+ - **Conversational Input**: "I make 6k monthly, rent 1800, food 600", "Help budget my 4500 salary"
110
+ - **OpenAI Data Extraction**: Automatically parses income and expenses from natural language
111
  - 50/30/20 rule implementation
112
  - Emergency fund calculations
113
  - Debt-to-income ratio analysis
114
  - Savings optimization recommendations
115
  - Expense category warnings
116
 
117
+ ### Market Trends Analyzer 🧠
118
+ - **Query Optimization**: Converts "What's happening in tech?" to optimized search queries
119
+ - **OpenAI-Enhanced Search**: Automatically improves search terms for better results
120
  - Real-time market news via Tavily Search
121
  - Major index tracking (S&P 500, NASDAQ)
122
  - Market sentiment analysis
123
  - Key theme extraction
124
  - Economic trend identification
125
 
126
+ ### Portfolio Analyzer 🧠
127
+ - **Natural Portfolio Input**: "My portfolio: Apple 100 shares, Google 50 shares"
128
+ - **Smart Format Detection**: Handles both share counts and percentages automatically
129
+ - **OpenAI JSON Conversion**: Converts natural descriptions to structured data
130
  - Diversification scoring
131
  - Sector allocation analysis
132
  - Concentration risk assessment
 
136
 
137
  ## πŸš€ Recent Updates
138
 
139
+ ### Latest (v2.0) - OpenAI Function Calling Integration 🧠
140
+ - βœ… **Universal Stock Support**: Removed hardcoded stock limitations - now supports ANY publicly traded stock
141
+ - βœ… **OpenAI-Powered Input Extraction**: All tools now use OpenAI function calling for intelligent data extraction
142
+ - βœ… **Natural Language Processing**:
143
+ - Investment: "Tell me about NVIDIA" β†’ Automatically extracts "NVDA"
144
+ - Budget: "I make 6k monthly, rent 1800" β†’ Extracts structured JSON
145
+ - Portfolio: "Apple 100 shares, Google 50 shares" β†’ Converts to holdings format
146
+ - Market: "What's happening in tech?" β†’ Optimizes to targeted search query
147
+ - βœ… **Enhanced Example Queries**: Updated with NVIDIA and natural language examples
148
+
149
+ ### Previous Updates
150
  - βœ… **Smart Response Detection**: Automatically detects if users want short or detailed responses
151
  - βœ… **Real LLM Streaming**: Genuine token-by-token streaming from OpenAI API
152
  - βœ… **Improved Data Analysis**: Comprehensive insights
 
158
  - **OpenAI API Key**: For language model
159
  - **Tavily API Key**: For real-time market news and trends
160
 
161
+ ## πŸ’‘ Example Natural Language Queries
162
+
163
+ ### Investment Analysis
164
+ - "Tell me about NVIDIA stocks"
165
+ - "How is Tesla performing?"
166
+ - "Should I invest in Apple?"
167
+ - "Analyze AMZN for me"
168
+ - "What's the latest on Microsoft stock?"
169
+
170
+ ### Budget Planning
171
+ - "I make $6000 monthly, rent is $1800, food $600, help me budget"
172
+ - "Help budget my $4500 salary, utilities cost $150"
173
+ - "Create a budget: income 5k, rent 1500, groceries 400"
174
+
175
+ ### Portfolio Analysis
176
+ - "My portfolio: Apple 100 shares, Google 50 shares, Microsoft 25 shares"
177
+ - "I have 40% AAPL, 30% MSFT, 30% TSLA"
178
+ - "Analyze portfolio with Tesla 200 shares and Amazon 25%"
179
+
180
+ ### Market Trends
181
+ - "What's happening in tech stocks?"
182
+ - "Tell me about today's market"
183
+ - "How is the crypto market doing?"
184
+ - "What are the latest NVIDIA trends?"
185
 
186
  ## 🀝 Contributing
187
 
agents/financial_agent.py CHANGED
@@ -76,46 +76,166 @@ When a user asks a question:
76
  def _prepare_tool_input(self, message: str, tool_name: str) -> str:
77
  """Prepare input for specific tools based on the message"""
78
  if tool_name == "investment_analyzer":
79
- # Extract stock symbols
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  symbols = re.findall(r"\b[A-Z]{2,5}\b", message)
81
- if symbols:
82
- return symbols[0]
83
- return "AAPL" # Default
84
 
85
  elif tool_name == "budget_planner":
86
- # Try to extract income and expenses from message
87
- income_match = re.search(
88
- r"\$?(\d+(?:,\d{3})*(?:\.\d{2})?)\s*(?:monthly\s*)?income",
89
- message,
90
- re.I,
91
- )
92
- income = (
93
- float(income_match.group(1).replace(",", "")) if income_match else 5000
94
- )
95
-
96
- # Extract expenses
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  expenses = {}
98
  expense_patterns = [
99
  (r"rent:?\s*\$?(\d+(?:,\d{3})*(?:\.\d{2})?)", "rent"),
100
  (r"food:?\s*\$?(\d+(?:,\d{3})*(?:\.\d{2})?)", "food"),
101
  (r"utilities:?\s*\$?(\d+(?:,\d{3})*(?:\.\d{2})?)", "utilities"),
102
- (
103
- r"transportation:?\s*\$?(\d+(?:,\d{3})*(?:\.\d{2})?)",
104
- "transportation",
105
- ),
106
  ]
107
-
108
  for pattern, category in expense_patterns:
109
  match = re.search(pattern, message, re.I)
110
  if match:
111
  expenses[category] = float(match.group(1).replace(",", ""))
112
-
113
  return json.dumps({"income": income, "expenses": expenses})
114
 
115
  elif tool_name == "portfolio_analyzer":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  return message
117
 
118
  elif tool_name == "market_trends":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  return message
120
 
121
  return message
 
76
  def _prepare_tool_input(self, message: str, tool_name: str) -> str:
77
  """Prepare input for specific tools based on the message"""
78
  if tool_name == "investment_analyzer":
79
+ # Use OpenAI to extract stock symbol from natural language
80
+ extraction_prompt = f"""Extract the stock symbol from this message: "{message}"
81
+
82
+ If the user mentions a company name, return the corresponding stock ticker symbol.
83
+ If they mention a ticker symbol directly, return that symbol.
84
+ If no stock or company is mentioned, return "UNKNOWN".
85
+
86
+ Examples:
87
+ - "Tell me about NVIDIA" -> "NVDA"
88
+ - "Analyze AAPL stock" -> "AAPL"
89
+ - "How is Tesla doing?" -> "TSLA"
90
+ - "What about Microsoft stock?" -> "MSFT"
91
+
92
+ Return only the stock symbol, nothing else."""
93
+
94
+ try:
95
+ response = self.llm.invoke([
96
+ SystemMessage(content="You are a stock symbol extraction assistant. Return only the ticker symbol."),
97
+ HumanMessage(content=extraction_prompt)
98
+ ])
99
+
100
+ extracted_symbol = response.content.strip().upper()
101
+ if extracted_symbol and extracted_symbol != "UNKNOWN":
102
+ return extracted_symbol
103
+
104
+ except Exception:
105
+ pass
106
+
107
+ # Fallback to regex if LLM fails
108
  symbols = re.findall(r"\b[A-Z]{2,5}\b", message)
109
+ return symbols[0] if symbols else ""
 
 
110
 
111
  elif tool_name == "budget_planner":
112
+ # Use OpenAI to extract budget information from natural language
113
+ extraction_prompt = f"""Extract budget information from this message: "{message}"
114
+
115
+ Extract:
116
+ 1. Monthly income (if mentioned)
117
+ 2. Expenses by category (rent, food, utilities, transportation, etc.)
118
+
119
+ Return as JSON format:
120
+ {{"income": 5000, "expenses": {{"rent": 1500, "food": 500, "utilities": 200}}}}
121
+
122
+ If income is not mentioned, use 5000 as default.
123
+ If no expenses are mentioned, return empty expenses object.
124
+
125
+ Examples:
126
+ - "I make $6000 monthly, rent is $1800, food $600" -> {{"income": 6000, "expenses": {{"rent": 1800, "food": 600}}}}
127
+ - "Help with budget, income 4500, utilities 150" -> {{"income": 4500, "expenses": {{"utilities": 150}}}}
128
+
129
+ Return only valid JSON, nothing else."""
130
+
131
+ try:
132
+ response = self.llm.invoke([
133
+ SystemMessage(content="You are a budget data extraction assistant. Return only valid JSON."),
134
+ HumanMessage(content=extraction_prompt)
135
+ ])
136
+
137
+ # Try to parse the JSON response
138
+ extracted_data = response.content.strip()
139
+ # Remove any markdown formatting
140
+ if extracted_data.startswith("```"):
141
+ extracted_data = extracted_data.split("\n")[1:-1]
142
+ extracted_data = "\n".join(extracted_data)
143
+
144
+ # Validate JSON
145
+ json.loads(extracted_data)
146
+ return extracted_data
147
+
148
+ except Exception:
149
+ pass
150
+
151
+ # Fallback to regex extraction
152
+ income_match = re.search(r"\$?(\d+(?:,\d{3})*(?:\.\d{2})?)\s*(?:monthly\s*)?income", message, re.I)
153
+ income = float(income_match.group(1).replace(",", "")) if income_match else 5000
154
+
155
  expenses = {}
156
  expense_patterns = [
157
  (r"rent:?\s*\$?(\d+(?:,\d{3})*(?:\.\d{2})?)", "rent"),
158
  (r"food:?\s*\$?(\d+(?:,\d{3})*(?:\.\d{2})?)", "food"),
159
  (r"utilities:?\s*\$?(\d+(?:,\d{3})*(?:\.\d{2})?)", "utilities"),
160
+ (r"transportation:?\s*\$?(\d+(?:,\d{3})*(?:\.\d{2})?)", "transportation"),
 
 
 
161
  ]
162
+
163
  for pattern, category in expense_patterns:
164
  match = re.search(pattern, message, re.I)
165
  if match:
166
  expenses[category] = float(match.group(1).replace(",", ""))
167
+
168
  return json.dumps({"income": income, "expenses": expenses})
169
 
170
  elif tool_name == "portfolio_analyzer":
171
+ # Use OpenAI to extract portfolio information from natural language
172
+ extraction_prompt = f"""Extract portfolio holdings from this message: "{message}"
173
+
174
+ Convert the portfolio information to JSON format with holdings array.
175
+ Each holding should have symbol and either shares or percentage.
176
+
177
+ Return format:
178
+ {{"holdings": [{{"symbol": "AAPL", "shares": 100}}, {{"symbol": "GOOGL", "percentage": 30}}]}}
179
+
180
+ Examples:
181
+ - "My portfolio: AAPL 100 shares, GOOGL 50 shares" -> {{"holdings": [{{"symbol": "AAPL", "shares": 100}}, {{"symbol": "GOOGL", "shares": 50}}]}}
182
+ - "I have 40% AAPL, 30% MSFT, 30% TSLA" -> {{"holdings": [{{"symbol": "AAPL", "percentage": 40}}, {{"symbol": "MSFT", "percentage": 30}}, {{"symbol": "TSLA", "percentage": 30}}]}}
183
+ - "Portfolio with Apple 200 shares and Microsoft 25%" -> {{"holdings": [{{"symbol": "AAPL", "shares": 200}}, {{"symbol": "MSFT", "percentage": 25}}]}}
184
+
185
+ If no clear portfolio data is found, return: {{"holdings": []}}
186
+
187
+ Return only valid JSON, nothing else."""
188
+
189
+ try:
190
+ response = self.llm.invoke([
191
+ SystemMessage(content="You are a portfolio data extraction assistant. Return only valid JSON with holdings array."),
192
+ HumanMessage(content=extraction_prompt)
193
+ ])
194
+
195
+ # Try to parse the JSON response
196
+ extracted_data = response.content.strip()
197
+ # Remove any markdown formatting
198
+ if extracted_data.startswith("```"):
199
+ extracted_data = extracted_data.split("\n")[1:-1]
200
+ extracted_data = "\n".join(extracted_data)
201
+
202
+ # Validate JSON
203
+ json.loads(extracted_data)
204
+ return extracted_data
205
+
206
+ except Exception:
207
+ pass
208
+
209
+ # Fallback to returning the original message
210
  return message
211
 
212
  elif tool_name == "market_trends":
213
+ # Use OpenAI to extract and refine market research query
214
+ extraction_prompt = f"""Convert this user message into an optimized market research query: "{message}"
215
+
216
+ Create a focused search query that will get the best market trends and financial news results.
217
+
218
+ Examples:
219
+ - "What's happening in tech stocks?" -> "technology stocks market trends latest news 2025"
220
+ - "Tell me about the market today" -> "stock market trends today financial news latest"
221
+ - "How is the crypto market?" -> "cryptocurrency market trends bitcoin ethereum latest news"
222
+ - "What about NVIDIA trends?" -> "NVIDIA NVDA stock market trends analysis latest news"
223
+
224
+ Return only the optimized search query, nothing else."""
225
+
226
+ try:
227
+ response = self.llm.invoke([
228
+ SystemMessage(content="You are a search query optimization assistant. Return only the optimized search query."),
229
+ HumanMessage(content=extraction_prompt)
230
+ ])
231
+
232
+ optimized_query = response.content.strip()
233
+ return optimized_query if optimized_query else message
234
+
235
+ except Exception:
236
+ pass
237
+
238
+ # Fallback to returning the original message
239
  return message
240
 
241
  return message
app.py CHANGED
@@ -477,10 +477,16 @@ def determine_intended_tool(message):
477
  "sell",
478
  "analyze",
479
  "AAPL",
480
- "GOOGL",
481
  "TSLA",
 
 
 
 
 
482
  "share",
483
  "equity",
 
484
  ],
485
  "portfolio_analyzer": [
486
  "portfolio",
@@ -821,8 +827,9 @@ with gr.Blocks(theme=gr.themes.Base(), title="Financial Advisory Agent") as demo
821
 
822
  # Example queries
823
  example_queries = [
824
- "Analyze AAPL stock and tell me if it's a good investment",
825
- "Help me create a budget with $5000 monthly income and expenses: rent $1500, food $500, utilities $200",
 
826
  "What are the latest market trends in tech stocks?",
827
  "Analyze my portfolio: {'holdings': [{'symbol': 'AAPL', 'shares': 100}, {'symbol': 'GOOGL', 'shares': 50}]}",
828
  ]
 
477
  "sell",
478
  "analyze",
479
  "AAPL",
480
+ "GOOGL",
481
  "TSLA",
482
+ "NVDA",
483
+ "NVIDIA",
484
+ "MSFT",
485
+ "AMZN",
486
+ "META",
487
  "share",
488
  "equity",
489
+ "ticker",
490
  ],
491
  "portfolio_analyzer": [
492
  "portfolio",
 
827
 
828
  # Example queries
829
  example_queries = [
830
+ "Analyze NVDA stock and tell me if it's a good investment",
831
+ "Tell me more about NVIDIA stocks",
832
+ "Help me create a budget with $5000 monthly income and expenses: rent $1500, food $500, utilities $200",
833
  "What are the latest market trends in tech stocks?",
834
  "Analyze my portfolio: {'holdings': [{'symbol': 'AAPL', 'shares': 100}, {'symbol': 'GOOGL', 'shares': 50}]}",
835
  ]