Skip to content

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

updated files

Avikumar Talaviya90159a01ca1b
diff --git a/Financial analyst using agno and GPT-OSS coder/.env b/Financial analyst using agno and GPT-OSS coder/.env
index e69de29..c393972 100644
--- a/Financial analyst using agno and GPT-OSS coder/.env
+++ b/Financial analyst using agno and GPT-OSS coder/.env
@@ -0,0 +1,3 @@
+FIRECRAWL_API_KEY=your_firecrawl_api_key_here
+OLLAMA_BASE_URL=http://localhost:11434
+GPT_OSS_MODEL=gpt-oss
\ No newline at end of file
diff --git a/Financial analyst using agno and GPT-OSS coder/README.md b/Financial analyst using agno and GPT-OSS coder/README.md
index e69de29..60c7081 100644
--- a/Financial analyst using agno and GPT-OSS coder/README.md
+++ b/Financial analyst using agno and GPT-OSS coder/README.md
@@ -0,0 +1,395 @@
+# MCP Financial Analyst with Agno Framework Setup Guide
+
+This guide will help you set up the enhanced MCP-powered Financial Analyst that uses the Agno agentic framework with GPT-OSS model and Firecrawl for news integration.
+
+## πŸ—οΈ Architecture Overview
+
+### File Structure
+```
+financial-analyst-agno/
+β”œβ”€β”€ financial_agents.py # Agentic system (separate file)
+β”œβ”€β”€ mcp_financial_main.py # Main MCP server
+β”œβ”€β”€ requirements.txt # Dependencies
+β”œβ”€β”€ .env # Environment variables
+└── financial_analysis_agno_output/ # Generated output directory
+```
+
+### Agent System Components
+1. **Query Parser Agent**: Converts natural language to structured queries
+2. **Code Generator Agent**: Creates executable Python analysis code
+3. **Market Analyst Agent**: Provides market insights and recommendations
+4. **Financial Tools**: Integrates Firecrawl for news and market data
+
+## πŸ“‹ Prerequisites
+
+### 1. Install Ollama and GPT-OSS
+```bash
+# Install Ollama
+curl -fsSL https://ollama.com/install.sh | sh
+
+# Pull GPT-OSS model
+ollama pull gpt-oss
+
+# Verify installation
+ollama list
+```
+
+### 2. Get Firecrawl API Key (Optional)
+1. Visit [Firecrawl](https://firecrawl.dev)
+2. Sign up for an account
+3. Get your API key from the dashboard
+4. Store it securely for configuration
+
+## πŸš€ Installation
+
+### 1. Install Python Dependencies
+```bash
+pip install mcp pandas matplotlib yfinance requests pydantic agno firecrawl-py
+```
+
+### 2. Create Environment File
+Create a `.env` file in your project directory:
+```env
+FIRECRAWL_API_KEY=your_firecrawl_api_key_here
+OLLAMA_BASE_URL=http://localhost:11434
+GPT_OSS_MODEL=gpt-oss
+```
+
+### 3. Create Requirements File
+```txt
+# requirements.txt
+mcp>=1.0.0
+pandas>=2.0.0
+matplotlib>=3.7.0
+yfinance>=0.2.0
+requests>=2.30.0
+pydantic>=2.0.0
+agno>=0.1.0
+firecrawl-py>=0.0.8
+python-dotenv>=1.0.0
+```
+
+## βš™οΈ Configuration
+
+### For Claude Desktop
+
+**Location:**
+- **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
+- **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
+
+**Configuration:**
+```json
+{
+ "mcpServers": {
+ "financial-analyst-agno": {
+ "command": "python",
+ "args": ["/absolute/path/to/mcp_financial_main.py"],
+ "env": {
+ "FIRECRAWL_API_KEY": "your_api_key_here",
+ "OLLAMA_BASE_URL": "http://localhost:11434"
+ }
+ }
+ }
+}
+```
+
+### For Cursor IDE
+
+1. Go to: **File β†’ Preferences β†’ Cursor Settings β†’ MCP**
+2. Add new global MCP server:
+
+```json
+{
+ "mcpServers": {
+ "financial-analyst-agno": {
+ "command": "python",
+ "args": ["/absolute/path/to/mcp_financial_main.py"],
+ "env": {
+ "FIRECRAWL_API_KEY": "your_api_key_here"
+ }
+ }
+ }
+}
+```
+
+## 🎯 Usage Examples
+
+### Basic Stock Analysis
+```
+Analyze Tesla stock performance over the last 3 months with market news
+```
+
+### Technical Analysis with Multiple Indicators
+```
+Show me Apple vs Microsoft comparison with SMA and RSI indicators for 1 year
+```
+
+### News-Focused Analysis
+```
+Get latest news and sentiment analysis for NVIDIA stock with price trends
+```
+
+### Comprehensive Investment Report
+```
+Generate a complete investment analysis for Amazon including risk assessment
+```
+
+## πŸ”§ Available Tools
+
+### 1. `analyze_stock_with_agents`
+**Purpose**: Complete multi-agent financial analysis
+- **Input**: Natural language query
+- **Process**:
+ 1. Query Parser Agent structures the request
+ 2. Market Analyst Agent gathers insights
+ 3. Code Generator Agent creates analysis code
+ 4. News integration via Firecrawl
+- **Output**: Comprehensive analysis with code, insights, and recommendations
+
+### 2. `save_analysis_code`
+**Purpose**: Save generated code with metadata
+- **Features**:
+ - Automatic timestamping
+ - Metadata preservation
+ - Organized file structure
+ - Code headers with generation info
+
+### 3. `execute_analysis_code`
+**Purpose**: Secure code execution with visualization
+- **Security**: Sandboxed execution environment
+- **Timeout**: Configurable execution limits
+- **Output**: Execution results and error handling
+
+### 4. `get_market_news`
+**Purpose**: Real-time news fetching with Firecrawl
+- **Sources**: Multiple financial websites
+- **Processing**: Content extraction and summarization
+- **Integration**: Sentiment analysis with stock data
+
+### 5. `generate_investment_report`
+**Purpose**: Comprehensive PDF-ready reports
+- **Format**: Professional investment analysis format
+- **Content**: Executive summary, methodology, recommendations
+- **Export**: Ready for external use
+
+## πŸ€– Agent System Details
+
+### Query Parser Agent
+```python
+# Specialized in financial terminology
+# Converts: "Show me Apple stock trends with moving averages"
+# To: StockQuery(symbol="AAPL", analysis_type="trend", indicators=["sma"])
+```
+
+### Code Generator Agent
+```python
+# Creates production-ready analysis code
+# Features: Error handling, professional visualizations, metrics calculation
+# Libraries: yfinance, pandas, matplotlib, numpy
+```
+
+### Market Analyst Agent
+```python
+# Provides expert-level insights
+# Analysis: Technical patterns, market sentiment, risk assessment
+# Integration: News sentiment, economic indicators
+```
+
+## πŸ“Š Enhanced Features
+
+### Multi-Agent Collaboration
+- **Parallel Processing**: Agents work simultaneously
+- **Specialization**: Each agent has specific expertise
+- **Quality Control**: Cross-validation between agents
+
+### Real-Time Data Integration
+- **Live Market Data**: Yahoo Finance integration
+- **News Scraping**: Firecrawl web scraping
+- **Sentiment Analysis**: AI-powered news sentiment
+
+### Advanced Code Generation
+- **Professional Quality**: Production-ready code
+- **Error Handling**: Comprehensive error management
+- **Visualization**: Advanced matplotlib charts
+- **Metrics**: Financial KPIs and risk measures
+
+## πŸ› οΈ Troubleshooting
+
+### Common Issues and Solutions
+
+#### 1. "GPT-OSS model not found"
+```bash
+# Solution
+ollama list
+ollama pull gpt-oss
+ollama serve
+```
+
+#### 2. "Agno import error"
+```bash
+# Solution
+pip install agno
+# Or try development version
+pip install git+https://github.com/agno-framework/agno.git
+```
+
+#### 3. "Firecrawl authentication failed"
+```bash
+# Check API key
+echo $FIRECRAWL_API_KEY
+
+# Set environment variable
+export FIRECRAWL_API_KEY="your_key_here"
+```
+
+#### 4. "MCP server connection failed"
+- Verify file paths in configuration
+- Check Python environment
+- Review Claude Desktop/Cursor logs
+
+### Performance Optimization
+
+#### 1. Model Performance
+```bash
+# Allocate more resources to Ollama
+OLLAMA_NUM_PARALLEL=4 ollama serve
+```
+
+#### 2. News Fetching Limits
+```python
+# Adjust in financial_agents.py
+news_items = self.tools.get_stock_news(symbol, limit=3) # Reduce limit
+```
+
+#### 3. Execution Timeout
+```python
+# Increase timeout for complex analysis
+await self.execute_analysis_code(code, timeout=60)
+```
+
+## πŸ” Security Considerations
+
+### Code Execution Safety
+- **Sandboxed Environment**: Isolated execution
+- **Timeout Protection**: Prevents infinite loops
+- **Resource Limits**: Memory and CPU constraints
+- **File System Protection**: Limited file access
+
+### API Key Security
+- **Environment Variables**: Never hardcode keys
+- **File Permissions**: Secure .env files
+- **Network Security**: HTTPS-only connections
+
+## πŸ“ˆ Advanced Configuration
+
+### Custom Agent Behavior
+```python
+# Modify in financial_agents.py
+class CustomMarketAnalyst(MarketAnalystAgent):
+ def analyze_stock(self, query, news_data):
+ # Custom analysis logic
+ return super().analyze_stock(query, news_data)
+```
+
+### Extended News Sources
+```python
+# Add more news sources in FinancialTools
+news_urls = [
+ f"https://finance.yahoo.com/quote/{symbol}/news/",
+ f"https://www.marketwatch.com/investing/stock/{symbol}",
+ f"https://www.bloomberg.com/quote/{symbol}:US", # New source
+ f"https://www.reuters.com/companies/{symbol}" # New source
+]
+```
+
+### Custom Technical Indicators
+```python
+# Extend indicators in CodeGeneratorAgent
+def add_custom_indicators(self, data):
+ # Bollinger Bands
+ data['BB_upper'] = data['Close'].rolling(20).mean() + 2*data['Close'].rolling(20).std()
+ data['BB_lower'] = data['Close'].rolling(20).mean() - 2*data['Close'].rolling(20).std()
+ return data
+```
+
+## πŸ“š Integration Examples
+
+### With Jupyter Notebooks
+```python
+from financial_agents import FinancialAnalysisTeam
+
+# Initialize team
+team = FinancialAnalysisTeam(firecrawl_api_key="your_key")
+
+# Run analysis
+result = team.analyze("Analyze TSLA stock with news integration")
+
+# Execute generated code
+exec(result.code)
+```
+
+### With FastAPI Backend
+```python
+from fastapi import FastAPI
+from financial_agents import FinancialAnalysisTeam
+
+app = FastAPI()
+team = FinancialAnalysisTeam()
+
[email protected]("/analyze")
+async def analyze_stock(query: str):
+ result = team.analyze(query)
+ return result.dict()
+```
+
+### With Streamlit Dashboard
+```python
+import streamlit as st
+from financial_agents import FinancialAnalysisTeam
+
+st.title("AI Financial Analyst")
+query = st.text_input("Enter your analysis query:")
+
+if query:
+ team = FinancialAnalysisTeam()
+ result = team.analyze(query)
+ st.code(result.code)
+ st.write(result.insights)
+```
+
+## πŸŽ“ Best Practices
+
+### 1. Query Formulation
+- **Be Specific**: "AAPL 6-month trend analysis with SMA"
+- **Include Timeframes**: Always specify time periods
+- **Mention Indicators**: Request specific technical indicators
+- **Multiple Symbols**: "Compare TSLA vs F stock performance"
+
+### 2. Code Execution
+- **Review First**: Always review generated code
+- **Test Incrementally**: Run small parts first
+- **Monitor Resources**: Watch CPU and memory usage
+- **Save Results**: Use save_analysis_code tool
+
+### 3. News Integration
+- **API Limits**: Be mindful of Firecrawl rate limits
+- **Relevance**: Focus on recent, relevant news
+- **Verification**: Cross-check news sentiment with data
+
+## 🀝 Support and Community
+
+### Getting Help
+- **Documentation**: Check agent docstrings and comments
+- **Logs**: Review application logs for debugging
+- **GitHub Issues**: Report bugs and feature requests
+- **Community**: Join AI/ML finance communities
+
+### Contributing
+- **Code**: Submit PRs for improvements
+- **Agents**: Create new specialized agents
+- **Tools**: Add new financial data sources
+- **Documentation**: Improve guides and examples
+
+---
+
+*Powered by Agno Framework, GPT-OSS, and Firecrawl for next-generation financial analysis*
\ No newline at end of file
diff --git a/Financial analyst using agno and GPT-OSS coder/financial_agents.py b/Financial analyst using agno and GPT-OSS coder/financial_agents.py
index e69de29..c4f97ee 100644
--- a/Financial analyst using agno and GPT-OSS coder/financial_agents.py
+++ b/Financial analyst using agno and GPT-OSS coder/financial_agents.py
@@ -0,0 +1,594 @@
+#!/usr/bin/env python3
+
+"""
+Financial Analysis Agents using Agno Framework with GPT-OSS
+Separate agentic logic for the MCP financial analyst
+"""
+
+import json
+import logging
+import requests
+from datetime import datetime, timedelta
+from typing import Any, Dict, List, Optional
+from pydantic import BaseModel, Field
+
+# Firecrawl imports
+try:
+ from firecrawl import FirecrawlApp
+except ImportError:
+ print("Firecrawl not installed. Install with: pip install firecrawl-py")
+
+# Agno imports
+try:
+ from agno import Agent, Team
+ from agno.llm.ollama import OllamaLLM
+ from agno.tools import Tool
+except ImportError:
+ print("Agno not installed. Install with: pip install agno")
+
+logger = logging.getLogger(__name__)
+
+# Pydantic models
+class StockQuery(BaseModel):
+ """Structured stock query model"""
+ symbol: str = Field(..., description="Stock ticker symbol")
+ analysis_type: str = Field(..., description="Type of analysis")
+ time_period: str = Field(default="1y", description="Time period")
+ additional_symbols: Optional[List[str]] = Field(default=None)
+ indicators: Optional[List[str]] = Field(default=None)
+
+class MarketNews(BaseModel):
+ """Market news structure"""
+ title: str
+ summary: str
+ url: str
+ published: str
+ relevance_score: float
+
+class AnalysisResult(BaseModel):
+ """Complete analysis result"""
+ query: StockQuery
+ code: str
+ insights: str
+ news: List[MarketNews]
+ recommendations: str
+
+class GPTOSSInterface:
+ """Interface to GPT-OSS model via Ollama"""
+
+ def __init__(self, model_name: str = "gpt-oss", base_url: str = "http://localhost:11434"):
+ self.model_name = model_name
+ self.base_url = base_url
+
+ def query(self, prompt: str, system_prompt: str = "", **kwargs) -> str:
+ """Query GPT-OSS model"""
+ try:
+ payload = {
+ "model": self.model_name,
+ "prompt": prompt,
+ "system": system_prompt,
+ "stream": False,
+ "options": {
+ "temperature": kwargs.get("temperature", 0.1),
+ "top_p": kwargs.get("top_p", 0.9),
+ "num_ctx": kwargs.get("num_ctx", 4096)
+ }
+ }
+
+ response = requests.post(
+ f"{self.base_url}/api/generate",
+ json=payload,
+ timeout=60
+ )
+ response.raise_for_status()
+
+ result = response.json()
+ return result.get("response", "")
+
+ except Exception as e:
+ logger.error(f"Error querying GPT-OSS: {e}")
+ return f"Error: {str(e)}"
+
+class FinancialTools:
+ """Financial analysis tools for agents"""
+
+ def __init__(self, firecrawl_api_key: Optional[str] = None):
+ self.firecrawl = None
+ if firecrawl_api_key:
+ self.firecrawl = FirecrawlApp(api_key=firecrawl_api_key)
+
+ def get_stock_news(self, symbol: str, limit: int = 5) -> List[Dict]:
+ """Fetch recent news for a stock using Firecrawl"""
+ try:
+ if not self.firecrawl:
+ return []
+
+ # Search for news on financial websites
+ news_urls = [
+ f"https://finance.yahoo.com/quote/{symbol}/news/",
+ f"https://www.marketwatch.com/investing/stock/{symbol}",
+ f"https://seekingalpha.com/symbol/{symbol}/news"
+ ]
+
+ news_items = []
+ for url in news_urls[:2]: # Limit to avoid rate limits
+ try:
+ result = self.firecrawl.scrape_url(
+ url,
+ params={
+ "formats": ["markdown"],
+ "onlyMainContent": True
+ }
+ )
+
+ if result and result.get('markdown'):
+ news_items.append({
+ 'url': url,
+ 'content': result['markdown'][:1000], # Limit content
+ 'title': f"Latest {symbol} News"
+ })
+
+ except Exception as e:
+ logger.warning(f"Failed to scrape {url}: {e}")
+ continue
+
+ return news_items
+
+ except Exception as e:
+ logger.error(f"Error fetching news: {e}")
+ return []
+
+ def get_market_data(self, symbol: str) -> Dict:
+ """Get basic market data (fallback if yfinance not available)"""
+ try:
+ if not self.firecrawl:
+ return {}
+
+ url = f"https://finance.yahoo.com/quote/{symbol}"
+ result = self.firecrawl.scrape_url(
+ url,
+ params={
+ "formats": ["markdown"],
+ "onlyMainContent": True
+ }
+ )
+
+ if result and result.get('markdown'):
+ return {
+ 'symbol': symbol,
+ 'data': result['markdown'][:500],
+ 'source': url
+ }
+
+ except Exception as e:
+ logger.error(f"Error fetching market data: {e}")
+
+ return {}
+
+class QueryParserAgent:
+ """Agent for parsing natural language queries"""
+
+ def __init__(self, gpt_interface: GPTOSSInterface):
+ self.gpt = gpt_interface
+
+ # Create Agno agent
+ self.agent = Agent(
+ name="Query Parser",
+ role="Financial Query Analyzer",
+ goal="Parse natural language financial queries into structured format",
+ backstory="Expert in understanding financial terminology and extracting structured data from user requests",
+ llm=self._create_ollama_llm(),
+ verbose=True
+ )
+
+ def _create_ollama_llm(self):
+ """Create Ollama LLM interface for Agno"""
+ try:
+ return OllamaLLM(
+ model="gpt-oss",
+ base_url="http://localhost:11434"
+ )
+ except:
+ # Fallback to direct interface
+ return None
+
+ def parse_query(self, user_query: str) -> StockQuery:
+ """Parse natural language query"""
+ system_prompt = """You are a financial query parser. Extract structured information from user queries.
+
+ Return ONLY a valid JSON object with these fields:
+ - symbol: main stock ticker symbol (uppercase)
+ - analysis_type: one of [price, trend, comparison, forecast, performance, news]
+ - time_period: one of [1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max]
+ - additional_symbols: array of additional ticker symbols if mentioned
+ - indicators: array of technical indicators if requested [sma, ema, rsi, macd, bollinger]"""
+
+ prompt = f"""Parse this financial query into structured JSON: "{user_query}"
+
+ Examples:
+ Query: "Show me Apple stock performance over 6 months"
+ Output: {{"symbol": "AAPL", "analysis_type": "performance", "time_period": "6mo"}}
+
+ Query: "Compare Tesla vs Ford with moving averages"
+ Output: {{"symbol": "TSLA", "analysis_type": "comparison", "time_period": "1y", "additional_symbols": ["F"], "indicators": ["sma"]}}"""
+
+ response = self.gpt.query(prompt, system_prompt, temperature=0.1)
+
+ try:
+ # Extract JSON from response
+ import re
+ json_match = re.search(r'\{.*\}', response, re.DOTALL)
+ if json_match:
+ data = json.loads(json_match.group())
+ return StockQuery(**data)
+ except Exception as e:
+ logger.warning(f"Failed to parse structured query: {e}")
+
+ # Fallback parsing
+ return self._fallback_parse(user_query)
+
+ def _fallback_parse(self, query: str) -> StockQuery:
+ """Fallback parsing logic"""
+ query_upper = query.upper()
+
+ # Common stock symbols
+ symbols = ["AAPL", "MSFT", "GOOGL", "AMZN", "TSLA", "NVDA", "META", "NFLX", "F"]
+ symbol = "AAPL" # default
+
+ for sym in symbols:
+ if sym in query_upper:
+ symbol = sym
+ break
+
+ # Analysis type detection
+ analysis_type = "price"
+ if any(word in query_upper for word in ["COMPARE", "VS", "VERSUS"]):
+ analysis_type = "comparison"
+ elif any(word in query_upper for word in ["TREND", "TRENDING"]):
+ analysis_type = "trend"
+ elif any(word in query_upper for word in ["NEWS", "LATEST"]):
+ analysis_type = "news"
+ elif any(word in query_upper for word in ["FORECAST", "PREDICT"]):
+ analysis_type = "forecast"
+
+ # Time period detection
+ time_period = "1y"
+ if "6 MONTH" in query_upper or "6MO" in query_upper:
+ time_period = "6mo"
+ elif "3 MONTH" in query_upper or "3MO" in query_upper:
+ time_period = "3mo"
+ elif "1 MONTH" in query_upper or "1MO" in query_upper:
+ time_period = "1mo"
+ elif "2 YEAR" in query_upper or "2Y" in query_upper:
+ time_period = "2y"
+
+ return StockQuery(
+ symbol=symbol,
+ analysis_type=analysis_type,
+ time_period=time_period
+ )
+
+class CodeGeneratorAgent:
+ """Agent for generating Python analysis code"""
+
+ def __init__(self, gpt_interface: GPTOSSInterface):
+ self.gpt = gpt_interface
+
+ self.agent = Agent(
+ name="Code Generator",
+ role="Python Financial Code Developer",
+ goal="Generate clean, executable Python code for financial analysis",
+ backstory="Senior Python developer specializing in financial data analysis with pandas, matplotlib, and yfinance",
+ llm=self._create_ollama_llm(),
+ verbose=True
+ )
+
+ def _create_ollama_llm(self):
+ """Create Ollama LLM interface"""
+ try:
+ return OllamaLLM(model="gpt-oss", base_url="http://localhost:11434")
+ except:
+ return None
+
+ def generate_code(self, query: StockQuery, news_data: List[Dict] = None) -> str:
+ """Generate Python code for analysis"""
+
+ system_prompt = """You are a senior Python developer creating financial analysis code.
+
+ Requirements:
+ - Use yfinance for data fetching
+ - Use pandas for data manipulation
+ - Use matplotlib for visualization
+ - Include error handling
+ - Create professional-looking plots
+ - Add proper titles, labels, and legends
+ - Return clean, executable code without markdown formatting"""
+
+ news_context = ""
+ if news_data:
+ news_context = f"\nRecent news context: {json.dumps([n.get('title', '') for n in news_data[:2]])}"
+
+ prompt = f"""Generate Python code for this financial analysis:
+
+ Symbol: {query.symbol}
+ Analysis Type: {query.analysis_type}
+ Time Period: {query.time_period}
+ Additional Symbols: {query.additional_symbols or []}
+ Technical Indicators: {query.indicators or []}
+ {news_context}
+
+ Code requirements:
+ 1. Fetch data using yfinance
+ 2. Create meaningful visualizations
+ 3. Calculate relevant metrics
+ 4. Handle errors gracefully
+ 5. Include comments explaining the analysis
+ 6. Use proper plot formatting with titles and labels
+
+ Return only the Python code, no explanations or markdown."""
+
+ code = self.gpt.query(prompt, system_prompt, temperature=0.2)
+
+ # Clean the response
+ return self._clean_code_response(code, query)
+
+ def _clean_code_response(self, response: str, query: StockQuery) -> str:
+ """Clean and validate code response"""
+ lines = response.split('\n')
+ clean_lines = []
+ in_code_block = False
+
+ for line in lines:
+ if '```python' in line.lower():
+ in_code_block = True
+ continue
+ elif '```' in line and in_code_block:
+ break
+ elif line.strip():
+ # Keep lines that look like Python code
+ if (in_code_block or
+ line.startswith('import ') or
+ line.startswith('from ') or
+ any(keyword in line for keyword in ['yf.', 'plt.', 'pd.', 'np.']) or
+ line.startswith(' ') or # Indented lines
+ '=' in line or
+ line.startswith('#')):
+ clean_lines.append(line)
+
+ if clean_lines:
+ return '\n'.join(clean_lines)
+
+ # Fallback code generation
+ return self._generate_fallback_code(query)
+
+ def _generate_fallback_code(self, query: StockQuery) -> str:
+ """Generate fallback code if AI generation fails"""
+ additional_plots = ""
+ if query.additional_symbols:
+ for symbol in query.additional_symbols[:2]: # Limit to 2 additional
+ additional_plots += f"""
+# Add {symbol} for comparison
+{symbol.lower()}_data = yf.Ticker('{symbol}').history(period='{query.time_period}')
+if not {symbol.lower()}_data.empty:
+ plt.plot({symbol.lower()}_data.index, {symbol.lower()}_data['Close'],
+ linewidth=2, label='{symbol} Close Price')
+"""
+
+ indicators_code = ""
+ if query.indicators:
+ if 'sma' in [i.lower() for i in query.indicators]:
+ indicators_code += """
+# Simple Moving Average
+data['SMA_20'] = data['Close'].rolling(window=20).mean()
+plt.plot(data.index, data['SMA_20'], '--', label='SMA 20', alpha=0.7)
+"""
+
+ return f"""
+import yfinance as yf
+import pandas as pd
+import matplotlib.pyplot as plt
+from datetime import datetime, timedelta
+import numpy as np
+
+try:
+ # Fetch stock data
+ print(f"Fetching data for {query.symbol}...")
+ ticker = yf.Ticker('{query.symbol}')
+ data = ticker.history(period='{query.time_period}')
+
+ if data.empty:
+ print(f"No data available for {query.symbol}")
+ exit()
+
+ # Create visualization
+ plt.figure(figsize=(14, 8))
+
+ # Main stock price
+ plt.subplot(2, 1, 1)
+ plt.plot(data.index, data['Close'], linewidth=2, label=f'{query.symbol} Close Price', color='blue')
+ {additional_plots}
+ {indicators_code}
+
+ plt.title(f'{query.symbol} Stock Analysis - {query.analysis_type.title()} ({query.time_period.upper()})', fontsize=16)
+ plt.xlabel('Date')
+ plt.ylabel('Price ($)')
+ plt.legend()
+ plt.grid(True, alpha=0.3)
+
+ # Volume subplot
+ plt.subplot(2, 1, 2)
+ plt.bar(data.index, data['Volume'], alpha=0.7, color='gray', label='Volume')
+ plt.title('Trading Volume')
+ plt.xlabel('Date')
+ plt.ylabel('Volume')
+ plt.legend()
+ plt.grid(True, alpha=0.3)
+
+ plt.tight_layout()
+ plt.show()
+
+ # Calculate metrics
+ current_price = data['Close'].iloc[-1]
+ start_price = data['Close'].iloc[0]
+ total_return = ((current_price / start_price) - 1) * 100
+ volatility = data['Close'].pct_change().std() * np.sqrt(252) * 100
+
+ print(f"\\n=== {query.symbol} Analysis Results ===")
+ print(f"Period: {query.time_period.upper()}")
+ print(f"Start Price: ${start_price:.2f}")
+ print(f"Current Price: ${current_price:.2f}")
+ print(f"Total Return: {total_return:.2f}%")
+ print(f"Annualized Volatility: {volatility:.2f}%")
+ print(f"Average Volume: {data['Volume'].mean():,.0f}")
+
+except Exception as e:
+ print(f"Error in analysis: {{e}}")
+ print("Please check the stock symbol and try again.")
+""".strip()
+
+class MarketAnalystAgent:
+ """Agent for market analysis and insights"""
+
+ def __init__(self, gpt_interface: GPTOSSInterface, tools: FinancialTools):
+ self.gpt = gpt_interface
+ self.tools = tools
+
+ self.agent = Agent(
+ name="Market Analyst",
+ role="Financial Market Expert",
+ goal="Provide comprehensive market insights and analysis",
+ backstory="Experienced financial analyst with deep knowledge of market trends, technical analysis, and economic indicators",
+ llm=self._create_ollama_llm(),
+ verbose=True
+ )
+
+ def _create_ollama_llm(self):
+ """Create Ollama LLM interface"""
+ try:
+ return OllamaLLM(model="gpt-oss", base_url="http://localhost:11434")
+ except:
+ return None
+
+ def analyze_stock(self, query: StockQuery, news_data: List[Dict] = None) -> str:
+ """Generate market insights"""
+
+ news_summary = ""
+ if news_data:
+ news_items = [item.get('content', '')[:200] for item in news_data[:3]]
+ news_summary = f"\n\nRecent News Context:\n" + "\n".join(f"- {item}" for item in news_items if item)
+
+ system_prompt = """You are a professional financial analyst providing market insights.
+
+ Provide analysis covering:
+ - Current market sentiment
+ - Technical outlook
+ - Key factors affecting the stock
+ - Risk assessment
+ - Investment considerations
+
+ Keep insights concise but informative (200-300 words)."""
+
+ prompt = f"""Provide market analysis for {query.symbol} stock:
+
+ Analysis Focus: {query.analysis_type}
+ Time Period: {query.time_period}
+ Comparison Stocks: {query.additional_symbols or 'None'}
+ Technical Indicators: {query.indicators or 'None'}
+ {news_summary}
+
+ Include:
+ 1. Current market position assessment
+ 2. Technical analysis perspective
+ 3. Key catalysts or concerns
+ 4. Risk factors to consider
+ 5. Brief outlook summary"""
+
+ insights = self.gpt.query(prompt, system_prompt, temperature=0.3)
+
+ return insights
+
+class FinancialAnalysisTeam:
+ """Orchestrate the financial analysis team using Agno"""
+
+ def __init__(self, firecrawl_api_key: Optional[str] = None):
+ self.gpt_interface = GPTOSSInterface()
+ self.tools = FinancialTools(firecrawl_api_key)
+
+ # Initialize agents
+ self.query_parser = QueryParserAgent(self.gpt_interface)
+ self.code_generator = CodeGeneratorAgent(self.gpt_interface)
+ self.market_analyst = MarketAnalystAgent(self.gpt_interface, self.tools)
+
+ logger.info("Financial Analysis Team initialized with GPT-OSS and Firecrawl")
+
+ def analyze(self, user_query: str) -> AnalysisResult:
+ """Perform complete financial analysis"""
+ try:
+ # Step 1: Parse the query
+ logger.info(f"Parsing query: {user_query}")
+ parsed_query = self.query_parser.parse_query(user_query)
+
+ # Step 2: Gather news and market data
+ logger.info(f"Gathering news for {parsed_query.symbol}")
+ news_data = self.tools.get_stock_news(parsed_query.symbol)
+
+ # Step 3: Generate analysis code
+ logger.info("Generating analysis code")
+ analysis_code = self.code_generator.generate_code(parsed_query, news_data)
+
+ # Step 4: Generate market insights
+ logger.info("Generating market insights")
+ market_insights = self.market_analyst.analyze_stock(parsed_query, news_data)
+
+ # Step 5: Generate recommendations
+ recommendations = self._generate_recommendations(parsed_query, market_insights)
+
+ # Step 6: Format news data
+ formatted_news = []
+ for news_item in news_data[:3]:
+ formatted_news.append(MarketNews(
+ title=news_item.get('title', 'Market News'),
+ summary=news_item.get('content', '')[:200],
+ url=news_item.get('url', ''),
+ published=datetime.now().isoformat(),
+ relevance_score=0.8
+ ))
+
+ return AnalysisResult(
+ query=parsed_query,
+ code=analysis_code,
+ insights=market_insights,
+ news=formatted_news,
+ recommendations=recommendations
+ )
+
+ except Exception as e:
+ logger.error(f"Error in analysis: {e}")
+ # Return minimal result on error
+ return AnalysisResult(
+ query=StockQuery(symbol="AAPL", analysis_type="price"),
+ code="# Error generating code",
+ insights=f"Error in analysis: {str(e)}",
+ news=[],
+ recommendations="Please check the query and try again."
+ )
+
+ def _generate_recommendations(self, query: StockQuery, insights: str) -> str:
+ """Generate investment recommendations"""
+ system_prompt = """Generate brief investment recommendations based on the analysis.
+ Include risk level and key actionable points. Keep it concise (100-150 words)."""
+
+ prompt = f"""Based on this analysis for {query.symbol}:
+
+ Analysis Type: {query.analysis_type}
+ Market Insights: {insights[:300]}...
+
+ Provide investment recommendations including:
+ 1. Risk assessment (Low/Medium/High)
+ 2. Key action items
+ 3. Timeline considerations
+ 4. Important disclaimers"""
+
+ recommendations = self.gpt_interface.query(prompt, system_prompt, temperature=0.2)
+
+ return recommendations + "\n\n⚠️ Disclaimer: This is not financial advice. Consult with a financial advisor before making investment decisions."
\ No newline at end of file
diff --git a/Financial analyst using agno and GPT-OSS coder/main.py b/Financial analyst using agno and GPT-OSS coder/main.py
index e69de29..f6fd4bb 100644
--- a/Financial analyst using agno and GPT-OSS coder/main.py
+++ b/Financial analyst using agno and GPT-OSS coder/main.py
@@ -0,0 +1,553 @@
+#!/usr/bin/env python3
+
+"""
+MCP Financial Analyst Server with Agno Framework and Firecrawl
+Main server file that integrates with the separate agentic system
+"""
+
+import asyncio
+import json
+import logging
+import os
+import sys
+import tempfile
+import subprocess
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Sequence
+from datetime import datetime
+
+# MCP imports
+try:
+ from mcp.server.models import InitializationOptions
+ from mcp.server import NotificationOptions, Server
+ from mcp.types import (
+ CallToolRequestParams,
+ ListToolsRequestParams,
+ Tool,
+ TextContent,
+ ImageContent,
+ EmbeddedResource,
+ )
+ import mcp.types as types
+except ImportError:
+ print("MCP not installed. Install with: pip install mcp")
+ sys.exit(1)
+
+# Import our agentic system
+try:
+ from financial_agents import FinancialAnalysisTeam, AnalysisResult
+except ImportError:
+ print("financial_agents.py not found. Make sure it's in the same directory.")
+ sys.exit(1)
+
+# Configure logging
+logging.basicConfig(level=logging.INFO)
+logger = logging.getLogger("mcp-financial-agno")
+
+class MCPFinancialServer:
+ """MCP Server for Financial Analysis using Agno Framework"""
+
+ def __init__(self, firecrawl_api_key: Optional[str] = None):
+ self.server = Server("financial-analyst-agno-gpt-oss")
+
+ # Initialize the agentic team
+ logger.info("Initializing Financial Analysis Team with Agno Framework...")
+ self.analysis_team = FinancialAnalysisTeam(firecrawl_api_key)
+
+ self.setup_handlers()
+ logger.info("MCP Financial Server initialized with Agno agents and Firecrawl")
+
+ def setup_handlers(self):
+ """Setup MCP server handlers"""
+
+ @self.server.list_tools()
+ async def handle_list_tools() -> List[Tool]:
+ return [
+ Tool(
+ name="analyze_stock_with_agents",
+ description="Comprehensive stock analysis using Agno agents with GPT-OSS model and Firecrawl news integration",
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": "Natural language query about stock analysis (e.g., 'Analyze AAPL performance over 6 months with news')"
+ }
+ },
+ "required": ["query"]
+ }
+ ),
+ Tool(
+ name="save_analysis_code",
+ description="Save generated analysis code to local directory with metadata",
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "code": {"type": "string", "description": "Python code to save"},
+ "filename": {"type": "string", "description": "Filename (optional)"},
+ "metadata": {"type": "object", "description": "Additional metadata about the analysis"}
+ },
+ "required": ["code"]
+ }
+ ),
+ Tool(
+ name="execute_analysis_code",
+ description="Execute Python analysis code in a secure environment and generate plots",
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "code": {"type": "string", "description": "Python code to execute"},
+ "timeout": {"type": "number", "description": "Execution timeout in seconds (default: 30)"}
+ },
+ "required": ["code"]
+ }
+ ),
+ Tool(
+ name="get_market_news",
+ description="Fetch latest market news using Firecrawl for specific stocks",
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "symbol": {"type": "string", "description": "Stock symbol (e.g., AAPL)"},
+ "limit": {"type": "number", "description": "Number of news articles to fetch (default: 5)"}
+ },
+ "required": ["symbol"]
+ }
+ ),
+ Tool(
+ name="generate_investment_report",
+ description="Generate comprehensive investment report with recommendations",
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "analysis_result": {"type": "string", "description": "JSON string of previous analysis result"},
+ "include_charts": {"type": "boolean", "description": "Whether to include chart generation code"}
+ },
+ "required": ["analysis_result"]
+ }
+ )
+ ]
+
+ @self.server.call_tool()
+ async def handle_call_tool(name: str, arguments: Dict[str, Any]) -> Sequence[types.TextContent | types.ImageContent | types.EmbeddedResource]:
+ if name == "analyze_stock_with_agents":
+ return await self.analyze_stock_with_agents(arguments.get("query", ""))
+ elif name == "save_analysis_code":
+ return await self.save_analysis_code(
+ arguments.get("code", ""),
+ arguments.get("filename"),
+ arguments.get("metadata", {})
+ )
+ elif name == "execute_analysis_code":
+ return await self.execute_analysis_code(
+ arguments.get("code", ""),
+ arguments.get("timeout", 30)
+ )
+ elif name == "get_market_news":
+ return await self.get_market_news(
+ arguments.get("symbol", ""),
+ arguments.get("limit", 5)
+ )
+ elif name == "generate_investment_report":
+ return await self.generate_investment_report(
+ arguments.get("analysis_result", ""),
+ arguments.get("include_charts", True)
+ )
+ else:
+ return [TextContent(type="text", text=f"Unknown tool: {name}")]
+
+ async def analyze_stock_with_agents(self, query: str) -> Sequence[types.TextContent]:
+ """Comprehensive stock analysis using Agno agents"""
+ try:
+ logger.info(f"Starting agentic analysis for query: {query}")
+
+ # Run the analysis using our agent team
+ result: AnalysisResult = self.analysis_team.analyze(query)
+
+ # Format the comprehensive result
+ news_section = ""
+ if result.news:
+ news_section = "### πŸ“° Latest Market News:\n"
+ for i, news_item in enumerate(result.news[:3], 1):
+ news_section += f"{i}. **{news_item.title}**\n"
+ news_section += f" {news_item.summary}...\n"
+ news_section += f" [Read more]({news_item.url})\n\n"
+
+ formatted_result = f"""# πŸ“ˆ Comprehensive Financial Analysis
+
+## 🎯 Query Analysis
+**Symbol:** {result.query.symbol}
+**Analysis Type:** {result.query.analysis_type.title()}
+**Time Period:** {result.query.time_period.upper()}
+**Additional Symbols:** {', '.join(result.query.additional_symbols) if result.query.additional_symbols else 'None'}
+**Technical Indicators:** {', '.join(result.query.indicators) if result.query.indicators else 'None'}
+
+## πŸ’‘ Market Insights (GPT-OSS Analysis)
+{result.insights}
+
+## πŸ“Š Generated Analysis Code
+```python
+{result.code}
+```
+
+{news_section}
+
+## 🎯 Investment Recommendations
+{result.recommendations}
+
+## πŸ”§ Next Steps
+1. **Save Code**: Use `save_analysis_code` tool to save the generated code locally
+2. **Execute Analysis**: Use `execute_analysis_code` tool to run the code and generate visualizations
+3. **Generate Report**: Use `generate_investment_report` tool for a comprehensive PDF-ready report
+4. **Get Updates**: Use `get_market_news` tool for the latest news updates
+
+---
+*Analysis powered by Agno Framework with GPT-OSS model and Firecrawl news integration*
+"""
+
+ return [TextContent(type="text", text=formatted_result)]
+
+ except Exception as e:
+ logger.error(f"Error in agentic analysis: {e}")
+ return [TextContent(type="text", text=f"❌ Error in analysis: {str(e)}\n\nPlease check that:\n- Ollama is running with gpt-oss model\n- Firecrawl API key is configured (if using news features)\n- All dependencies are installed")]
+
+ async def save_analysis_code(self, code: str, filename: Optional[str] = None, metadata: Dict = None) -> Sequence[types.TextContent]:
+ """Save analysis code with metadata"""
+ try:
+ if not filename:
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ filename = f"agno_financial_analysis_{timestamp}.py"
+
+ # Create output directory
+ output_dir = Path.cwd() / "financial_analysis_agno_output"
+ output_dir.mkdir(exist_ok=True)
+
+ code_file = output_dir / filename
+
+ # Add header to the code
+ header = f"""#!/usr/bin/env python3
+\"\"\"
+Financial Analysis Code Generated by Agno Framework
+Generated: {datetime.now().isoformat()}
+Agent System: GPT-OSS + Firecrawl
+Metadata: {json.dumps(metadata or {}, indent=2)}
+\"\"\"
+
+"""
+
+ with open(code_file, 'w') as f:
+ f.write(header + code)
+
+ # Save metadata separately
+ if metadata:
+ metadata_file = output_dir / f"{filename.replace('.py', '_metadata.json')}"
+ with open(metadata_file, 'w') as f:
+ json.dump({
+ 'generated_at': datetime.now().isoformat(),
+ 'filename': filename,
+ 'agent_system': 'Agno Framework + GPT-OSS',
+ 'features': 'Firecrawl news integration',
+ **metadata
+ }, f, indent=2)
+
+ return [TextContent(type="text", text=f"βœ… Code saved successfully!\n\nπŸ“ **Location**: {code_file}\nπŸ“„ **Filename**: {filename}\nπŸ—‚οΈ **Directory**: {output_dir}\n\n{f'πŸ“‹ **Metadata**: Saved to {filename.replace(\".py\", \"_metadata.json\")}' if metadata else ''}")]
+
+ except Exception as e:
+ logger.error(f"Error saving code: {e}")
+ return [TextContent(type="text", text=f"❌ Error saving code: {str(e)}")]
+
+ async def execute_analysis_code(self, code: str, timeout: int = 30) -> Sequence[types.TextContent]:
+ """Execute analysis code in secure environment"""
+ try:
+ logger.info("Executing analysis code in secure environment")
+
+ # Create temporary file with proper imports
+ execution_code = f"""
+import sys
+import warnings
+warnings.filterwarnings('ignore')
+
+# Add error handling wrapper
+try:
+{chr(10).join(' ' + line for line in code.split(chr(10)))}
+except Exception as e:
+ print(f"Execution Error: {{e}}")
+ sys.exit(1)
+"""
+
+ with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
+ f.write(execution_code)
+ temp_file = f.name
+
+ # Execute with timeout
+ result = subprocess.run([
+ sys.executable, temp_file
+ ], capture_output=True, text=True, timeout=timeout, cwd=Path.cwd())
+
+ # Clean up
+ os.unlink(temp_file)
+
+ if result.returncode == 0:
+ output = result.stdout if result.stdout else "Code executed successfully! Check for generated plots."
+ warnings = f"\n⚠️ **Warnings:**\n```\n{result.stderr}\n```" if result.stderr else ""
+
+ execution_summary = f"""βœ… **Execution Successful!**
+
+πŸ“Š **Output:**
+```
+{output}
+```{warnings}
+
+🎯 **Status**: Analysis completed successfully
+⏱️ **Execution Time**: Within {timeout} seconds
+πŸ–ΌοΈ **Plots**: Check for generated matplotlib windows or saved plot files
+"""
+ return [TextContent(type="text", text=execution_summary)]
+ else:
+ error_details = f"""❌ **Execution Failed!**
+
+🚨 **Error Details:**
+```
+{result.stderr}
+```
+
+πŸ” **Troubleshooting Tips:**
+1. Check if all required packages are installed (yfinance, pandas, matplotlib)
+2. Verify internet connection for data fetching
+3. Ensure stock symbols are valid
+4. Check for any syntax errors in the generated code
+
+πŸ’‘ **Suggestion**: Try regenerating the code with a simpler query or check the error message above.
+"""
+ return [TextContent(type="text", text=error_details)]
+
+ except subprocess.TimeoutExpired:
+ return [TextContent(type="text", text=f"⏰ **Execution Timeout!**\n\nThe analysis took longer than {timeout} seconds to complete.\n\nπŸ’‘ **Solutions:**\n- Increase timeout value\n- Simplify the analysis query\n- Check network connection for data fetching")]
+
+ except Exception as e:
+ logger.error(f"Error executing code: {e}")
+ return [TextContent(type="text", text=f"❌ **Execution Error**: {str(e)}\n\nPlease check the code and try again.")]
+
+ async def get_market_news(self, symbol: str, limit: int = 5) -> Sequence[types.TextContent]:
+ """Fetch latest market news using Firecrawl"""
+ try:
+ logger.info(f"Fetching market news for {symbol}")
+
+ # Use the tools from our agent system
+ news_data = self.analysis_team.tools.get_stock_news(symbol, limit)
+
+ if not news_data:
+ return [TextContent(type="text", text=f"πŸ“° **Market News for {symbol}**\n\n⚠️ No recent news available or Firecrawl not configured.\n\nπŸ’‘ **Note**: To enable news fetching, provide a Firecrawl API key when starting the server.")]
+
+ news_formatted = f"# πŸ“° Latest Market News for {symbol}\n\n"
+
+ for i, news_item in enumerate(news_data[:limit], 1):
+ news_formatted += f"## {i}. {news_item.get('title', 'Market Update')}\n\n"
+ news_formatted += f"πŸ“… **Source**: {news_item.get('url', 'N/A')}\n\n"
+
+ content = news_item.get('content', '')
+ if len(content) > 300:
+ content = content[:300] + "..."
+ news_formatted += f"πŸ“ **Summary**: {content}\n\n"
+ news_formatted += "---\n\n"
+
+ news_formatted += f"*Powered by Firecrawl - Real-time web scraping for financial news*"
+
+ return [TextContent(type="text", text=news_formatted)]
+
+ except Exception as e:
+ logger.error(f"Error fetching news: {e}")
+ return [TextContent(type="text", text=f"❌ **Error fetching news**: {str(e)}\n\nPlease check your Firecrawl API key and internet connection.")]
+
+ async def generate_investment_report(self, analysis_result_json: str, include_charts: bool = True) -> Sequence[types.TextContent]:
+ """Generate comprehensive investment report"""
+ try:
+ logger.info("Generating comprehensive investment report")
+
+ # Parse the analysis result if provided as JSON string
+ if analysis_result_json.strip():
+ try:
+ analysis_data = json.loads(analysis_result_json)
+ except:
+ analysis_data = {"symbol": "Unknown", "analysis_type": "general"}
+ else:
+ analysis_data = {"symbol": "Unknown", "analysis_type": "general"}
+
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+
+ report = f"""# πŸ“‹ Investment Analysis Report
+
+**Generated**: {timestamp}
+**Powered by**: Agno Framework + GPT-OSS + Firecrawl
+**Report Type**: Comprehensive Financial Analysis
+
+---
+
+## πŸ“Š Executive Summary
+
+This report provides a comprehensive analysis of the requested financial instrument(s) using advanced AI agents powered by the GPT-OSS model and real-time news integration via Firecrawl.
+
+### Key Highlights:
+- **AI-Powered Analysis**: Multi-agent system with specialized roles
+- **Real-time Data**: Live market data and news integration
+- **Technical Analysis**: Advanced charting and indicator analysis
+- **Risk Assessment**: Comprehensive risk evaluation
+- **Actionable Insights**: Clear recommendations and next steps
+
+---
+
+## πŸ€– Agent System Overview
+
+### Query Parser Agent
+- **Role**: Natural language processing
+- **Function**: Convert user queries into structured analysis parameters
+- **Technology**: GPT-OSS model with specialized prompts
+
+### Code Generator Agent
+- **Role**: Python code generation
+- **Function**: Create executable analysis scripts with proper error handling
+- **Libraries**: yfinance, pandas, matplotlib, numpy
+
+### Market Analyst Agent
+- **Role**: Market insights and recommendations
+- **Function**: Provide expert-level market analysis and investment guidance
+- **Data Sources**: Historical data, technical indicators, news sentiment
+
+---
+
+## πŸ“ˆ Analysis Methodology
+
+### 1. Data Collection
+- **Primary Source**: Yahoo Finance via yfinance library
+- **News Integration**: Real-time news scraping with Firecrawl
+- **Technical Indicators**: SMA, EMA, RSI, MACD, Bollinger Bands
+
+### 2. AI-Powered Processing
+- **Model**: GPT-OSS (locally hosted via Ollama)
+- **Framework**: Agno multi-agent orchestration
+- **Approach**: Collaborative analysis with specialized agents
+
+### 3. Visualization & Reporting
+- **Charts**: Professional matplotlib visualizations
+- **Metrics**: Key performance indicators and risk measures
+- **Format**: Code generation for reproducible analysis
+
+---
+
+## 🎯 Investment Framework
+
+### Risk Categories
+- **Low Risk**: Blue-chip stocks, established companies
+- **Medium Risk**: Growth stocks, sector-specific investments
+- **High Risk**: Volatile stocks, emerging markets
+
+### Analysis Dimensions
+1. **Technical Analysis**: Price patterns, volume, indicators
+2. **Fundamental Factors**: Company performance, market position
+3. **Market Sentiment**: News analysis, social indicators
+4. **Risk Assessment**: Volatility, correlation, sector risks
+
+---
+
+## πŸ”§ Usage Instructions
+
+### 1. Running Analysis
+```bash
+# Ensure Ollama is running with GPT-OSS
+ollama serve
+ollama pull gpt-oss
+
+# Run the MCP server
+python mcp_financial_main.py
+```
+
+### 2. Available Tools
+- `analyze_stock_with_agents`: Complete multi-agent analysis
+- `save_analysis_code`: Save generated code with metadata
+- `execute_analysis_code`: Run analysis in secure environment
+- `get_market_news`: Fetch latest news with Firecrawl
+- `generate_investment_report`: Create comprehensive reports
+
+### 3. Integration Options
+- **Claude Desktop**: Full MCP integration
+- **Cursor IDE**: Development environment integration
+- **Command Line**: Direct Python execution
+
+---
+
+## ⚠️ Important Disclaimers
+
+1. **Not Financial Advice**: This analysis is for informational purposes only
+2. **AI Limitations**: AI-generated insights should be verified with human expertise
+3. **Data Accuracy**: Market data may have delays or inaccuracies
+4. **Risk Warning**: All investments carry risk of loss
+5. **Professional Consultation**: Consult licensed financial advisors for investment decisions
+
+---
+
+## πŸ“ž Technical Support
+
+### Dependencies
+```bash
+pip install mcp pandas matplotlib yfinance requests pydantic agno firecrawl-py
+```
+
+### Configuration Files
+- MCP Server: `mcp_financial_main.py`
+- Agent System: `financial_agents.py`
+- Output Directory: `./financial_analysis_agno_output/`
+
+### Troubleshooting
+1. **Ollama Issues**: Ensure GPT-OSS model is loaded
+2. **Firecrawl Errors**: Check API key configuration
+3. **MCP Connection**: Verify Claude Desktop/Cursor setup
+4. **Code Execution**: Check Python environment and dependencies
+
+---
+
+*Report generated by MCP Financial Analyst with Agno Framework*
+*Β© 2025 - Powered by GPT-OSS, Firecrawl, and Agno Multi-Agent System*
+"""
+
+ if include_charts:
+ report += f"\n\n## πŸ“Š Chart Generation Code\n\n```python\n# Use the 'execute_analysis_code' tool with generated analysis code\n# Charts will be displayed in matplotlib windows\n```"
+
+ return [TextContent(type="text", text=report)]
+
+ except Exception as e:
+ logger.error(f"Error generating report: {e}")
+ return [TextContent(type="text", text=f"❌ **Error generating report**: {str(e)}")]
+
+async def main():
+ """Main function to run the MCP server"""
+ # Get Firecrawl API key from environment
+ firecrawl_api_key = os.getenv('FIRECRAWL_API_KEY')
+
+ if not firecrawl_api_key:
+ logger.warning("FIRECRAWL_API_KEY not found in environment. News features will be limited.")
+
+ server_instance = MCPFinancialServer(firecrawl_api_key)
+
+ async with server_instance.server.run_stdio() as server:
+ await server.initialize(InitializationOptions())
+ logger.info("πŸš€ MCP Financial Analyst Server with Agno Framework started!")
+ logger.info("πŸ“Š Features: GPT-OSS model, Firecrawl news integration, Multi-agent analysis")
+ await asyncio.Event().wait() # Run forever
+
+if __name__ == "__main__":
+ asyncio.run(main())
+
+# End of MCP Financial Analyst Server with Agno Framework
+# Make sure to run this script with Python 3.8+ and all dependencies installed.
+# Use the command: python main.py
+# Ensure Ollama is running with the gpt-oss model for full functionality.
+# For Firecrawl news features, set the FIRECRAWL_API_KEY environment variable.
+# Example: export FIRECRAWL_API_KEY='your_api_key_here'
+# This server integrates with Claude Desktop and Cursor IDE for enhanced user experience.
+# For any issues, check the logs or refer to the documentation.
+# Β© 2025 - Powered by Agno Framework, GPT-OSS, and Firecrawl
+# License: MIT License
+# This code is open source and can be modified under the terms of the MIT License.
+# Contributions are welcome! Please follow the contribution guidelines in the repository.
+# For more information, visit the project repository on GitHub.
+# Thank you for using the MCP Financial Analyst Server with Agno Framework!
\ No newline at end of file
diff --git a/Financial analyst using agno and GPT-OSS coder/requirements.txt b/Financial analyst using agno and GPT-OSS coder/requirements.txt
index dfeddcb..a8180b8 100644
--- a/Financial analyst using agno and GPT-OSS coder/requirements.txt
+++ b/Financial analyst using agno and GPT-OSS coder/requirements.txt
@@ -1,8 +1,9 @@
-mcp
-pandas
-matplotlib
-yfinance
-requests
-pydantic
-
-
+mcp>=1.0.0
+pandas>=2.0.0
+matplotlib>=3.7.0
+yfinance>=0.2.0
+requests>=2.30.0
+pydantic>=2.0.0
+agno>=0.1.0
+firecrawl-py>=0.0.8
+python-dotenv>=1.0.0
\ No newline at end of file