A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.
Add multi-agent financial analyst project
Sumanth0773f6ef4070473
diff --git a/financial analyst/README.md b/financial analyst/README.mdnew file mode 100644index 0000000..59d8a18--- /dev/null+++ b/financial analyst/README.md@@ -0,0 +1,66 @@+# π― Multi-Agent AI Financial Analyst++A powerful multi-agent system that performs comprehensive stock analysis and generates detailed financial reports.++## Features++- Stock Analysis Agent: Performs thorough analysis of stocks using fundamental and technical indicators+- Report Writing Agent: Transforms analysis into comprehensive, reader-friendly reports+- Real-time market data integration+- Professional report generation in markdown format+- Interactive Streamlit interface++## Installation++1. Clone this repository:+```bash+git clone <your-repo-url>+cd financial-analyst+```++2. Install dependencies:+```bash+pip install -r requirements.txt+```++3. Create a `.env` file in the root directory and add your SambaNova API key:+```bash+SAMBANOVA_API_KEY=your_api_key_here+```++## Usage++1. Start the Streamlit app:+```bash+streamlit run financial_analyst.py+```++2. In the web interface:+ - Enter your stock symbol (e.g., AAPL, GOOGL)+ - Click "Analyze Stock" to start the analysis+ - Wait for the agents to complete their analysis+ - Download the generated report++## How It Works++The application uses two specialized AI agents:++1. **Stock Analysis Agent**+ - Analyzes company fundamentals+ - Reviews market news+ - Evaluates technical indicators+ - Assesses market trends++2. **Report Writing Agent**+ - Compiles analysis into structured reports+ - Formats information for clarity+ - Generates actionable insights+ - Creates downloadable markdown reports++## Contributing++Contributions are welcome! Please feel free to submit a Pull Request.++## License++This project is licensed under the MIT License - see the LICENSE file for details.\ No newline at end of filediff --git a/financial analyst/financial_analyst.py b/financial analyst/financial_analyst.pynew file mode 100644index 0000000..748d5a1--- /dev/null+++ b/financial analyst/financial_analyst.py@@ -0,0 +1,228 @@+import streamlit as st+import os+import pandas as pd+from datetime import datetime, timedelta+from dotenv import load_dotenv+from crewai import Agent, Crew, Process, Task, LLM+from pydantic import BaseModel+from tools.financial_tools import YFinanceStockTool++# Load environment variables+load_dotenv()++# Define Pydantic models for structured output+class StockAnalysis(BaseModel):+ symbol: str+ company_name: str+ current_price: float+ market_cap: float+ pe_ratio: float+ recommendation: str+ analysis_summary: str+ risk_assessment: str+ technical_indicators: dict+ fundamental_metrics: dict++# Initialize SambaNova LLM[email protected]_resource+def load_llm():+ return LLM(+ model="sambanova/Llama-4-Maverick-17B-128E-Instruct",+ api_key=os.getenv("SAMBANOVA_API_KEY"),+ temperature=0.3+ )++# Create agents and tasks+def create_agents_and_tasks(symbol: str):+ llm = load_llm()++ # Initialize tools+ stock_tool = YFinanceStockTool()++ # Stock Analysis Agent+ stock_analysis_agent = Agent(+ role="Wall Street Financial Analyst",+ goal=f"Conduct a comprehensive, data-driven analysis of {symbol} stock using real-time market data",+ backstory="""You are a seasoned Wall Street analyst with 15+ years of experience in equity research.+ You're known for your meticulous analysis and data-driven insights.+ You ALWAYS base your analysis on real-time market data, never relying solely on pre-existing knowledge.+ You're an expert at interpreting financial metrics, market trends, and providing actionable insights.""",+ llm=llm,+ verbose=True,+ memory=True,+ tools=[stock_tool]+ )++ # Report Writing Agent+ report_writer_agent = Agent(+ role="Financial Report Specialist",+ goal="Transform detailed financial analysis into a professional, comprehensive investment report",+ backstory="""You are an expert financial writer with a track record of creating institutional-grade research reports.+ You excel at presenting complex financial data in a clear, structured format.+ You always maintain professional standards while making reports accessible and actionable.+ You're known for your clear data presentation, trend analysis, and risk assessment capabilities.""",+ llm=llm,+ verbose=True+ )++ # Analysis Task+ analysis_task = Task(+ description=f"""Analyze {symbol} stock using the stock_data_tool to fetch real-time data. Your analysis must include:++ 1. Latest Trading Information (HIGHEST PRIORITY)+ - Latest stock price with specific date+ - Percentage change+ - Trading volume+ - Market status (open/closed)+ - Highlight if this is from the most recent trading session++ 2. 52-Week Performance (CRITICAL)+ - 52-week high with exact date+ - 52-week low with exact date+ - Current price position relative to 52-week range+ - Calculate percentage from highs and lows++ 3. Financial Deep Dive+ - Market capitalization+ - P/E ratio and other key metrics+ - Revenue growth and profit margins+ - Dividend information (if applicable)++ 4. Technical Analysis+ - Recent price movements+ - Volume analysis+ - Key technical indicators++ 5. Market Context+ - Business summary+ - Analyst recommendations+ - Key risk factors++ IMPORTANT:+ - ALWAYS use the stock_data_tool to fetch real-time data+ - Begin your analysis with the latest price and 52-week data+ - Include specific dates for all price points+ - Clearly indicate when each price point was recorded+ - Calculate and show percentage changes+ - Verify all numbers with live data+ - Compare current metrics with historical trends""",+ expected_output="A comprehensive analysis report with real-time data, including all specified metrics and clear section breakdowns",+ agent=stock_analysis_agent+ )++ # Report Task+ report_task = Task(+ description=f"""Transform the analysis into a professional investment report for {symbol}. The report must:++ 1. Structure:+ - Begin with an executive summary+ - Use clear section headers+ - Include tables for data presentation+ - Add emoji indicators for trends (π π)++ 2. Content Requirements:+ - Include timestamps for all data points+ - Present key metrics in tables+ - Use bullet points for key insights+ - Compare metrics to industry averages+ - Explain technical terms+ - Highlight potential risks++ 3. Sections:+ - Executive Summary+ - Market Position Overview+ - Financial Metrics Analysis+ - Technical Analysis+ - Risk Assessment+ - Future Outlook++ 4. Formatting:+ - Use markdown formatting+ - Create tables for data comparison+ - Include trend emojis+ - Use bold for key metrics+ - Add bullet points for key takeaways++ IMPORTANT:+ - Maintain professional tone+ - Clearly state all data sources+ - Include risk disclaimers+ - Format in clean, readable markdown""",+ expected_output="A professionally formatted investment report in markdown, with clear sections, data tables, and visual indicators",+ agent=report_writer_agent+ )++ # Create Crew+ crew = Crew(+ agents=[stock_analysis_agent, report_writer_agent],+ tasks=[analysis_task, report_task],+ process=Process.sequential,+ verbose=True+ )++ return crew++# Streamlit UI+st.set_page_config(page_title="Multi-Agent AI Financial Analyst", layout="wide")++st.title("π― Multi-Agent AI Financial Analyst")++# Sidebar+with st.sidebar:+ st.header("Configuration")++ # API Key input+ api_key = st.text_input(+ "SambaNova API Key",+ type="password",+ value=os.getenv("SAMBANOVA_API_KEY", ""),+ help="Enter your SambaNova API key"+ )+ if api_key:+ os.environ["SAMBANOVA_API_KEY"] = api_key++ # Stock Symbol input+ symbol = st.text_input(+ "Stock Symbol",+ value="AAPL",+ help="Enter a stock symbol (e.g., AAPL, GOOGL)"+ ).upper()++ # Analysis button+ analyze_button = st.button("Analyze Stock", type="primary")++# Main content area+if "analysis_complete" not in st.session_state:+ st.session_state.analysis_complete = False+ st.session_state.report = None++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()+ # Convert the CrewOutput to string if needed+ if hasattr(result, 'raw'):+ st.session_state.report = result.raw+ else:+ st.session_state.report = str(result)+ st.session_state.analysis_complete = True++ except Exception as e:+ st.error(f"An error occurred: {str(e)}")++if st.session_state.analysis_complete and st.session_state.report:+ st.markdown("### Analysis Report")+ st.markdown(st.session_state.report)++ # Download button+ st.download_button(+ label="Download Report",+ data=st.session_state.report,+ file_name=f"stock_analysis_{symbol}_{datetime.now().strftime('%Y%m%d')}.md",+ mime="text/markdown"+ )++# Footer+st.markdown("---")\ No newline at end of filediff --git a/financial analyst/requirements.txt b/financial analyst/requirements.txtnew file mode 100644index 0000000..6d51798--- /dev/null+++ b/financial analyst/requirements.txt@@ -0,0 +1,7 @@+crewai>=0.12.2+streamlit>=1.31.0+python-dotenv>=1.0.0+pydantic>=2.5.0+yfinance>=0.2.35+pandas>=2.1.0+plotly>=5.18.0\ No newline at end of filediff --git a/financial analyst/tools/__pycache__/financial_tools.cpython-311.pyc b/financial analyst/tools/__pycache__/financial_tools.cpython-311.pycnew file mode 100644index 0000000..72d07cbBinary files /dev/null and b/financial analyst/tools/__pycache__/financial_tools.cpython-311.pyc differdiff --git a/financial analyst/tools/financial_tools.py b/financial analyst/tools/financial_tools.pynew file mode 100644index 0000000..71885ca--- /dev/null+++ b/financial analyst/tools/financial_tools.py@@ -0,0 +1,74 @@+import yfinance as yf+from datetime import datetime+from crewai.tools import BaseTool+from pydantic import BaseModel, Field+import json++class StockInput(BaseModel):+ """Input schema for YFinanceStockTool."""+ symbol: str = Field(..., description="The stock symbol to analyze (e.g., 'AAPL', 'GOOGL')")++class YFinanceStockTool(BaseTool):+ name: str = "stock_data_tool"+ description: str = """+ A tool for getting real-time and historical stock market data.+ Use this tool when you need specific stock information like:+ - Latest stock price from most recent trading day+ - Current price and trading volume+ - Historical price data+ - Company financials and metrics+ - Company information and business summary+ """+ args_schema: type[BaseModel] = StockInput++ def _run(self, symbol: str) -> str:+ try:+ stock = yf.Ticker(symbol)++ # Get basic info+ info = stock.info++ # Get recent market data+ hist = stock.history(period="1mo")++ # Get the latest trading day's data+ latest_data = hist.iloc[-1]+ latest_date = latest_data.name.strftime('%Y-%m-%d')++ # Format 52-week data with dates+ hist_1y = stock.history(period="1y")+ fifty_two_week_high_date = hist_1y['High'].idxmax().strftime('%Y-%m-%d')+ fifty_two_week_low_date = hist_1y['Low'].idxmin().strftime('%Y-%m-%d')++ # Prepare the response+ response = {+ "company_name": info.get("longName", "N/A"),+ "latest_trading_data": {+ "date": latest_date,+ "price": latest_data['Close'],+ "volume": latest_data['Volume'],+ "change": f"{((latest_data['Close'] - latest_data['Open']) / latest_data['Open'] * 100):.2f}%"+ },+ "52_week_high": {+ "price": info.get("fiftyTwoWeekHigh", "N/A"),+ "date": fifty_two_week_high_date+ },+ "52_week_low": {+ "price": info.get("fiftyTwoWeekLow", "N/A"),+ "date": fifty_two_week_low_date+ },+ "market_cap": info.get("marketCap", "N/A"),+ "pe_ratio": info.get("forwardPE", "N/A"),+ "dividend_yield": info.get("dividendYield", "N/A"),+ "business_summary": info.get("longBusinessSummary", "N/A"),+ "analyst_rating": info.get("recommendationKey", "N/A")+ }++ return json.dumps(response, indent=2)++ except Exception as e:+ return f"Error fetching data for {symbol}: {str(e)}"++ def _arun(self, symbol: str) -> str:+ # Async implementation if needed+ raise NotImplementedError("Async version not implemented")\ No newline at end of file