Skip to content

A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.

corrected mcp for finagent

Omee9721d9e5951c0d
diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json
new file mode 100644
index 0000000..f912847
--- /dev/null
+++ b/.vscode/c_cpp_properties.json
@@ -0,0 +1,18 @@
+{
+ "configurations": [
+ {
+ "name": "windows-gcc-x86",
+ "includePath": [
+ "${workspaceFolder}/**"
+ ],
+ "compilerPath": "C:/MinGW/bin/gcc.exe",
+ "cStandard": "${default}",
+ "cppStandard": "${default}",
+ "intelliSenseMode": "windows-gcc-x86",
+ "compilerArgs": [
+ ""
+ ]
+ }
+ ],
+ "version": 4
+}
\ No newline at end of file
diff --git a/.vscode/launch.json b/.vscode/launch.json
new file mode 100644
index 0000000..2f014ea
--- /dev/null
+++ b/.vscode/launch.json
@@ -0,0 +1,24 @@
+{
+ "version": "0.2.0",
+ "configurations": [
+ {
+ "name": "C/C++ Runner: Debug Session",
+ "type": "cppdbg",
+ "request": "launch",
+ "args": [],
+ "stopAtEntry": false,
+ "externalConsole": true,
+ "cwd": ".",
+ "program": "build/Debug/outDebug",
+ "MIMode": "gdb",
+ "miDebuggerPath": "gdb",
+ "setupCommands": [
+ {
+ "description": "Enable pretty-printing for gdb",
+ "text": "-enable-pretty-printing",
+ "ignoreFailures": true
+ }
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/.vscode/settings.json b/.vscode/settings.json
new file mode 100644
index 0000000..bb879da
--- /dev/null
+++ b/.vscode/settings.json
@@ -0,0 +1,59 @@
+{
+ "C_Cpp_Runner.cCompilerPath": "gcc",
+ "C_Cpp_Runner.cppCompilerPath": "g++",
+ "C_Cpp_Runner.debuggerPath": "gdb",
+ "C_Cpp_Runner.cStandard": "",
+ "C_Cpp_Runner.cppStandard": "",
+ "C_Cpp_Runner.msvcBatchPath": "C:/Program Files/Microsoft Visual Studio/VR_NR/Community/VC/Auxiliary/Build/vcvarsall.bat",
+ "C_Cpp_Runner.useMsvc": false,
+ "C_Cpp_Runner.warnings": [
+ "-Wall",
+ "-Wextra",
+ "-Wpedantic",
+ "-Wshadow",
+ "-Wformat=2",
+ "-Wcast-align",
+ "-Wconversion",
+ "-Wsign-conversion",
+ "-Wnull-dereference"
+ ],
+ "C_Cpp_Runner.msvcWarnings": [
+ "/W4",
+ "/permissive-",
+ "/w14242",
+ "/w14287",
+ "/w14296",
+ "/w14311",
+ "/w14826",
+ "/w44062",
+ "/w44242",
+ "/w14905",
+ "/w14906",
+ "/w14263",
+ "/w44265",
+ "/w14928"
+ ],
+ "C_Cpp_Runner.enableWarnings": true,
+ "C_Cpp_Runner.warningsAsError": false,
+ "C_Cpp_Runner.compilerArgs": [],
+ "C_Cpp_Runner.linkerArgs": [],
+ "C_Cpp_Runner.includePaths": [],
+ "C_Cpp_Runner.includeSearch": [
+ "*",
+ "**/*"
+ ],
+ "C_Cpp_Runner.excludeSearch": [
+ "**/build",
+ "**/build/**",
+ "**/.*",
+ "**/.*/**",
+ "**/.vscode",
+ "**/.vscode/**"
+ ],
+ "C_Cpp_Runner.useAddressSanitizer": false,
+ "C_Cpp_Runner.useUndefinedSanitizer": false,
+ "C_Cpp_Runner.useLeakSanitizer": false,
+ "C_Cpp_Runner.showCompilationTime": false,
+ "C_Cpp_Runner.useLinkTimeOptimization": false,
+ "C_Cpp_Runner.msvcSecureNoWarnings": false
+}
\ No newline at end of file
diff --git a/finagent/README.md b/finagent/README.md
index 0164cc4..140d8a3 100644
--- a/finagent/README.md
+++ b/finagent/README.md
@@ -7,8 +7,8 @@ A sophisticated financial analysis system that leverages Google's Gemini AI and
- **Multi-Agent AI System**: Specialized agents for query parsing, code generation, and market analysis
- **Real-time Stock Data**: Fetches live market data using Yahoo Finance
- **Automated Code Generation**: Creates executable Python code for financial analysis
-- **News Integration**: Incorporates latest market news into analysis (via Firecrawl)
-- **MCP Server**: Modern Model Context Protocol server for seamless AI assistant integration
+- **News Integration**: Incorporates latest market news into analysis
+- **MCP Server**: Modern Model Context Protocol server for Claude Desktop integration
- **Professional Visualizations**: Generates matplotlib charts and technical analysis plots
- **Risk Assessment**: Provides balanced investment recommendations with proper disclaimers
@@ -16,6 +16,7 @@ A sophisticated financial analysis system that leverages Google's Gemini AI and
- Python 3.8+
- Google Gemini API key
+- Claude Desktop (for MCP integration)
- Firecrawl API key (optional, for enhanced news features)
## File Structure
@@ -68,34 +69,108 @@ FIRECRAWL_API_KEY=your_firecrawl_api_key_here # Optional
2. Get your API key from the dashboard
3. Add it to your `.env` file for enhanced news features
+## Claude Desktop Integration
+
+### Setup MCP Server with Claude Desktop
+
+1. **Install Claude Desktop**:
+
+ - Download from [Claude.ai](https://claude.ai/download)
+ - Install and launch the application
+
+2. **Configure MCP Server**:
+
+ Locate your Claude Desktop config file:
+
+ - **MacOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
+ - **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
+
+3. **Add Finagent Server**:
+
+ Edit the config file and add:
+
+ ```json
+ {
+ "mcpServers": {
+ "financial-analyst": {
+ "command": "python",
+ "args": ["/absolute/path/to/finagent/main.py"],
+ "env": {
+ "GEMINI_API_KEY": "your_gemini_api_key_here",
+ "FIRECRAWL_API_KEY": "your_firecrawl_api_key_here"
+ }
+ }
+ }
+ }
+ ```
+
+ Replace `/absolute/path/to/finagent/main.py` with the actual path to your main.py file.
+
+4. **Restart Claude Desktop**:
+
+ - Quit Claude Desktop completely
+ - Relaunch the application
+ - The MCP server should now be available
+
+5. **Verify Connection**:
+
+ In Claude Desktop, you should see the financial analysis tools available. Ask Claude:
+
+ ```
+ Can you analyze Apple stock for me?
+ ```
+
+### Available Tools in Claude Desktop
+
+Once configured, Claude can use these tools:
+
+- **analyze_stock**: Get comprehensive stock analysis with AI insights
+- **execute_code**: Run generated Python analysis code
+- **get_news**: Fetch latest market news for stocks
+
+### Example Conversations with Claude Desktop
+
+```
+You: Analyze Tesla stock performance over the last 6 months
+
+Claude: I'll analyze Tesla stock for you using the financial analysis tool...
+[Uses analyze_stock tool]
+```
+
+```
+You: What's the latest news on NVDA?
+
+Claude: Let me fetch the latest news for NVIDIA...
+[Uses get_news tool]
+```
+
+```
+You: Can you execute this analysis code for me?
+
+Claude: I'll run that code using the execution tool...
+[Uses execute_code tool]
+```
+
## Usage
-### As MCP Server
+### As MCP Server (Standalone)
-Start the MCP server:
+Start the MCP server manually:
```bash
python main.py
```
-The server will expose three main tools:
-
-- `analyze_stock`: Comprehensive stock analysis with AI insights
-- `execute_code`: Execute generated Python analysis code
-- `get_news`: Fetch latest market news for any stock
-
### Direct Python Usage
```python
from financial_agents import FinancialAnalysisTeam
-# Initialize the analysis team
team = FinancialAnalysisTeam(
gemini_api_key="your_gemini_key",
- firecrawl_api_key="your_firecrawl_key" # Optional
+ firecrawl_api_key="your_firecrawl_key"
)
-# Analyze a stock
result = team.analyze("Analyze Apple stock over the last 6 months")
print(f"Insights: {result.insights}")
@@ -111,29 +186,16 @@ The system understands natural language queries:
- "Compare Apple and Microsoft stocks this year"
- "Technical analysis of NVDA with RSI and MACD indicators"
- "What's the current sentiment on Bitcoin?"
+- "Show me the latest news for Amazon stock"
## Architecture
### Core Components
1. **FinancialAnalysisTeam**: Main orchestrator class
-
- - Coordinates multiple AI agents
- - Manages data flow and analysis workflow
-
2. **GeminiAgent**: Base agent class using Gemini AI
-
- - Specialized agents for different analysis tasks
- - Configurable safety settings and generation parameters
-
3. **FinancialTools**: Data acquisition utilities
-
- - Yahoo Finance integration for market data
- - News fetching capabilities
-
-4. **MCP Server**: Modern protocol server
- - Seamless integration with AI assistants
- - RESTful API endpoints for analysis tools
+4. **MCP Server**: Model Context Protocol server for Claude Desktop
### Agent Specialization
@@ -161,17 +223,51 @@ The system understands natural language queries:
### Common Issues
-1. **Import Errors**: Ensure all dependencies are installed
+1. **MCP Server Not Showing in Claude Desktop**:
+
+ - Verify the config file path is correct
+ - Check that Python path in config is valid
+ - Ensure main.py path is absolute, not relative
+ - Restart Claude Desktop completely
+
+2. **Import Errors**:
```bash
pip install google-generativeai yfinance pandas mcp python-dotenv
```
-2. **API Key Issues**: Verify your `.env` file is in the project root and properly formatted
+3. **API Key Issues**:
+
+ - Verify your `.env` file is in the project root
+ - Check API keys are valid and properly formatted
+ - Ensure environment variables are set in Claude Desktop config
+
+4. **Data Fetching Errors**:
+
+ - Check internet connection
+ - Verify ticker symbol validity
+ - Yahoo Finance may have rate limits
+
+5. **Code Execution Timeout**:
+ - Large datasets may require increased timeout values
+ - Check for infinite loops in generated code
+
+### Debug Mode
+
+To enable detailed logging:
-3. **Data Fetching Errors**: Check internet connection and ticker symbol validity
+```bash
+export LOG_LEVEL=DEBUG
+python main.py
+```
+
+## Security
-4. **Code Execution Timeout**: Large datasets may require increased timeout values
+- Never commit API keys to version control
+- Use environment variables for all sensitive configuration
+- Regularly rotate API keys
+- Monitor API usage and costs
+- Keep Claude Desktop config file secure
## Contributing
@@ -185,13 +281,6 @@ pip install google-generativeai yfinance pandas mcp python-dotenv
This project is licensed under the MIT License - see the LICENSE file for details.
-## Security
-
-- Never commit API keys to version control
-- Use environment variables for all sensitive configuration
-- Regularly rotate API keys
-- Monitor API usage and costs
-
## Support
For questions and support:
@@ -202,4 +291,4 @@ For questions and support:
---
-**Made with care using Google Gemini AI**
+**Made with Google Gemini AI & Claude Desktop**
diff --git a/finagent/__pycache__/financial_agents.cpython-313.pyc b/finagent/__pycache__/financial_agents.cpython-313.pyc
index 1c14e10..9c0a3a0 100644
Binary files a/finagent/__pycache__/financial_agents.cpython-313.pyc and b/finagent/__pycache__/financial_agents.cpython-313.pyc differ
diff --git a/finagent/__pycache__/main.cpython-313.pyc b/finagent/__pycache__/main.cpython-313.pyc
new file mode 100644
index 0000000..d4421eb
Binary files /dev/null and b/finagent/__pycache__/main.cpython-313.pyc differ
diff --git a/finagent/financial_agents.py b/finagent/financial_agents.py
index 731141f..aca7f45 100644
--- a/finagent/financial_agents.py
+++ b/finagent/financial_agents.py
@@ -1,46 +1,45 @@
#!/usr/bin/env python3
-"""
-Financial Analysis Team using Gemini AI
-"""
-
import json
import re
-from dataclasses import dataclass, asdict, field
-from typing import List, Optional, Dict, Any
import logging
import sys
+from dataclasses import dataclass, field
+from typing import List, Optional, Dict
try:
import google.generativeai as genai
from google.generativeai.types import HarmCategory, HarmBlockThreshold
-except ImportError:
- print("Google Generative AI not installed. Install with: pip install google-generativeai", file=sys.stderr)
- raise
-
-try:
import yfinance as yf
import pandas as pd
-except ImportError:
- print("Required packages not installed. Install with: pip install yfinance pandas", file=sys.stderr)
+except ImportError as e:
+ print(f"Required packages not installed: {e}\nInstall with: pip install google-generativeai yfinance pandas", file=sys.stderr)
raise
+logging.basicConfig(
+ level=logging.INFO,
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+)
+
logger = logging.getLogger(__name__)
+
@dataclass
class QueryInfo:
symbol: str
analysis_type: str = "comprehensive"
- time_period: str = "6m"
+ time_period: str = "6mo"
additional_symbols: List[str] = field(default_factory=list)
indicators: List[str] = field(default_factory=list)
+
@dataclass
class NewsItem:
title: str
summary: str
url: str
+
@dataclass
class AnalysisResult:
query: QueryInfo
@@ -49,94 +48,133 @@ class AnalysisResult:
recommendations: str
news: List[NewsItem] = field(default_factory=list)
+
class FinancialTools:
- """Financial data and news tools"""
-
def __init__(self, firecrawl_api_key: Optional[str] = None):
self.firecrawl_api_key = firecrawl_api_key
-
+
def get_stock_data(self, symbol: str, period: str = "6mo") -> pd.DataFrame:
- """Get stock data from Yahoo Finance"""
+ """Fetch historical stock data"""
try:
ticker = yf.Ticker(symbol)
- return ticker.history(period=period)
+ data = ticker.history(period=period)
+ if data.empty:
+ logger.warning(f"No data returned for {symbol}")
+ return data
except Exception as e:
logger.error(f"Error fetching data for {symbol}: {e}")
return pd.DataFrame()
-
+
def get_stock_info(self, symbol: str) -> Dict:
- """Get basic stock information"""
+ """Fetch stock metadata and information"""
try:
ticker = yf.Ticker(symbol)
- return ticker.info
+ info = ticker.info
+ return info if info else {}
except Exception as e:
logger.error(f"Error fetching info for {symbol}: {e}")
return {}
-
+
def get_stock_news(self, symbol: str, limit: int = 5) -> List[Dict]:
- """Get stock news - simplified version"""
+ """Fetch recent news for a stock symbol"""
+
+ def _normalize_url(u: Optional[str]) -> str:
+ if not u:
+ return ''
+ u = str(u).strip()
+ if u.startswith('//'):
+ return 'https:' + u
+ if u.startswith('http://') or u.startswith('https://'):
+ return u
+ if u.startswith('/'):
+ return 'https://finance.yahoo.com' + u
+ return ''
+
+ def _safe_string(value, default: str = '') -> str:
+ """Safely convert value to string, handling None cases"""
+ if value is None:
+ return default
+ return str(value)
+
try:
ticker = yf.Ticker(symbol)
- news = getattr(ticker, 'news', None)
- if not news:
- # Some versions of yfinance may expose news via an attribute or method
- news = []
-
- parsed = []
- for item in news[:limit]:
- # yfinance news items can vary across versions; be defensive
- title = item.get('title') if isinstance(item, dict) and 'title' in item else item.get('summary', '') if isinstance(item, dict) else ''
- url = item.get('link') or item.get('url') or '' if isinstance(item, dict) else ''
- content = item.get('summary') or item.get('content') or '' if isinstance(item, dict) else ''
- parsed.append({'title': title, 'url': url, 'content': content})
-
- return parsed
+ news = getattr(ticker, 'news', []) or []
+
+ out: List[Dict] = []
+ for item in news:
+ if not isinstance(item, dict):
+ continue
+
+ title = _safe_string(
+ item.get('title') or
+ item.get('summary') or
+ item.get('headline'),
+ 'Market Update'
+ )
+
+ raw_url = _safe_string(
+ item.get('link') or
+ item.get('url') or
+ item.get('linkUrl')
+ )
+
+ url = _normalize_url(raw_url)
+
+ content = _safe_string(
+ item.get('summary') or
+ item.get('content') or
+ item.get('snippet')
+ )
+
+ out.append({
+ 'title': title,
+ 'url': url,
+ 'content': content
+ })
+
+ if len(out) >= limit:
+ break
+
+ return out
+
except Exception as e:
logger.error(f"Error fetching news for {symbol}: {e}")
return []
def _normalize_period(period: str) -> str:
- """Normalize common period shorthand to yfinance-compatible period strings.
-
- Examples:
- - '6m' -> '6mo'
- - '1y' -> '1y'
- - '1d' -> '1d'
- - '3m' -> '3mo'
- If period is already yfinance-friendly, return it unchanged.
- """
+ """Normalize time period strings to yfinance format"""
if not period:
return '6mo'
+
p = str(period).strip().lower()
- # Accept formats like '6m', '6mo', '1y', '1d'
- m = re.match(r'^(\d+)(m|mo|y|d)$', p)
+ m = re.match(r'^(\d+)(m|mo|y|d|w)$', p)
if m:
- num, unit = m.groups()
+ num, unit = m.group(1), m.group(2)
if unit == 'm':
unit = 'mo'
return f"{num}{unit}"
+
return p
+
class GeminiAgent:
- """Base agent using Gemini AI"""
-
+ """Agent that uses Google's Gemini API for text generation"""
+
def __init__(self, api_key: str, role: str, system_prompt: str):
genai.configure(api_key=api_key)
- self.model = genai.GenerativeModel('gemini-pro')
+ self.model = genai.GenerativeModel('gemini-2.5-flash')
self.role = role
self.system_prompt = system_prompt
-
- # Configure safety settings
self.safety_settings = {
HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE,
HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_NONE,
HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE,
HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_NONE,
}
-
+
def generate(self, prompt: str) -> str:
- """Generate response using Gemini"""
+ """Generate a response using Gemini"""
try:
full_prompt = f"{self.system_prompt}\n\nUser Request: {prompt}"
response = self.model.generate_content(
@@ -144,255 +182,284 @@ class GeminiAgent:
safety_settings=self.safety_settings,
generation_config=genai.types.GenerationConfig(
temperature=0.7,
- max_output_tokens=2000,
+ max_output_tokens=2000
)
)
return response.text
except Exception as e:
- logger.error(f"Error generating response: {e}")
- return f"Error: Unable to generate response - {str(e)}"
+ logger.error(f"Error generating response for {self.role}: {e}")
+ return f"Error: Unable to generate response - {e}"
+
class FinancialAnalysisTeam:
- """Multi-agent financial analysis team using Gemini AI"""
-
+ """Orchestrates multiple AI agents for comprehensive financial analysis"""
+
def __init__(self, firecrawl_api_key: Optional[str] = None, gemini_api_key: str = None):
if not gemini_api_key:
raise ValueError("Gemini API key is required")
-
+
self.tools = FinancialTools(firecrawl_api_key)
-
- # Initialize agents
+
self.query_parser = GeminiAgent(
- api_key=gemini_api_key,
- role="Query Parser",
- system_prompt="""You are a financial query parser. Extract key information from user queries:
-- Stock symbol (primary focus)
+ gemini_api_key,
+ "Query Parser",
+ """You are a financial query parser. Extract key information from user queries:
+- Stock symbol (primary focus) - must be a valid ticker
- Analysis type (technical, fundamental, comprehensive)
-- Time period (1d, 1w, 1m, 3m, 6m, 1y, 2y)
+- Time period (1d, 1w, 1m, 3m, 6m, 1y, 2y, 5y)
- Additional symbols for comparison
-- Technical indicators requested
+- Technical indicators requested (RSI, MACD, Moving Averages, etc.)
Return a JSON object with: symbol, analysis_type, time_period, additional_symbols, indicators.
-If information is unclear, use reasonable defaults."""
+If information is unclear, use reasonable defaults. Always extract at least the stock symbol."""
)
-
+
self.code_generator = GeminiAgent(
- api_key=gemini_api_key,
- role="Code Generator",
- system_prompt="""You are a Python code generator for financial analysis. Generate clean, executable Python code using:
-- yfinance for data
-- pandas for analysis
-- matplotlib for visualization
-- numpy for calculations
+ gemini_api_key,
+ "Code Generator",
+ """You are a Python code generator for financial analysis. Generate clean, executable Python code using:
+- yfinance for data retrieval
+- pandas for data manipulation
+- matplotlib/seaborn for visualization
+- numpy for numerical calculations
Requirements:
-- Include proper imports
-- Add error handling
-- Create informative plots
-- Use professional styling
-- Include data validation
+- Include all necessary imports at the top
+- Add comprehensive error handling
+- Create clear, informative plots with proper labels
+- Use professional styling (grid, legends, titles)
+- Include data validation checks
- Add comments explaining key sections
+- Make code self-contained and executable
-Focus on creating practical, working code that provides valuable insights."""
+Focus on creating practical, working code that provides valuable financial insights."""
)
-
+
self.market_analyst = GeminiAgent(
- api_key=gemini_api_key,
- role="Market Analyst",
- system_prompt="""You are a senior financial analyst. Provide expert market insights and investment recommendations based on:
-- Technical analysis patterns
+ gemini_api_key,
+ "Market Analyst",
+ """You are a senior financial analyst with expertise in market analysis. Provide expert insights based on:
+- Technical analysis patterns (support/resistance, trends, momentum)
- Market trends and sentiment
-- Risk assessment
+- Price action and volume analysis
+- Risk assessment and volatility
- Investment opportunities
-Be professional, balanced, and provide actionable insights. Always include risk warnings and mention this is not financial advice."""
+Be professional, balanced, and provide actionable insights. Structure your analysis clearly.
+Always include risk warnings and explicitly state "This is not financial advice. Do your own research before investing."""""
)
-
+
def parse_query(self, query: str) -> QueryInfo:
- """Parse natural language query"""
+ """Parse user query to extract structured information"""
try:
response = None
try:
response = self.query_parser.generate(query)
- except Exception as gen_err:
- # Log and continue to heuristic fallback below
- logger.warning(f"Gemini generation failed, falling back to heuristic parsing: {gen_err}")
+ except Exception as e:
+ logger.warning(f"Gemini parsing failed, using fallback: {e}")
data = None
if response:
- # Extract JSON from response if present
json_match = re.search(r'\{.*\}', response, re.DOTALL)
if json_match:
try:
data = json.loads(json_match.group())
- except Exception:
- # Invalid JSON in model output; ignore and use heuristic fallback
- logger.warning("Model output contained invalid JSON — falling back to heuristic parsing")
+ except json.JSONDecodeError:
+ logger.warning("Invalid JSON in model response")
- # If model didn't provide valid JSON, fall back to heuristic extraction + yfinance validation
+ # Fallback parsing if Gemini fails
if not data:
- # Try to heuristically extract a ticker symbol from the query
symbol_match = re.search(r"\b([A-Z]{1,5}(?:\.[A-Z]{1,4})?)\b", query.upper())
if not symbol_match:
- raise ValueError("No ticker symbol found in query. Please include a valid stock ticker.")
+ raise ValueError("No ticker symbol found in query. Please include a valid stock ticker (e.g., AAPL, MSFT).")
symbol = symbol_match.group(1)
- # Validate the extracted symbol with yfinance to ensure real data exists
+ # Validate symbol
try:
info = yf.Ticker(symbol).info
- if not info or info.get('regularMarketPrice') is None:
+ if not info or 'regularMarketPrice' not in info:
raise ValueError(f"Ticker '{symbol}' not found or has no market data.")
- except Exception as e:
- raise ValueError(f"Ticker validation failed for '{symbol}': {e}")
+ except Exception:
+ raise ValueError(f"Unable to verify ticker '{symbol}'. Please check the symbol.")
+
+ data = {
+ "symbol": symbol,
+ "analysis_type": "comprehensive",
+ "time_period": "6mo",
+ "additional_symbols": [],
+ "indicators": []
+ }
- data = {"symbol": symbol, "analysis_type": "comprehensive", "time_period": "6m", "additional_symbols": [], "indicators": []}
-
- # Ensure the parser returned a real symbol; do not silently
- # fall back to any hard-coded ticker.
symbol = data.get("symbol")
if not symbol:
- raise ValueError("Parser did not return a ticker symbol.")
+ raise ValueError("Could not extract ticker symbol from query.")
return QueryInfo(
symbol=symbol,
analysis_type=data.get("analysis_type", "comprehensive"),
- time_period=data.get("time_period", "6m"),
+ time_period=data.get("time_period", "6mo"),
additional_symbols=data.get("additional_symbols", []),
indicators=data.get("indicators", [])
)
+
except Exception as e:
- # Log the parsing/validation error and re-raise so the higher-level
- # workflow can produce an informative AnalysisResult instead of
- # silently using mock data.
logger.error(f"Error parsing query: {e}", exc_info=True)
raise
-
+
def generate_code(self, query_info: QueryInfo, stock_data: pd.DataFrame) -> str:
- """Generate Python analysis code"""
+ """Generate Python code for financial analysis"""
+ data_info = "No data available"
+ if not stock_data.empty:
+ data_info = f"{len(stock_data)} rows, columns: {', '.join(stock_data.columns[:5])}"
+
prompt = f"""Generate Python code for financial analysis:
-Stock: {query_info.symbol}
+Stock Symbol: {query_info.symbol}
Analysis Type: {query_info.analysis_type}
Time Period: {query_info.time_period}
-Data Shape: {stock_data.shape if not stock_data.empty else "No data"}
-
-Create code that:
-1. Fetches data using yfinance
-2. Performs technical analysis
-3. Creates professional visualizations
-4. Calculates key metrics
-5. Handles errors gracefully
+Data Available: {data_info}
+Requested Indicators: {', '.join(query_info.indicators) if query_info.indicators else 'Standard technical indicators'}
+
+Create complete, executable code that:
+1. Imports required libraries (yfinance, pandas, matplotlib, numpy)
+2. Fetches stock data for the specified period
+3. Performs technical analysis (moving averages, RSI, volume analysis)
+4. Creates professional visualizations with:
+ - Price chart with moving averages
+ - Volume chart
+ - Technical indicators
+5. Calculates key metrics (returns, volatility, trends)
+6. Includes proper error handling
+7. Uses professional styling
+
+Make the code self-contained and production-ready with clear comments."""
-Make it production-ready and well-documented."""
-
return self.code_generator.generate(prompt)
-
- def analyze_market(self, query_info: QueryInfo, stock_data: pd.DataFrame, news: List[Dict] = None) -> tuple:
+
+ def analyze_market(self, query_info: QueryInfo, stock_data: pd.DataFrame,
+ news: List[Dict] = None) -> tuple:
"""Generate market insights and recommendations"""
- # Prepare data summary with defensive checks
data_summary = "No data available"
+
try:
- if not stock_data.empty and 'Close' in stock_data.columns and len(stock_data['Close']) >= 1:
- latest_price = stock_data['Close'].iloc[-1]
-
- # Compute price change only if we have at least two data points and non-zero first value
- if len(stock_data['Close']) >= 2 and stock_data['Close'].iloc[0] != 0:
- price_change = ((stock_data['Close'].iloc[-1] / stock_data['Close'].iloc[0]) - 1) * 100
- else:
- price_change = 0.0
-
- # Volatility requires at least two points
- if len(stock_data['Close']) >= 2:
- volatility = stock_data['Close'].pct_change().std() * 100
- else:
- volatility = 0.0
-
- data_summary = f"Latest Price: ${latest_price:.2f}, Change: {price_change:.1f}%, Volatility: {volatility:.1f}%"
+ if not stock_data.empty and 'Close' in stock_data.columns:
+ close_prices = stock_data['Close'].dropna()
+ if len(close_prices) >= 2:
+ latest = close_prices.iloc[-1]
+ first = close_prices.iloc[0]
+ change = ((latest / first) - 1) * 100 if first != 0 else 0.0
+ volatility = close_prices.pct_change().std() * 100
+
+ data_summary = (
+ f"Latest Price: ${latest:.2f}, "
+ f"Period Change: {change:+.1f}%, "
+ f"Volatility: {volatility:.1f}%"
+ )
except Exception as e:
logger.warning(f"Failed to compute data summary: {e}")
-
+
news_summary = ""
if news:
- news_summary = "Recent news: " + "; ".join([item.get('title', '')[:50] for item in news[:3]])
-
- insights_prompt = f"""Analyze this stock data and provide expert insights:
+ news_titles = []
+ for item in news[:3]:
+ title = item.get('title', '') if item.get('title') is not None else ''
+ if title:
+ news_titles.append(str(title)[:60])
+
+ if news_titles:
+ news_summary = "Recent headlines: " + "; ".join(news_titles)
+
+ insights_prompt = f"""Analyze this stock and provide expert insights:
Stock: {query_info.symbol}
Analysis Period: {query_info.time_period}
Data Summary: {data_summary}
{news_summary}
-Provide professional market insights covering:
-- Current market position
-- Technical patterns observed
-- Market sentiment
-- Key risk factors
-- Investment thesis"""
-
+Provide a comprehensive analysis covering:
+1. Current market position and price action
+2. Technical patterns and trends observed
+3. Market sentiment indicators
+4. Key support and resistance levels
+5. Risk factors to consider
+
+Be specific, professional, and actionable."""
+
+ insights = self.market_analyst.generate(insights_prompt)
+
recommendations_prompt = f"""Based on the analysis of {query_info.symbol}, provide investment recommendations:
Data: {data_summary}
{news_summary}
-Provide:
-- Clear investment recommendation (Buy/Hold/Sell with rationale)
-- Risk assessment
-- Price targets or key levels
-- Time horizon considerations
-- Portfolio allocation suggestions
+Provide clear guidance including:
+1. Investment recommendation (Buy/Hold/Sell) with detailed rationale
+2. Risk assessment (Low/Medium/High with explanation)
+3. Price targets or key technical levels to watch
+4. Time horizon considerations (short/medium/long term)
+5. Portfolio allocation suggestions (if buying)
+
+End with: "⚠️ Disclaimer: This is not financial advice. Always do your own research and consult with a financial advisor before making investment decisions."""
-Remember to include appropriate disclaimers."""
-
- insights = self.market_analyst.generate(insights_prompt)
recommendations = self.market_analyst.generate(recommendations_prompt)
-
+
return insights, recommendations
-
+
def analyze(self, query: str) -> AnalysisResult:
- """Complete financial analysis workflow"""
+ """Main analysis pipeline"""
try:
- # Parse query (may raise ValueError if no valid ticker found)
+ # Parse the query
try:
query_info = self.parse_query(query)
except Exception as e:
- # Return a structured AnalysisResult indicating the input error
+ logger.error(f"Query parsing failed: {e}")
return AnalysisResult(
query=QueryInfo(symbol="INVALID"),
- insights=f"Input error: {str(e)}",
+ insights=f"Input error: {e}",
code="# No code generated due to input error",
recommendations="Please provide a valid stock ticker in your query.",
news=[]
)
- logger.info(f"Analyzing {query_info.symbol}")
- # Normalize period for yfinance compatibility and fetch data
+ logger.info(f"Analyzing {query_info.symbol} for period {query_info.time_period}")
+
+ # Fetch data
period = _normalize_period(query_info.time_period)
stock_data = self.tools.get_stock_data(query_info.symbol, period)
news_data = self.tools.get_stock_news(query_info.symbol, 5)
+ # Check if we have data
if stock_data.empty:
+ logger.warning(f"No data available for {query_info.symbol}")
return AnalysisResult(
query=query_info,
insights="No market data could be retrieved for the provided ticker.",
code="# No code generated because historical price data is unavailable",
- recommendations="Verify the ticker symbol and try again. If the ticker is correct, the data source may be temporarily unavailable.",
+ recommendations="Please verify the ticker symbol and try again.",
news=[]
)
-
+
# Generate analysis components
code = self.generate_code(query_info, stock_data)
insights, recommendations = self.analyze_market(query_info, stock_data, news_data)
-
- # Format news
+
+ # Process news items with safe string handling
news_items = []
for item in news_data[:3]:
+ title = item.get('title', '') if item.get('title') is not None else 'Market Update'
+ content = item.get('content', '') if item.get('content') is not None else ''
+ url = item.get('url', '') if item.get('url') is not None else ''
+
+ # Safe string slicing
+ summary = str(content)[:200] if len(str(content)) > 200 else str(content)
+
news_items.append(NewsItem(
- title=item.get('title', 'Market Update'),
- summary=item.get('content', '')[:200],
- url=item.get('url', '')
+ title=str(title),
+ summary=summary,
+ url=str(url)
))
-
+
return AnalysisResult(
query=query_info,
insights=insights,
@@ -400,13 +467,13 @@ Remember to include appropriate disclaimers."""
recommendations=recommendations,
news=news_items
)
-
+
except Exception as e:
- logger.error(f"Error in analysis: {e}")
- # Return error result
+ logger.error(f"Error in analysis pipeline: {e}", exc_info=True)
return AnalysisResult(
query=QueryInfo(symbol="ERROR"),
insights=f"Analysis failed: {str(e)}",
code="# Error: Unable to generate code",
- recommendations="Unable to provide recommendations due to error."
- )
\ No newline at end of file
+ recommendations="Unable to provide recommendations due to error.",
+ news=[]
+ )
diff --git a/finagent/main.py b/finagent/main.py
index b527965..bbca80a 100644
--- a/finagent/main.py
+++ b/finagent/main.py
@@ -1,212 +1,262 @@
#!/usr/bin/env python3
-"""
-MCP Financial Analyst Server with Gemini AI
-Using FastMCP for modern MCP server implementation
-"""
-
-import asyncio
-import json
import logging
import os
import sys
import tempfile
import subprocess
from dotenv import load_dotenv
-from pathlib import Path
-from typing import Any, Dict, List, Optional, Sequence
-from datetime import datetime
+from typing import Optional
+
+# Configure logging
+logging.basicConfig(
+ stream=sys.stderr,
+ level=logging.INFO,
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
+)
+logger = logging.getLogger("mcp-financial")
-logging.basicConfig(stream=sys.stderr, level=logging.INFO)
-# Load environment variables from .env file
+# Load environment variables
load_dotenv()
-# MCP imports - Using FastMCP
+# Import required modules with error handling
try:
from mcp.server.fastmcp import FastMCP
-except ImportError:
- print("MCP not installed. Install with: pip install mcp", file=sys.stderr)
- sys.exit(1)
-
-# Import agentic system
-try:
from financial_agents import FinancialAnalysisTeam, AnalysisResult, FinancialTools
- print("✅ Successfully imported financial_agents.py", file=sys.stderr)
except ImportError as e:
- print(f"❌ Error importing financial_agents.py: {str(e)}", file=sys.stderr)
- print("Make sure financial_agents.py is in the same directory and all dependencies are installed.", file=sys.stderr)
+ print(f"Import error: {e}\nInstall with: pip install mcp", file=sys.stderr)
sys.exit(1)
-logging.basicConfig(level=logging.INFO)
-logger = logging.getLogger("mcp-financial")
+# Create the FastMCP instance
+mcp = FastMCP("financial-analyst-gemini")
+
+# Initialize API keys from environment
+GEMINI_API_KEY = os.getenv('GEMINI_API_KEY')
+FIRECRAWL_API_KEY = os.getenv('FIRECRAWL_API_KEY')
+
+if not GEMINI_API_KEY:
+ print(
+ "ERROR: GEMINI_API_KEY environment variable is required.\n"
+ "Get your API key from: https://makersuite.google.com/app/apikey\n"
+ "Set it with: export GEMINI_API_KEY='your-key-here'",
+ file=sys.stderr
+ )
+ sys.exit(1)
+
+if not FIRECRAWL_API_KEY:
+ logger.info("FIRECRAWL_API_KEY not set (optional)")
+
+# Instantiate the analysis team object
+analysis_team = FinancialAnalysisTeam(FIRECRAWL_API_KEY, GEMINI_API_KEY)
+
+
+def analyze_stock(query: str) -> str:
+ """
+ Comprehensive stock analysis using AI agents.
+ Args:
+ query: Natural language query (e.g., "analyze AAPL" or "technical analysis of MSFT over 6 months")
+ Returns:
+ Formatted analysis report with insights, code, and recommendations
+ """
+ try:
+ result: AnalysisResult = analysis_team.analyze(query)
+ news_section = ""
+ if result.news:
+ news_section = "\n### Latest News:\n"
+ for i, news_item in enumerate(result.news[:3], 1):
+ summary = str(news_item.summary) if news_item.summary else ""
+ if len(summary) > 100:
+ summary = summary[:100] + "..."
+ url_part = f"\n [Read more]({news_item.url})" if news_item.url else ""
+ news_section += f"{i}. **{news_item.title}**\n {summary}{url_part}\n\n"
+
+ report = f"""# Stock Analysis - {result.query.symbol}
+
+## Market Insights
-class FinancialAnalysisServer:
- """Modern MCP Server for Financial Analysis with Gemini AI using FastMCP"""
-
- def __init__(self, gemini_api_key: str, firecrawl_api_key: Optional[str] = None):
- # Create FastMCP server
- self.mcp = FastMCP("financial-analyst-gemini")
- self.analysis_team = FinancialAnalysisTeam(firecrawl_api_key, gemini_api_key)
- self.setup_tools()
-
- def setup_tools(self):
- """Setup MCP tools using FastMCP decorators"""
-
- @self.mcp.tool()
- def analyze_stock(query: str) -> str:
- """Analyze stock using Gemini AI with news integration"""
- try:
- result: AnalysisResult = self.analysis_team.analyze(query)
-
- news_section = ""
- if result.news:
- news_section = "\n### 📰 Latest News:\n"
- for i, news in enumerate(result.news[:3], 1):
- news_section += f"{i}. **{news.title}**\n {news.summary[:100]}...\n\n"
-
- response = f"""# 📈 Stock Analysis - {result.query.symbol}
-
-## 💡 AI Insights
{result.insights}
-## 📊 Analysis Code
-```python
+## Analysis Code
+
{result.code}
-```
+
+
{news_section}
-## 🎯 Recommendations
+
+## Investment Recommendations
+
{result.recommendations}
---
-*Powered by Gemini AI*
-"""
- return response
- except Exception as e:
- logger.error(f"Analysis error: {str(e)}", exc_info=True)
- return f"❌ Analysis Error: {str(e)}"
-
- @self.mcp.tool()
- def execute_code(code: str, timeout: int = 30) -> str:
- """Execute generated Python analysis code"""
- execution_code = f"""
-import sys
-import warnings
-warnings.filterwarnings('ignore')
-try:
-{chr(10).join(' ' + line for line in code.split(chr(10)))}
-except Exception as e:
- print(f"Error: {{e}}")
- sys.exit(1)
+*Analysis powered by Gemini AI | Period: {result.query.time_period}*
"""
-
- with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
- f.write(execution_code)
- temp_file = f.name
-
- try:
- # Use UTF-8 encoding and replace errors to avoid 'charmap' codec issues on Windows
- result = subprocess.run([sys.executable, temp_file],
- capture_output=True, text=True, timeout=timeout, encoding='utf-8', errors='replace')
- os.unlink(temp_file)
-
- if result.returncode == 0:
- output = result.stdout or "Code executed successfully!"
- # Remove or replace non-printable / non-ascii characters that may break MCP clients
- safe_output = ''.join((ch if ord(ch) < 0x110000 else '?' for ch in output))
- return f"**Success**\n```\n{safe_output}\n```"
- else:
- safe_err = ''.join((ch if ord(ch) < 0x110000 else '?' for ch in (result.stderr or 'Error')))
- return f"**Error**\n```\n{safe_err}\n```"
-
- except subprocess.TimeoutExpired:
- os.unlink(temp_file)
- return f"⏰ Execution timeout after {timeout}s"
- except Exception as e:
- if os.path.exists(temp_file):
- os.unlink(temp_file)
- return f"❌ Execution error: {str(e)}"
-
- @self.mcp.tool()
- def get_news(symbol: str, limit: int = 5) -> str:
- """Fetch latest market news for a stock"""
- try:
- # Create FinancialTools instance to get news
- tools = FinancialTools()
- news_data = tools.get_stock_news(symbol, limit)
-
- if not news_data:
- return f"📰 No news found for {symbol}"
-
- news_text = f"# 📰 News for {symbol}\n\n"
- for i, item in enumerate(news_data[:limit], 1):
- title = item.get('title', 'Update')
- content = item.get('content', '')[:200] + "..." if len(item.get('content', '')) > 200 else item.get('content', '')
- url = item.get('url', '')
- news_text += f"## {i}. {title}\n{content}\n[Read more]({url})\n\n"
-
- return news_text
-
- except Exception as e:
- logger.error(f"News fetch error: {str(e)}", exc_info=True)
- return f"❌ News fetch error: {str(e)}"
-
- def run(self):
- """Run the MCP server"""
- self.mcp.run()
-
-def main():
- """Initialize and run the MCP server"""
-
- # Check for required packages
- missing_packages = []
- try:
- import google.generativeai as genai
- except ImportError:
- missing_packages.append("google-generativeai")
-
+ return report
+
+ except Exception as e:
+ logger.error(f"Analysis error: {e}", exc_info=True)
+ return (
+ f"# Analysis Error\n\n"
+ f"An unexpected error occurred while analyzing the query.\n\n"
+ f"**Error details:** {str(e)}\n\n"
+ f"Please check:\n"
+ f"- The ticker symbol is valid\n"
+ f"- Your API keys are configured correctly\n"
+ f"- You have an active internet connection\n\n"
+ f"Check server logs for full traceback."
+ )
+
+
+def execute_code(code: str, timeout: int = 30) -> str:
+ """
+ Execute Python code in a sandboxed environment.
+ Args:
+ code: Python code to execute
+ timeout: Maximum execution time in seconds (default: 30)
+ Returns:
+ Execution output or error message
+ """
+ exec_code = (
+ "import sys\n"
+ "import warnings\n"
+ "warnings.filterwarnings('ignore')\n\n"
+ "try:\n"
+ )
+
+ for line in code.split('\n'):
+ exec_code += f" {line}\n"
+
+ exec_code += (
+ "except Exception as e:\n"
+ " print(f'Execution Error: {e}', file=sys.stderr)\n"
+ " import traceback\n"
+ " traceback.print_exc()\n"
+ " sys.exit(1)\n"
+ )
+
+ with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
+ f.write(exec_code)
+ temp_file = f.name
+
try:
- import yfinance as yf
- import pandas as pd
- except ImportError:
- missing_packages.append("yfinance pandas")
-
+ result = subprocess.run(
+ [sys.executable, temp_file],
+ capture_output=True,
+ text=True,
+ timeout=timeout,
+ encoding='utf-8',
+ errors='replace'
+ )
+
+ os.unlink(temp_file)
+
+ stdout = result.stdout.strip()
+ stderr = result.stderr.strip()
+
+ if result.returncode != 0:
+ error_msg = stderr or stdout or 'Unknown error'
+ safe_output = ''.join(ch if ord(ch) < 0x110000 else '?' for ch in error_msg)
+ return f"**Execution Failed**\n``````"
+ else:
+ output = stdout or 'Code executed successfully!'
+ safe_output = ''.join(ch if ord(ch) < 0x110000 else '?' for ch in output)
+ return f"**Success**\n``````"
+
+ except subprocess.TimeoutExpired:
+ if os.path.exists(temp_file):
+ os.unlink(temp_file)
+ return f"**Timeout Error**\nExecution exceeded {timeout} seconds limit."
+
+ except Exception as e:
+ if os.path.exists(temp_file):
+ os.unlink(temp_file)
+ logger.exception("Code execution error")
+ return f"**Execution Error**\n``````"
+
+
+def get_news(symbol: str, limit: int = 5) -> str:
+ """
+ Fetch latest news for a stock symbol.
+ Args:
+ symbol: Stock ticker symbol (e.g., AAPL, MSFT)
+ limit: Maximum number of news items to return (default: 5)
+ Returns:
+ Formatted news items with titles, summaries, and links
+ """
try:
- from mcp.server.fastmcp import FastMCP
- except ImportError:
- missing_packages.append("mcp")
-
- if missing_packages:
- print(f"❌ Missing required packages: {', '.join(missing_packages)}", file=sys.stderr)
- print("Install with: pip install " + " ".join(missing_packages), file=sys.stderr)
- sys.exit(1)
-
- gemini_api_key = os.getenv('GEMINI_API_KEY')
- if not gemini_api_key:
- print("❌ GEMINI_API_KEY required. Get one from: https://makersuite.google.com/app/apikey", file=sys.stderr)
- print(f"❌ Debug: API Key found = {'Yes' if gemini_api_key else 'No'}", file=sys.stderr)
- print("❌ Make sure your .env file is in the same directory as main.py", file=sys.stderr)
- print("❌ .env file format should be: GEMINI_API_KEY=your_actual_key_here", file=sys.stderr)
+ news_data = FinancialTools().get_stock_news(symbol, limit)
+
+ if not news_data:
+ return f"# No News Found\n\nNo recent news articles found for {symbol.upper()}."
+
+ news_report = f"# Latest News for {symbol.upper()}\n\n"
+
+ for i, item in enumerate(news_data[:limit], 1):
+ title = str(item.get('title', 'Market Update'))
+ content = str(item.get('content', ''))
+ url = str(item.get('url', ''))
+
+ if len(content) > 200:
+ content = content[:200] + '...'
+
+ news_report += f"## {i}. {title}\n"
+ if content:
+ news_report += f"{content}\n"
+ if url:
+ news_report += f"[Read full article]({url})\n"
+ news_report += "\n"
+
+ return news_report
+
+ except Exception as e:
+ logger.error(f"News fetch error: {e}", exc_info=True)
+ return f"# Error Fetching News\n\nFailed to retrieve news for {symbol}: {str(e)}"
+
+
+def check_dependencies() -> bool:
+ """Check if all required packages are installed"""
+ required_packages = {
+ "google-generativeai": "google.generativeai",
+ "yfinance": "yfinance",
+ "pandas": "pandas",
+ "mcp": "mcp.server.fastmcp"
+ }
+
+ missing = []
+ for pkg_name, import_path in required_packages.items():
+ try:
+ parts = import_path.split('.')
+ module = __import__(parts[0])
+ for part in parts[1:]:
+ module = getattr(module, part)
+ except (ImportError, AttributeError):
+ missing.append(pkg_name)
+
+ if missing:
+ print(
+ f"Missing required packages: {', '.join(missing)}\n"
+ f"Install with: pip install {' '.join(missing)}",
+ file=sys.stderr
+ )
+ return False
+
+ return True
+
+
+if __name__ == "__main__":
+ if not check_dependencies():
sys.exit(1)
-
- print(f"✅ Gemini API Key loaded successfully (first 10 chars): {gemini_api_key[:10]}...", file=sys.stderr)
-
-
- firecrawl_api_key = os.getenv('FIRECRAWL_API_KEY')
- if firecrawl_api_key:
- print("✅ Firecrawl API Key also loaded", file=sys.stderr)
- else:
- print("⚠️ Firecrawl API Key not found (optional)", file=sys.stderr)
-
- # Create and run server
+
+ logger.info("Starting Financial Analysis MCP server...")
try:
- server = FinancialAnalysisServer(gemini_api_key, firecrawl_api_key)
- logger.info(f"✅ Financial Analysis Server initialized successfully")
- server.run()
+ mcp.run()
+ except KeyboardInterrupt:
+ logger.info("Server shutdown requested")
+ sys.exit(0)
except Exception as e:
- print(f"❌ Failed to start server: {str(e)}", file=sys.stderr)
- logger.error(f"Server startup error: {str(e)}", exc_info=True)
+ logger.error(f"Fatal error starting server: {e}", exc_info=True)
+ print(f"Failed to start server: {e}", file=sys.stderr)
sys.exit(1)
-
-if __name__ == "__main__":
- main()#!/usr/bin/env python3