A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.
Updated Readme.md
Omee971ffff09dc348
diff --git a/finagent/README.md b/finagent/README.mdindex 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 # Optional2. Get your API key from the dashboard3. 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:```bashpython 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```pythonfrom financial_agents import FinancialAnalysisTeam-# Initialize the analysis teamteam = FinancialAnalysisTeam(gemini_api_key="your_gemini_key",- firecrawl_api_key="your_firecrawl_key" # Optional+ firecrawl_api_key="your_firecrawl_key")-# Analyze a stockresult = 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 Components1. **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**:```bashpip 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-dotenvThis 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-## SupportFor 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/financial_agents.py b/finagent/financial_agents.pyindex 731141f..b2f306e 100644--- a/finagent/financial_agents.py+++ b/finagent/financial_agents.py@@ -1,28 +1,19 @@#!/usr/bin/env python3-"""-Financial Analysis Team using Gemini AI-"""-import jsonimport re-from dataclasses import dataclass, asdict, field-from typing import List, Optional, Dict, Any+from dataclasses import dataclass, field+from typing import List, Optional, Dictimport loggingimport systry:import google.generativeai as genaifrom 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 yfimport 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)raiselogger = logging.getLogger(__name__)@@ -50,84 +41,48 @@ class AnalysisResult: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_keydef get_stock_data(self, symbol: str, period: str = "6mo") -> pd.DataFrame:- """Get stock data from Yahoo Finance"""try:- ticker = yf.Ticker(symbol)- return ticker.history(period=period)+ return yf.Ticker(symbol).history(period=period)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"""try:- ticker = yf.Ticker(symbol)- return ticker.info+ return yf.Ticker(symbol).infoexcept 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"""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', [])+ return [{'title': item.get('title', item.get('summary', '')),+ 'url': item.get('link') or item.get('url', ''),+ 'content': item.get('summary') or item.get('content', '')}+ for item in news[:limit] if isinstance(item, dict)]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.- """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)- if m:- num, unit = m.groups()- if unit == 'm':- unit = 'mo'- return f"{num}{unit}"- return p+ return f"{m.group(1)}{'mo' if m.group(2) == 'm' else m.group(2)}" if m else pclass GeminiAgent:- """Base agent using Gemini AI"""-def __init__(self, api_key: str, role: str, system_prompt: str):genai.configure(api_key=api_key)self.model = genai.GenerativeModel('gemini-pro')self.role = roleself.system_prompt = system_prompt-- # Configure safety settingsself.safety_settings = {HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE,HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_NONE,@@ -136,36 +91,26 @@ class GeminiAgent:}def generate(self, prompt: str) -> str:- """Generate response using Gemini"""try:- full_prompt = f"{self.system_prompt}\n\nUser Request: {prompt}"response = self.model.generate_content(- full_prompt,+ f"{self.system_prompt}\n\nUser Request: {prompt}",safety_settings=self.safety_settings,- generation_config=genai.types.GenerationConfig(- temperature=0.7,- max_output_tokens=2000,- )+ generation_config=genai.types.GenerationConfig(temperature=0.7, max_output_tokens=2000))return response.textexcept Exception as e:logger.error(f"Error generating response: {e}")- return f"Error: Unable to generate response - {str(e)}"+ return f"Error: Unable to generate response - {e}"class FinancialAnalysisTeam:- """Multi-agent financial analysis team using Gemini AI"""-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:+ self.query_parser = GeminiAgent(gemini_api_key, "Query Parser",+ """You are a financial query parser. Extract key information from user queries:- Stock symbol (primary focus)- Analysis type (technical, fundamental, comprehensive)- Time period (1d, 1w, 1m, 3m, 6m, 1y, 2y)@@ -173,13 +118,10 @@ class FinancialAnalysisTeam:- Technical indicators requestedReturn 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.""")- 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:+ self.code_generator = GeminiAgent(gemini_api_key, "Code Generator",+ """You are a Python code generator for financial analysis. Generate clean, executable Python code using:- yfinance for data- pandas for analysis- matplotlib for visualization@@ -193,83 +135,60 @@ Requirements:- Include data validation- Add comments explaining key sections-Focus on creating practical, working code that provides valuable insights."""- )+Focus on creating practical, working code that provides valuable 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:+ self.market_analyst = GeminiAgent(gemini_api_key, "Market Analyst",+ """You are a senior financial analyst. Provide expert market insights and investment recommendations based on:- Technical analysis patterns- Market trends and sentiment- Risk assessment- 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. Always include risk warnings and mention this is not financial advice.""")def parse_query(self, query: str) -> QueryInfo:- """Parse natural language query"""try:response = Nonetry: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 generation failed, falling back to heuristic parsing: {e}")data = Noneif response:- # Extract JSON from response if presentjson_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")+ logger.warning("Model output contained invalid JSON")- # If model didn't provide valid JSON, fall back to heuristic extraction + yfinance validationif not data:- # Try to heuristically extract a ticker symbol from the querysymbol_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.")-+symbol = symbol_match.group(1)-- # Validate the extracted symbol with yfinance to ensure real data exists- try:- info = yf.Ticker(symbol).info- if not info or info.get('regularMarketPrice') is None:- 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}")-- data = {"symbol": symbol, "analysis_type": "comprehensive", "time_period": "6m", "additional_symbols": [], "indicators": []}+ info = yf.Ticker(symbol).info+ if not info or info.get('regularMarketPrice') is None:+ raise ValueError(f"Ticker '{symbol}' not found or has no market data.")++ 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.")- return QueryInfo(- symbol=symbol,- analysis_type=data.get("analysis_type", "comprehensive"),- time_period=data.get("time_period", "6m"),- additional_symbols=data.get("additional_symbols", []),- indicators=data.get("indicators", [])- )+ return QueryInfo(symbol=symbol, analysis_type=data.get("analysis_type", "comprehensive"),+ time_period=data.get("time_period", "6m"),+ 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)raisedef generate_code(self, query_info: QueryInfo, stock_data: pd.DataFrame) -> str:- """Generate Python analysis code"""prompt = f"""Generate Python code for financial analysis:Stock: {query_info.symbol}@@ -285,38 +204,22 @@ Create code that:5. Handles errors gracefullyMake 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:- """Generate market insights and recommendations"""- # Prepare data summary with defensive checksdata_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}%"+ latest = stock_data['Close'].iloc[-1]+ change = ((latest / stock_data['Close'].iloc[0]) - 1) * 100 if len(stock_data['Close']) >= 2 and stock_data['Close'].iloc[0] != 0 else 0.0+ vol = stock_data['Close'].pct_change().std() * 100 if len(stock_data['Close']) >= 2 else 0.0+ data_summary = f"Latest Price: ${latest:.2f}, Change: {change:.1f}%, Volatility: {vol:.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]])+ news_summary = "Recent news: " + "; ".join([item.get('title', '')[:50] for item in news[:3]]) if news else ""- insights_prompt = f"""Analyze this stock data and provide expert insights:+ insights = self.market_analyst.generate(f"""Analyze this stock data and provide expert insights:Stock: {query_info.symbol}Analysis Period: {query_info.time_period}@@ -328,9 +231,9 @@ Provide professional market insights covering:- Technical patterns observed- Market sentiment- Key risk factors-- Investment thesis"""+- Investment thesis""")- recommendations_prompt = f"""Based on the analysis of {query_info.symbol}, provide investment recommendations:+ recommendations = self.market_analyst.generate(f"""Based on the analysis of {query_info.symbol}, provide investment recommendations:Data: {data_summary}{news_summary}@@ -342,71 +245,39 @@ Provide:- Time horizon considerations- Portfolio allocation suggestions-Remember to include appropriate disclaimers."""-- insights = self.market_analyst.generate(insights_prompt)- recommendations = self.market_analyst.generate(recommendations_prompt)+Remember to include appropriate disclaimers.""")return insights, recommendationsdef analyze(self, query: str) -> AnalysisResult:- """Complete financial analysis workflow"""try:- # Parse query (may raise ValueError if no valid ticker found)try:query_info = self.parse_query(query)except Exception as e:- # Return a structured AnalysisResult indicating the input error- return AnalysisResult(- query=QueryInfo(symbol="INVALID"),- insights=f"Input error: {str(e)}",- code="# No code generated due to input error",- recommendations="Please provide a valid stock ticker in your query.",- news=[]- )+ return AnalysisResult(QueryInfo(symbol="INVALID"), f"Input error: {e}",+ "# No code generated due to input error",+ "Please provide a valid stock ticker in your query.", [])logger.info(f"Analyzing {query_info.symbol}")- # Normalize period for yfinance compatibility and fetch dataperiod = _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)if stock_data.empty:- 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.",- news=[]- )+ return AnalysisResult(query_info, "No market data could be retrieved for the provided ticker.",+ "# No code generated because historical price data is unavailable",+ "Verify the ticker symbol and try again.", [])- # Generate analysis componentscode = self.generate_code(query_info, stock_data)insights, recommendations = self.analyze_market(query_info, stock_data, news_data)- # Format news- news_items = []- for item in news_data[:3]:- news_items.append(NewsItem(- title=item.get('title', 'Market Update'),- summary=item.get('content', '')[:200],- url=item.get('url', '')- ))+ news_items = [NewsItem(item.get('title', 'Market Update'), item.get('content', '')[:200],+ item.get('url', '')) for item in news_data[:3]]- return AnalysisResult(- query=query_info,- insights=insights,- code=code,- recommendations=recommendations,- news=news_items- )+ return AnalysisResult(query_info, insights, code, recommendations, news_items)except Exception as e:logger.error(f"Error in analysis: {e}")- # Return error result- 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+ return AnalysisResult(QueryInfo(symbol="ERROR"), f"Analysis failed: {e}",+ "# Error: Unable to generate code",+ "Unable to provide recommendations due to error.")\ No newline at end of filediff --git a/finagent/main.py b/finagent/main.pyindex b527965..2528170 100644--- a/finagent/main.py+++ b/finagent/main.py@@ -1,212 +1,135 @@#!/usr/bin/env python3-"""-MCP Financial Analyst Server with Gemini AI-Using FastMCP for modern MCP server implementation-"""--import asyncio-import jsonimport loggingimport osimport sysimport tempfileimport subprocessfrom dotenv import load_dotenv-from pathlib import Path-from typing import Any, Dict, List, Optional, Sequence-from datetime import datetime+from typing import Optionallogging.basicConfig(stream=sys.stderr, level=logging.INFO)-# Load environment variables from .env fileload_dotenv()-# MCP imports - Using FastMCPtry: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")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 serverself.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 = "\n### Latest News:\n" + "\n".join(+ f"{i}. **{n.title}**\n {n.summary[:100]}...\n"+ for i, n in enumerate(result.news[:3], 1)+ ) if result.news else ""- 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}+ return f"""# Stock Analysis - {result.query.symbol}-## 💡 AI Insights+## AI Insights{result.insights}-## 📊 Analysis Code+## Analysis Code```python{result.code}```{news_section}-## 🎯 Recommendations+## Recommendations{result.recommendations}---*Powered by Gemini AI*"""- return responseexcept Exception as e:- logger.error(f"Analysis error: {str(e)}", exc_info=True)- return f"❌ Analysis Error: {str(e)}"+ logger.error(f"Analysis error: {e}", exc_info=True)+ return f"Analysis Error: {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)-"""+ exec_code = f"import sys\nimport warnings\nwarnings.filterwarnings('ignore')\n\ntry:\n{chr(10).join(' ' + line for line in code.split(chr(10)))}\nexcept Exception as e:\n print(f'Error: {{e}}')\n sys.exit(1)"with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:- f.write(execution_code)+ f.write(exec_code)temp_file = f.nametry:- # 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')+ 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```"-+ output = result.stdout or "Code executed successfully!" if result.returncode == 0 else result.stderr or 'Error'+ safe_output = ''.join(ch if ord(ch) < 0x110000 else '?' for ch in output)+ status = "Success" if result.returncode == 0 else "Error"+ return f"**{status}**\n```\n{safe_output}\n```"except subprocess.TimeoutExpired:os.unlink(temp_file)- return f"⏰ Execution timeout after {timeout}s"+ 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)}"+ return f"Execution error: {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)-+ news_data = FinancialTools().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+ return f"No news found for {symbol}"+ return f"# News for {symbol}\n\n" + "\n".join(+ f"## {i}. {item.get('title', 'Update')}\n{item.get('content', '')[:200]}{'...' if len(item.get('content', '')) > 200 else ''}\n[Read more]({item.get('url', '')})\n"+ for i, item in enumerate(news_data[:limit], 1)+ )except Exception as e:- logger.error(f"News fetch error: {str(e)}", exc_info=True)- return f"❌ News fetch error: {str(e)}"+ logger.error(f"News fetch error: {e}", exc_info=True)+ return f"News fetch error: {e}"def run(self):- """Run the MCP server"""self.mcp.run()def main():- """Initialize and run the MCP server"""+ required = ["google-generativeai", "yfinance pandas", "mcp"]+ missing = []- # Check for required packages- missing_packages = []- try:- import google.generativeai as genai- except ImportError:- missing_packages.append("google-generativeai")+ for pkg in required:+ try:+ if pkg == "google-generativeai":+ import google.generativeai+ elif pkg == "yfinance pandas":+ import yfinance, pandas+ else:+ from mcp.server.fastmcp import FastMCP+ except ImportError:+ missing.append(pkg)- try:- import yfinance as yf- import pandas as pd- except ImportError:- missing_packages.append("yfinance pandas")-- 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)+ if missing:+ print(f"Missing packages: {', '.join(missing)}\nInstall with: pip install {' '.join(missing)}", 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)+ print("GEMINI_API_KEY required. Get one from: https://makersuite.google.com/app/apikey", file=sys.stderr)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 servertry:- server = FinancialAnalysisServer(gemini_api_key, firecrawl_api_key)- logger.info(f"✅ Financial Analysis Server initialized successfully")+ server = FinancialAnalysisServer(gemini_api_key, os.getenv('FIRECRAWL_API_KEY'))+ logger.info("Financial Analysis Server initialized successfully")server.run()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)+ print(f"Failed to start server: {e}", file=sys.stderr)+ logger.error(f"Server startup error: {e}", exc_info=True)sys.exit(1)if __name__ == "__main__":- main()#!/usr/bin/env python3+ main()\ No newline at end of file