A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.
Update: finagent financial agents
Tiioluwania85e5f9704fe
diff --git a/finagent/.env.example b/finagent/.env.examplenew file mode 100644index 0000000..3cac181--- /dev/null+++ b/finagent/.env.example@@ -0,0 +1 @@+OPENAI_API_KEY=your_openai_api_key_herediff --git a/finagent/.gitignore b/finagent/.gitignorenew file mode 100644index 0000000..6801b16--- /dev/null+++ b/finagent/.gitignore@@ -0,0 +1,5 @@+.env+__pycache__/+venv/+.DS_Store+*.pycdiff --git a/finagent/README.md b/finagent/README.mdindex 140d8a3..3e7fa55 100644--- a/finagent/README.md+++ b/finagent/README.md@@ -1,294 +1,36 @@-# Finagent - AI-Powered Financial Analysis Tool+# Financial Analyst (FastMCP Server)-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.+A high-performance financial analysis tool that exposes deep market insights via the Model Context Protocol (MCP). It allows other AI tools (or the terminal) to query real-time stock data using natural language.-## Features+## Principal Functionalities+- **Natural Language Analysis**: Ask questions like "Is Apple a good buy right now?" or "Compare Nvidia and AMD's recent trends" without needing to write code.+- **High-Speed Execution**: Optimized to deliver professional financial reports in under 20 seconds using streamlined `yfinance` data streams.+- **Model Context Protocol (MCP)**: Built with **FastMCP**, allowing this analyst to be plugged directly into any MCP-compatible environment as a specialized tool.+- **Professional Assessment**: Provides technical levels, market trends, and risk factors in a structured, institutional-grade format.-- **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-- **MCP Server**: Modern Model Context Protocol server for Claude Desktop integration-- **Professional Visualizations**: Generates matplotlib charts and technical analysis plots-- **Risk Assessment**: Provides balanced investment recommendations with proper disclaimers+## Technical Context+- **Infrastructure**: **FastMCP** for tool definition and transport.+- **Intelligence**: OpenAI `gpt-4o-mini` for fast, concise financial reasoning.+- **Data Source**: Optimized `yfinance` historical price engine.-## Prerequisites--- Python 3.8+-- Google Gemini API key-- Claude Desktop (for MCP integration)-- 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--## Claude Desktop Integration--### Setup MCP Server with Claude Desktop--1. **Install Claude Desktop**:-- - Download from [Claude.ai](https://claude.ai/download)- - Install and launch the application--2. **Configure MCP Server**:-- Locate your Claude Desktop config file:-- - **MacOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`- - **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`--3. **Add Finagent Server**:-- Edit the config file and add:-- ```json- {- "mcpServers": {- "financial-analyst": {- "command": "python",- "args": ["/absolute/path/to/finagent/main.py"],- "env": {- "GEMINI_API_KEY": "your_gemini_api_key_here",- "FIRECRAWL_API_KEY": "your_firecrawl_api_key_here"- }- }- }- }- ```-- Replace `/absolute/path/to/finagent/main.py` with the actual path to your main.py file.--4. **Restart Claude Desktop**:-- - Quit Claude Desktop completely- - Relaunch the application- - The MCP server should now be available--5. **Verify Connection**:-- In Claude Desktop, you should see the financial analysis tools available. Ask Claude:-- ```- Can you analyze Apple stock for me?- ```--### Available Tools in Claude Desktop--Once configured, Claude can use these tools:--- **analyze_stock**: Get comprehensive stock analysis with AI insights-- **execute_code**: Run generated Python analysis code-- **get_news**: Fetch latest market news for stocks--### Example Conversations with Claude Desktop--```-You: Analyze Tesla stock performance over the last 6 months--Claude: I'll analyze Tesla stock for you using the financial analysis tool...-[Uses analyze_stock tool]-```--```-You: What's the latest news on NVDA?--Claude: Let me fetch the latest news for NVIDIA...-[Uses get_news tool]-```--```-You: Can you execute this analysis code for me?--Claude: I'll run that code using the execution tool...-[Uses execute_code tool]-```--## Usage--### As MCP Server (Standalone)--Start the MCP server manually:--```bash-python main.py-```--### Direct Python Usage--```python-from financial_agents import FinancialAnalysisTeam--team = FinancialAnalysisTeam(- gemini_api_key="your_gemini_key",- firecrawl_api_key="your_firecrawl_key"-)--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?"-- "Show me the latest news for Amazon stock"--## Architecture--### Core Components--1. **FinancialAnalysisTeam**: Main orchestrator class-2. **GeminiAgent**: Base agent class using Gemini AI-3. **FinancialTools**: Data acquisition utilities-4. **MCP Server**: Model Context Protocol server for Claude Desktop--### 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. **MCP Server Not Showing in Claude Desktop**:-- - Verify the config file path is correct- - Check that Python path in config is valid- - Ensure main.py path is absolute, not relative- - Restart Claude Desktop completely--2. **Import Errors**:+## Setup & Execution+### 1. Requirements+This tool runs within the shared repository environment. Ensure dependencies are met:```bash-pip install google-generativeai yfinance pandas mcp python-dotenv+pip install -r requirements.txt```-3. **API Key Issues**:-- - Verify your `.env` file is in the project root- - Check API keys are valid and properly formatted- - Ensure environment variables are set in Claude Desktop config--4. **Data Fetching Errors**:-- - Check internet connection- - Verify ticker symbol validity- - Yahoo Finance may have rate limits--5. **Code Execution Timeout**:- - Large datasets may require increased timeout values- - Check for infinite loops in generated code--### Debug Mode--To enable detailed logging:+### 2. Environment+The server automatically loads your `OPENAI_API_KEY` from the root `.env` file.+### 3. Launch```bash-export LOG_LEVEL=DEBUGpython main.py```-## Security--- Never commit API keys to version control-- Use environment variables for all sensitive configuration-- Regularly rotate API keys-- Monitor API usage and costs-- Keep Claude Desktop config file secure--## Contributing--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.--## 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 Google Gemini AI & Claude Desktop**+## How to Use+Once the server is running (Stdio transport), you can interact with the `analyze_stock` tool. It is designed to interpret a wide variety of financial queries:+- "Analyze TSLA and give me the key technical levels"+- "Give me a risk assessment for Microsoft"+- "Should I hold or sell Nvidia based on the last month?"diff --git a/finagent/financial_agents.py b/finagent/financial_agents.pyindex 4f293e8..dd8693d 100644--- a/finagent/financial_agents.py+++ b/finagent/financial_agents.py@@ -1,103 +1,43 @@import os-import re-import json-import yfinance as yf-import google.generativeai as genai--def _normalize_period(period: str) -> str:- if not period:- return '6mo'- p = str(period).strip().lower()- m = re.match(r'^(\d+)(m|mo|y|d|w)$', p)- if m:- num, unit = m.group(1), m.group(2)- if unit == 'm':- unit = 'mo'- return f"{num}{unit}"- return p---class GeminiAgent:- def __init__(self, api_key: str, role: str, system_prompt: str):- genai.configure(api_key=api_key)- self.model = genai.GenerativeModel('gemini-2.5-flash')- self.role = role- self.system_prompt = system_prompt-- def generate(self, prompt: str) -> str:- full_prompt = f"{self.system_prompt}\n\nUser Request: {prompt}"- response = self.model.generate_content(full_prompt)- return response.text---class FinancialTools:- def get_stock_data(self, symbol: str, period: str = "6mo"):- ticker = yf.Ticker(symbol)- return ticker.history(period=period)---class FinancialAnalysisTeam:- def __init__(self, gemini_api_key: str):- self.tools = FinancialTools()- self.query_parser = GeminiAgent(- gemini_api_key,- "Query Parser",- """You are a financial query parser. Extract from the user query:-- Stock symbol (ticker)-- Analysis type (technical, fundamental, comprehensive)-- Time period (like 1d, 1mo, 6mo, 1y)-Return a JSON object with keys: symbol, analysis_type, time_period."""- )- self.market_analyst = GeminiAgent(- gemini_api_key,- "Market Analyst",- """You are a senior financial analyst. Provide a clear, professional, and actionable analysis for the stock.-Include market trends, price action, risk assessment and investment recommendations."""- )-- def parse_query(self, query: str):- response = self.query_parser.generate(query)- try:- json_match = re.search(r"\{.*\}", response, re.DOTALL)- data = json.loads(json_match.group()) if json_match else {}- except Exception:- data = {}-- symbol = data.get("symbol")- if not symbol:- symbol_match = re.search(r"\b([A-Z]{1,5})\b", query.upper())- if not symbol_match:- raise ValueError("No stock ticker symbol found in query.")- symbol = symbol_match.group(1)- data = {"symbol": symbol, "analysis_type": "comprehensive", "time_period": "6mo"}-- return data-- def analyze_market(self, query_info, stock_data) -> str:- prompt = (- f"Analyze the stock symbol {query_info['symbol']} for the period "- f"{query_info.get('time_period', '6mo')}. Use recent price data and technical indicators "- f"to provide market trends, risk factors, and recommendations."- )- return self.market_analyst.generate(prompt)-- def analyze(self, query: str) -> str:- query_info = self.parse_query(query)- period = _normalize_period(query_info.get("time_period", "6mo"))- stock_data = self.tools.get_stock_data(query_info["symbol"], period)- if stock_data.empty:- return f"No data available for symbol {query_info['symbol']} in period {period}."-- analysis = self.analyze_market(query_info, stock_data)- return analysis-+from agno.agent import Agent+from agno.models.openai import OpenAIChat+from agno.tools.yfinance import YFinanceTools+from dotenv import load_dotenv, find_dotenv++# Load environment variables from root .env+load_dotenv(find_dotenv())++def get_financial_analyst_agent(api_key: str):+ return Agent(+ model=OpenAIChat(id="gpt-4o-mini", api_key=api_key),+ tools=[YFinanceTools(+ stock_price=False, # Slow: calls yfinance.info+ technical_indicators=False, # Redundant: calls history() again+ historical_prices=True, # Fast: calls history()+ company_info=False,+ analyst_recommendations=False+ )],+ instructions=[+ "You are a senior financial analyst team.",+ "Use 'get_historical_stock_prices' to fetch recent price data.",+ "The most recent trading price is the last entry in the historical data.",+ "Analyze the trends and provide a CONCISE, professional report.",+ "Focus on the most important technical levels and risk factors.",+ "Always state a disclaimer that this is not financial advice."+ ],+ show_tool_calls=False,+ markdown=True+ )def run_financial_analysis(query: str) -> str:- gemini_api_key = os.getenv("GEMINI_API_KEY")- if not gemini_api_key:- return "Error: GEMINI_API_KEY environment variable is not set."- team = FinancialAnalysisTeam(gemini_api_key)+ openai_api_key = os.getenv("OPENAI_API_KEY")+ if not openai_api_key:+ return "Error: OPENAI_API_KEY environment variable is not set."++ agent = get_financial_analyst_agent(openai_api_key)try:- return team.analyze(query)+ # Run the agent and collect response+ response = agent.run(query)+ return response.contentexcept Exception as e:return f"Error during analysis: {e}"diff --git a/finagent/requirements.txt b/finagent/requirements.txtindex cdf3f28..99d3d0d 100644--- a/finagent/requirements.txt+++ b/finagent/requirements.txt@@ -1,7 +1,6 @@-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+mcp+yfinance+openai==1.83.0+python-dotenv+pandas+numpy\ No newline at end of file