File size: 7,468 Bytes
6ceb32c
 
5ad2796
6ceb32c
5ad2796
6ceb32c
 
 
 
 
 
 
 
5ad2796
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
---
title: Financial Advisory Agent
emoji: πŸ§‘β€πŸ’Ό
colorFrom: gray
colorTo: blue
sdk: gradio
sdk_version: 5.33.0
app_file: app.py
pinned: false
license: apache-2.0
short_description: Financial analysis, investments, budget planning, and more.
---


# AI Financial Advisory Agent

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.

## πŸš€ Features

### Core Financial Tools
- **πŸ“Š Investment Analyzer**: Real-time stock analysis with technical indicators, risk assessment, and investment recommendations
- **πŸ’° Budget Planner**: Personalized budget creation using the 50/30/20 rule with optimization suggestions
- **πŸ’³ Expense Tracker**: Advanced expense analysis with trends, predictions, and anomaly detection
- **πŸ“ˆ Portfolio Analyzer**: Portfolio diversification analysis and performance optimization
- **πŸ“° Market Trends Analyzer**: Real-time market news, sector analysis, and economic insights

### Advanced Features
- **🎯 Smart Response Type Detection**: Automatically detects if users want short summaries or detailed reports
- **⚑ Real-time LLM Streaming**: Live token-by-token response generation from OpenAI API
- **πŸ“‹ Interactive Tool Results**: Collapsible sections for clean data presentation
- **πŸ” Comprehensive Data Analysis**: Enhanced visualizations and insights for all financial data
- **⏱️ Real-time Status Updates**: Shows which APIs are being called and estimated completion times

## πŸ› οΈ Installation

1. **Clone the repository**
```bash
git clone https://github.com/yourusername/financial-advisory-agent.git
cd financial-advisory-agent
```

2. **Install dependencies**
```bash
pip install -r requirements.txt
```

3. **Set up environment variables**
Create a `.env` file or set environment variables:
```bash
export OPENAI_API_KEY="your-openai-api-key"
export TAVILY_API_KEY="your-tavily-api-key"
```

4. **Run the application**
```bash
python app.py
```

## πŸ’¬ Example Prompts

### Single Tool Invocation

#### Investment Analyzer
```
"Analyze AAPL stock and tell me if it's a good investment"
"Should I buy Tesla stock right now?"
"Give me a detailed analysis of Microsoft shares"
"Quick summary of NVDA stock performance"
```

#### Budget Planner
```
"Help me create a budget with $5000 monthly income and expenses: rent $1500, food $500, utilities $200"
"I make $75,000 annually, help me budget my expenses"
"Create a budget plan for someone earning $4000/month"
"Quick budget advice for $6000 monthly income"
```

#### Market Trends Analyzer
```
"What are the latest market trends in tech stocks?"
"Give me current market news and analysis"
"Detailed report on today's market movements"
"Quick market update for technology sector"
```

#### Portfolio Analyzer
```
"Analyze my portfolio: {'holdings': [{'symbol': 'AAPL', 'shares': 100}, {'symbol': 'GOOGL', 'shares': 50}]}"
"Check my diversification with holdings: AAPL 40%, MSFT 30%, TSLA 30%"
"Detailed portfolio analysis for my current investments"
```

#### Expense Tracker
```
"Track my expenses: [{'category': 'food', 'amount': 150}, {'category': 'gas', 'amount': 80}]"
"Analyze my spending patterns from last month"
"Help me categorize and analyze my expenses"
```

### Response Type Control

#### Short Responses (Under 200 words)
```
"Quick analysis of AAPL"
"Brief summary of market trends"
"Give me a short budget recommendation"
"Simple portfolio check"
"Fast expense analysis"
```

#### Detailed Responses (Comprehensive reports)
```
"Give me a detailed report on AAPL stock"
"Comprehensive market analysis for tech sector"
"Thorough budget breakdown with recommendations"
"In-depth portfolio diversification analysis"
"Complete expense tracking report with insights"
```

### Multi-Tool Queries
```
"Analyze AAPL stock and create a budget for investing $1000 monthly"
"What are the current market trends and how should I adjust my portfolio?"
"Help me budget $5000 income and recommend some good stocks to invest in"
"Track my expenses and suggest a better budget allocation"
```

### Advanced Queries
```
"I have $50K to invest. Analyze current market trends, suggest a diversified portfolio, and create a budget for monthly investments of $2000"
"Detailed analysis: Review AAPL, MSFT, and GOOGL stocks, then help me rebalance my portfolio"
"Comprehensive financial review: Budget analysis for $8000 monthly income, expense tracking, and investment recommendations"
```

## 🎯 Response Types

The system automatically detects your preference:

### Short Response Keywords
- `quick`, `brief`, `short`, `summary`, `concise`, `simple`, `fast`, `tldr`, `bottom line`

### Detailed Response Keywords  
- `detailed`, `comprehensive`, `thorough`, `in-depth`, `report`, `breakdown`, `explain`, `elaborate`, `deep dive`

### Default Behavior
- **Short responses** are the default (under 200 words)
- **Detailed responses** are triggered by specific keywords (comprehensive analysis)

## πŸ”§ Technical Architecture

- **Frontend**: Gradio web interface with real-time streaming
- **Backend**: LangChain agents with OpenAI GPT-4
- **Data Sources**: 
  - Yahoo Finance API for stock data
  - Tavily Search API for market news
  - Real-time financial calculations
- **Streaming**: Direct LLM token streaming from OpenAI API
- **Tools**: Specialized financial analysis functions

## πŸ“Š Tool Capabilities

### Investment Analyzer
- Real-time stock prices and historical data
- Technical indicators (RSI, MACD, Bollinger Bands, Moving Averages)
- Risk assessment (volatility, VaR, beta analysis)
- Fundamental analysis (P/E, P/B ratios, dividend yield)
- Buy/Hold/Sell recommendations with confidence scores

### Budget Planner
- 50/30/20 rule implementation
- Emergency fund calculations
- Debt-to-income ratio analysis
- Savings optimization recommendations
- Expense category warnings

### Market Trends Analyzer
- Real-time market news via Tavily Search
- Major index tracking (S&P 500, NASDAQ)
- Market sentiment analysis
- Key theme extraction
- Economic trend identification

### Portfolio Analyzer
- Diversification scoring
- Sector allocation analysis
- Concentration risk assessment
- Rebalancing recommendations
- Performance metrics

### Expense Tracker
- Category-wise spending analysis
- Trend detection and predictions
- Budget vs. actual comparisons
- Anomaly detection
- Spending pattern insights

## πŸš€ Recent Updates

- βœ… **Smart Response Detection**: Automatically detects if users want short or detailed responses
- βœ… **Real LLM Streaming**: Genuine token-by-token streaming from OpenAI API
- βœ… **Enhanced Tool Status**: Real-time API call tracking with time estimates
- βœ… **Improved Data Analysis**: Comprehensive visualizations and insights
- βœ… **Optimized Performance**: Faster tool execution and response times
- βœ… **Collapsible Results**: Clean, organized tool output presentation

## πŸ”’ API Keys Required

- **OpenAI API Key**: For language model
- **Tavily API Key**: For real-time market news and trends

## Issues to Resolve
The problem is in the current flow:
    1. Agent executor runs all tools
    2. We collect ALL results
    3. Then display everything at once
    4. Then stream the final response

## 🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.