Skip to content

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

compeleted financial analysis

PankajKumar23108e22bd6c3acd
diff --git a/Financial analyst using agno and GPT-OSS coder/.env b/Financial analyst using agno and GPT-OSS coder/.env
deleted file mode 100644
index c393972..0000000
--- a/Financial analyst using agno and GPT-OSS coder/.env
+++ /dev/null
@@ -1,3 +0,0 @@
-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
deleted file mode 100644
index 60c7081..0000000
--- a/Financial analyst using agno and GPT-OSS coder/README.md
+++ /dev/null
@@ -1,395 +0,0 @@
-# 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
deleted file mode 100644
index 8f5a130..0000000
--- a/Financial analyst using agno and GPT-OSS coder/financial_agents.py
+++ /dev/null
@@ -1,605 +0,0 @@
-#!/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 for stock analysis and query parsing
-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
-
-# ---------------------------------------------------****-----------------------------------------------------
-# GPT-OSS Interface for model inference
-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)}"
-# ---------------------------------------------------****-----------------------------------------------------
-# set all the financial tools
-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 {}
-
-# ---------------------------------------------------****-----------------------------------------------------
-# Query Parser Agent
-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
- )
-
-# ---------------------------------------------------****-----------------------------------------------------
-# Code generation agent for financial analysis
-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()
-
-# ---------------------------------------------------****-----------------------------------------------------
-# market analysis agent
-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
-
-# ---------------------------------------------------****-----------------------------------------------------
-# FINAL CLASS FOR THE INTERACTION OF ALL AGENTS WITH THE SERVER AND USER QUERY
-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 d4a474f..a331470 100644
--- a/Financial analyst using agno and GPT-OSS coder/main.py
+++ b/Financial analyst using agno and GPT-OSS coder/main.py
@@ -72,7 +72,7 @@ class MCPFinancialServer:
"properties": {
"query": {
"type": "string",
- "description": "Natural language query about stock analysis (e.g., 'Analyze AAPL performance over 6 months with news')"
+ "description": "Natural language query about stock analysis (e.g., 'Analyze <TICKER> performance over 6 months with news')"
}
},
"required": ["query"]
@@ -109,7 +109,7 @@ class MCPFinancialServer:
inputSchema={
"type": "object",
"properties": {
- "symbol": {"type": "string", "description": "Stock symbol (e.g., AAPL)"},
+ "symbol": {"type": "string", "description": "Stock symbol (replace with desired ticker)"},
"limit": {"type": "number", "description": "Number of news articles to fetch (default: 5)"}
},
"required": ["symbol"]
diff --git a/Financial analyst using agno and GPT-OSS coder/requirements.txt b/Financial analyst using agno and GPT-OSS coder/requirements.txt
deleted file mode 100644
index a8180b8..0000000
--- a/Financial analyst using agno and GPT-OSS coder/requirements.txt
+++ /dev/null
@@ -1,9 +0,0 @@
-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
diff --git a/finagent/.env b/finagent/.env
new file mode 100644
index 0000000..b76708c
--- /dev/null
+++ b/finagent/.env
@@ -0,0 +1,2 @@
+GEMINI_API_KEY=AIzaSyCVx0yZQ5uFhifY_eTy9ChPxmCc3ZjjhTw
+FIRECRAWL_API_KEY=fc-159693bb0bd34c4599588f97dd6583cd
diff --git a/finagent/.vscode/launch.json b/finagent/.vscode/launch.json
new file mode 100644
index 0000000..ab4ce7d
--- /dev/null
+++ b/finagent/.vscode/launch.json
@@ -0,0 +1,26 @@
+{
+ "version": "0.2.0",
+ "configurations": [
+ {
+ "name": "Run MCP Financial Server",
+ "type": "python",
+ "request": "launch",
+ "program": "${workspaceFolder}/mcp_financial_main.py",
+ "console": "integratedTerminal",
+ "envFile": "${workspaceFolder}/.env",
+ "env": {
+ "GEMINI_API_KEY": "AIzaSyCVx0yZQ5uFhifY_eTy9ChPxmCc3ZjjhTw",
+ "FIRECRAWL_API_KEY": "fc-159693bb0bd34c4599588f97dd6583cd"
+ },
+ "cwd": "${workspaceFolder}"
+ },
+ {
+ "name": "Test Financial Analysis",
+ "type": "python",
+ "request": "launch",
+ "program": "${workspaceFolder}/test_analysis.py",
+ "console": "integratedTerminal",
+ "envFile": "${workspaceFolder}/.env"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/finagent/README.md b/finagent/README.md
new file mode 100644
index 0000000..0164cc4
--- /dev/null
+++ b/finagent/README.md
@@ -0,0 +1,205 @@
+# Finagent - AI-Powered Financial Analysis Tool
+
+A sophisticated financial analysis system that leverages Google's Gemini AI and real-time market data to provide comprehensive stock analysis, automated code generation, and investment insights.
+
+## Features
+
+- **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
+- **Professional Visualizations**: Generates matplotlib charts and technical analysis plots
+- **Risk Assessment**: Provides balanced investment recommendations with proper disclaimers
+
+## Prerequisites
+
+- Python 3.8+
+- Google Gemini API key
+- Firecrawl API key (optional, for enhanced news features)
+
+## File Structure
+
+```
+finagent/
+β”œβ”€β”€ main.py # MCP server entry point
+β”œβ”€β”€ financial_agents.py # Core AI agents and analysis logic
+β”œβ”€β”€ .env # Environment variables (create this)
+β”œβ”€β”€ .env.example # Environment variables template
+β”œβ”€β”€ requirements.txt # Python dependencies
+β”œβ”€β”€ README.md # This file
+└── logs/ # Log files (auto-created)
+```
+
+## Installation
+
+1. **Clone the repository**:
+
+```bash
+git clone <your-repo-url>
+cd finagent
+```
+
+2. **Install required packages**:
+
+```bash
+pip install google-generativeai yfinance pandas matplotlib numpy mcp python-dotenv
+```
+
+3. **Set up environment variables**:
+ Create a `.env` file in the project root:
+
+```env
+GEMINI_API_KEY=your_gemini_api_key_here
+FIRECRAWL_API_KEY=your_firecrawl_api_key_here # Optional
+```
+
+## API Keys Setup
+
+### Gemini API Key (Required)
+
+1. Visit [Google AI Studio](https://makersuite.google.com/app/apikey)
+2. Create a new API key
+3. Add it to your `.env` file
+
+### Firecrawl API Key (Optional)
+
+1. Sign up at [Firecrawl](https://firecrawl.dev)
+2. Get your API key from the dashboard
+3. Add it to your `.env` file for enhanced news features
+
+## Usage
+
+### As MCP Server
+
+Start the MCP server:
+
+```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
+)
+
+# Analyze a stock
+result = team.analyze("Analyze Apple stock over the last 6 months")
+
+print(f"Insights: {result.insights}")
+print(f"Recommendations: {result.recommendations}")
+print(f"Generated Code:\n{result.code}")
+```
+
+## Example Queries
+
+The system understands natural language queries:
+
+- "Analyze Tesla stock performance over the last 3 months"
+- "Compare Apple and Microsoft stocks this year"
+- "Technical analysis of NVDA with RSI and MACD indicators"
+- "What's the current sentiment on Bitcoin?"
+
+## 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
+
+### Agent Specialization
+
+- **Query Parser**: Extracts symbols, timeframes, and analysis requirements
+- **Code Generator**: Creates executable Python analysis scripts
+- **Market Analyst**: Provides professional investment insights and recommendations
+
+## Generated Analysis Includes
+
+- **Technical Indicators**: RSI, MACD, Moving averages, Bollinger bands
+- **Price Analysis**: Trend analysis, support/resistance levels
+- **Risk Metrics**: Volatility calculations, drawdown analysis
+- **Visualizations**: Professional charts with technical overlays
+- **News Integration**: Latest market sentiment and news impact
+- **Investment Recommendations**: Buy/Hold/Sell with rationale
+
+## Important Disclaimers
+
+- This tool is for educational and research purposes only
+- All analysis and recommendations are not financial advice
+- Always consult with qualified financial advisors before making investment decisions
+- Past performance does not guarantee future results
+
+## Troubleshooting
+
+### Common Issues
+
+1. **Import Errors**: Ensure all dependencies are installed
+
+```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. **Data Fetching Errors**: Check internet connection and ticker symbol validity
+
+4. **Code Execution Timeout**: Large datasets may require increased timeout values
+
+## Contributing
+
+1. Fork the repository
+2. Create a feature branch (`git checkout -b feature/amazing-feature`)
+3. Commit your changes (`git commit -m 'Add amazing feature'`)
+4. Push to the branch (`git push origin feature/amazing-feature`)
+5. Open a Pull Request
+
+## License
+
+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:
+
+- Open an issue on GitHub
+- Check the troubleshooting section above
+- Review the example queries for proper usage patterns
+
+---
+
+**Made with care using Google Gemini AI**
diff --git a/finagent/__pycache__/financial_agents.cpython-313.pyc b/finagent/__pycache__/financial_agents.cpython-313.pyc
new file mode 100644
index 0000000..1c14e10
Binary files /dev/null and b/finagent/__pycache__/financial_agents.cpython-313.pyc differ
diff --git a/finagent/financial_agents.py b/finagent/financial_agents.py
new file mode 100644
index 0000000..731141f
--- /dev/null
+++ b/finagent/financial_agents.py
@@ -0,0 +1,412 @@
+#!/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
+
+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)
+ raise
+
+logger = logging.getLogger(__name__)
+
+@dataclass
+class QueryInfo:
+ symbol: str
+ analysis_type: str = "comprehensive"
+ time_period: str = "6m"
+ 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
+ insights: str
+ code: str
+ 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"""
+ try:
+ ticker = yf.Ticker(symbol)
+ return ticker.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
+ 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"""
+ 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
+ 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
+
+class 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 = 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"""
+ try:
+ full_prompt = f"{self.system_prompt}\n\nUser Request: {prompt}"
+ response = self.model.generate_content(
+ full_prompt,
+ safety_settings=self.safety_settings,
+ generation_config=genai.types.GenerationConfig(
+ temperature=0.7,
+ 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)}"
+
+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:
+- Stock symbol (primary focus)
+- Analysis type (technical, fundamental, comprehensive)
+- Time period (1d, 1w, 1m, 3m, 6m, 1y, 2y)
+- Additional symbols for comparison
+- Technical indicators requested
+
+Return a JSON object with: symbol, analysis_type, time_period, additional_symbols, indicators.
+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:
+- yfinance for data
+- pandas for analysis
+- matplotlib for visualization
+- numpy for calculations
+
+Requirements:
+- Include proper imports
+- Add error handling
+- Create informative plots
+- Use professional styling
+- Include data validation
+- Add comments explaining key sections
+
+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:
+- 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."""
+ )
+
+ def parse_query(self, query: str) -> QueryInfo:
+ """Parse natural language query"""
+ 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}")
+
+ 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")
+
+ # If model didn't provide valid JSON, fall back to heuristic extraction + yfinance validation
+ 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.")
+
+ 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": []}
+
+ # 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", [])
+ )
+ 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"""
+ prompt = f"""Generate Python code for financial analysis:
+
+Stock: {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
+
+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:
+ """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}%"
+ 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:
+
+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"""
+
+ 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
+
+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"""
+ 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=[]
+ )
+
+ logger.info(f"Analyzing {query_info.symbol}")
+ # Normalize period for yfinance compatibility and 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)
+
+ 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=[]
+ )
+
+ # Generate analysis components
+ code = 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', '')
+ ))
+
+ return AnalysisResult(
+ query=query_info,
+ insights=insights,
+ code=code,
+ recommendations=recommendations,
+ news=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
diff --git a/finagent/main.py b/finagent/main.py
new file mode 100644
index 0000000..b527965
--- /dev/null
+++ b/finagent/main.py
@@ -0,0 +1,212 @@
+#!/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
+
+logging.basicConfig(stream=sys.stderr, level=logging.INFO)
+# Load environment variables from .env file
+load_dotenv()
+
+# MCP imports - Using FastMCP
+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)
+ 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 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
+{result.code}
+```
+{news_section}
+## 🎯 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)
+"""
+
+ 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")
+
+ 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)
+ 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)
+ 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
+ try:
+ server = FinancialAnalysisServer(gemini_api_key, firecrawl_api_key)
+ logger.info(f"βœ… 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)
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()#!/usr/bin/env python3
diff --git a/finagent/requirements.txt b/finagent/requirements.txt
new file mode 100644
index 0000000..cdf3f28
--- /dev/null
+++ b/finagent/requirements.txt
@@ -0,0 +1,7 @@
+google-generativeai>=0.3.0
+mcp>=0.1.0
+yfinance>=0.2.18
+pandas>=1.5.0
+numpy>=1.21.0
+matplotlib>=3.5.0
+python-dotenv>=0.19.0
\ No newline at end of file
diff --git a/multi_agent_financial_analyst/financial_analyst.py b/multi_agent_financial_analyst/financial_analyst.py
index 748d5a1..f7eba00 100644
--- a/multi_agent_financial_analyst/financial_analyst.py
+++ b/multi_agent_financial_analyst/financial_analyst.py
@@ -184,8 +184,8 @@ with st.sidebar:
# Stock Symbol input
symbol = st.text_input(
"Stock Symbol",
- value="AAPL",
- help="Enter a stock symbol (e.g., AAPL, GOOGL)"
+ value="",
+ help="Enter a stock symbol (for example: TSLA or MSFT). Provide a single ticker symbol to analyze."
).upper()
# Analysis button
@@ -198,10 +198,13 @@ if "analysis_complete" not in st.session_state:
if analyze_button:
try:
- with st.spinner(f'Analyzing {symbol}... This may take a few minutes.'):
- # Create and run the crew
- crew = create_agents_and_tasks(symbol)
- result = crew.kickoff()
+ if not symbol:
+ st.error("Please enter a valid stock symbol before running the analysis.")
+ else:
+ with st.spinner(f'Analyzing {symbol}... This may take a few minutes.'):
+ # Create and run the crew
+ crew = create_agents_and_tasks(symbol)
+ result = crew.kickoff()
# Convert the CrewOutput to string if needed
if hasattr(result, 'raw'):
st.session_state.report = result.raw