The foundation of the Stock Analysis Agent is its ability to coordinate 5 specialized AI agents that work sequentially to perform comprehensive stock analysis:
import google.generativeai as genai
import yfinance as yf
from tavily import TavilyClient
from typing import Dict, List, Optional
import json
class StockAnalysisPipeline:
"""
Multi-agent orchestration system for comprehensive stock analysis.
Coordinates 5 specialized AI agents for screening, fundamental analysis,
business moat research, dividend evaluation, and report generation.
"""
def __init__(self, gemini_api_key: str, tavily_api_key: str):
genai.configure(api_key=gemini_api_key)
self.model = genai.GenerativeModel('gemini-2.0-flash-exp')
self.tavily = TavilyClient(api_key=tavily_api_key)
self.scoring_categories = {
'fundamentals_profitability': 20,
'financial_health': 15,
'valuation': 20,
'business_moat': 15,
'dividends_cashflow': 15,
'management_outlook': 10,
'liquidity': 5
}
async run_stock_analysis_pipeline(self, ticker: str) -> Dict:
"""
Execute complete 5-agent analysis pipeline for a stock.
Args:
ticker: Stock symbol (e.g., '1818.KL' for Bursa Malaysia)
Returns:
Complete investment analysis with scoring and recommendation
"""
print(f"🔍 Starting analysis for {ticker}...")
stock_data = self._fetch_stock_data(ticker)
if not stock_data['valid']:
return {'error': 'Failed to fetch stock data'}
screening_result = await self._agent_stock_screener(stock_data)
if not screening_result['passed']:
return {
'ticker': ticker,
'screening': screening_result,
'recommendation': 'FAIL - Does not meet investment criteria'
}
fundamental_analysis = await self._agent_fundamental_analyst(stock_data)
moat_analysis = await self._agent_business_moat(ticker, stock_data)
dividend_analysis = await self._agent_dividend_cashflow(stock_data)
total_score = self._calculate_total_score(
fundamental_analysis,
moat_analysis,
dividend_analysis
)
report = await self._agent_report_generator(
ticker,
stock_data,
screening_result,
fundamental_analysis,
moat_analysis,
dividend_analysis,
total_score
)
return {
'ticker': ticker,
'total_score': total_score,
'recommendation': self._get_recommendation(total_score),
'screening': screening_result,
'fundamental_analysis': fundamental_analysis,
'moat_analysis': moat_analysis,
'dividend_analysis': dividend_analysis,
'report_path': report['markdown_path'],
'chart_path': report['chart_path']
}
def _fetch_stock_data(self, ticker: str) -> Dict:
"""
Fetch comprehensive stock data from Yahoo Finance.
Includes price, fundamentals, dividends, and financial statements.
"""
try:
stock = yf.Ticker(ticker)
info = stock.info
return {
'valid': True,
'ticker': ticker,
'name': info.get('longName', ticker),
'current_price': info.get('currentPrice'),
'market_cap': info.get('marketCap'),
'pe_ratio': info.get('trailingPE'),
'forward_pe': info.get('forwardPE'),
'roe': info.get('returnOnEquity', 0) * 100,
'eps': info.get('trailingEps'),
'dividend_yield': info.get('dividendYield', 0) * 100,
'payout_ratio': info.get('payoutRatio', 0) * 100,
'debt_to_equity': info.get('debtToEquity'),
'current_ratio': info.get('currentRatio'),
'price_to_book': info.get('priceToBook'),
'volume': info.get('volume'),
'avg_volume': info.get('averageVolume')
}
except Exception as e:
print(f"Error fetching data: {e}")
return {'valid': False}