agent.py
from google.genai import types
from google.adk.tools import ToolContext
from google.adk.agents import Agent
from google.adk.tools.agent_tool import AgentTool
from google.adk.models.lite_llm import LiteLlm
from .sub_agents.data_analyst import data_analyst
from .sub_agents.financial_analyst import financial_analyst
from .sub_agents.news_analyst import news_analyst
from .prompt import PROMPT
MODEL = LiteLlm("openai/gpt-4o")
async def save_advice_report(tool_context: ToolContext, summary: str, ticker: str):
state = tool_context.state
data_analyst_result = state.get("data_analyst_result")
financial_analyst_result = state.get("financial_analyst_result")
news_analyst_analyst_result = state.get("news_analyst_analyst_result")
report = f"""
# Excetuve Summary and Advice:
{summary}
## Data Analyst Report:
{data_analyst_result}
## Financial Analyst Report:
{financial_analyst_result}
## News Analyst Report:
{news_analyst_analyst_result}
"""
state["report"] = report
filename = f"{ticker}_investment_advice.md"
artifact = types.Part(
inline_data=types.Blob(
mime_type="text/markdown",
data=report.encode("utf-8"),
)
)
await tool_context.save_artifact(filename, artifact)
return {
"success": True,
}
financial_advisor = Agent(
name="FinancialAdvisor",
instruction=PROMPT,
model=MODEL,
tools=[
AgentTool(agent=financial_analyst),
AgentTool(agent=news_analyst),
AgentTool(agent=data_analyst),
save_advice_report,
],
)
root_agent = financial_advisor
promt.py
PROMPT = """
You are a Professional Financial Advisor specializing in equity analysis and investment recommendations. You ONLY provide advice on stocks, trading, and investment decisions.
**STRICT SCOPE LIMITATIONS:**
- ONLY answer questions about stocks, trading, investments, financial markets, and company analysis
- REFUSE to answer questions about: general knowledge, technology help, personal advice unrelated to finance, or any non-financial topics
- If asked about non-financial topics, politely redirect: "I'm a specialized financial advisor. I can only help with stock analysis and investment decisions."
**INVESTMENT RECOMMENDATION PROCESS:**
Before providing any BUY/SELL/HOLD recommendation, you MUST:
1. Ask about the user's investment goals (growth, income, speculation, etc.)
2. Ask about their risk tolerance (conservative, moderate, aggressive)
3. Ask about their investment timeline (short-term, medium-term, long-term)
**RECOMMENDATION REQUIREMENTS:**
After gathering user preferences, you MUST provide a clear recommendation:
- **BUY**: Strong positive outlook with specific price targets and rationale
- **SELL**: Negative outlook with clear reasons to exit
- **HOLD**: Neutral position with conditions for future action
**Available Specialized Tools:**
- **data_analyst**: Gathers market data, company info, pricing, and financial metrics
- **news_analyst**: Searches current news and industry information using web tools
- **financial_analyst**: Analyzes detailed financial statements including income, balance sheet, and cash flow
**Direct Tools:**
- **save_company_report()**: Save comprehensive reports as artifacts (use ONLY when user requests a report and you have all the data you need for it.)
**ANALYSIS METHODOLOGY:**
For thorough analysis, you should:
1. Gather quantitative data (financial metrics, performance, valuation)
2. Research current news and market sentiment
3. Analyze financial statements for fundamental strength
4. Consider user's specific goals and risk profile
5. Provide confident recommendation with clear reasoning
**REPORT REQUIREMENTS:**
When creating reports, include:
- Executive Summary with clear BUY/SELL/HOLD recommendation
- Fundamental Analysis (financial health, valuation metrics)
- Technical Analysis (price trends, momentum)
- News and Market Sentiment Analysis
- Risk Assessment specific to user's tolerance
- Price Targets and Timeline
- Action Plan with entry/exit strategies
**Communication Style:**
- Be confident and decisive in recommendations
- Use specific data points and metrics
- Explain reasoning clearly with supporting evidence
- Provide actionable investment guidance
- Show conviction in your analysis
You are an expert who makes money for clients through sound investment decisions. Be opinionated and confident.
"""
__init__.py
from . import agent
data_analyst.py
import yfinance as yf
from google.adk.agents import LlmAgent
from google.adk.models.lite_llm import LiteLlm
MODEL = LiteLlm(model="openai/gpt-4o")
def get_company_info(ticker: str) -> str:
"""
Retrieves basic company information for a given stock ticker.
This tool fetches fundamental company details including the official company name,
industry classification, and sector categorization from Yahoo Finance.
Args:
ticker (str): The stock ticker symbol (e.g., 'AAPL' for Apple Inc.)
Returns:
dict: A dictionary containing:
- ticker (str): The input ticker symbol
- success (bool): True if the operation was successful
- company_name (str): Full legal name of the company
- industry (str): Specific industry classification
- sector (str): Broader sector categorization
Example:
>>> get_company_info('MSFT')
{
'ticker': 'MSFT',
'success': True,
'company_name': 'Microsoft Corporation',
'industry': 'Software - Infrastructure',
'sector': 'Technology'
}
"""
stock = yf.Ticker(ticker)
info = stock.info
return {
"ticker": ticker,
"success": True,
"company_name": info.get("longName", "NA"),
"industry": info.get("industry", "NA"),
"sector": info.get("sector", "NA"),
}
def get_stock_price(ticker: str, period: str) -> str:
"""
Fetches historical stock price data and current trading price for a given ticker.
This tool retrieves both the current market price and historical price data
over a specified time period, including open, high, low, close prices and volume.
Args:
ticker (str): Stock ticker symbol (e.g., 'AAPL' for Apple Inc.)
period (str): Time period for historical data. Valid options:
- '1d': 1 day
- '5d': 5 days
- '1mo': 1 month (default)
- '3mo': 3 months
- '6mo': 6 months
- '1y': 1 year
- '2y': 2 years
- '5y': 5 years
- '10y': 10 years
- 'ytd': Year to date
- 'max': Maximum available data
Returns:
dict: A dictionary containing:
- ticker (str): The input ticker symbol
- success (bool): True if the operation was successful
- history (str): JSON-formatted historical price data with OHLCV
- current_price (float): Current market price of the stock
Example:
>>> get_stock_price('TSLA', '3mo')
{
'ticker': 'TSLA',
'success': True,
'history': '{"Open": {...}, "High": {...}, ...}',
'current_price': 245.67
}
"""
stock = yf.Ticker(ticker)
info = stock.info
history = stock.history(period=period)
return {
"ticker": ticker,
"success": True,
"history": history.to_json(),
"current_price": info.get("currentPrice"),
}
def get_financial_metrics(ticker: str) -> str:
"""
Retrieves key financial metrics and valuation ratios for stock analysis.
This tool fetches essential financial indicators that help assess a company's
valuation, profitability, dividend policy, and market risk characteristics.
Args:
ticker (str): Stock ticker symbol (e.g., 'AAPL' for Apple Inc.)
Returns:
dict: A dictionary containing:
- ticker (str): The input ticker symbol
- success (bool): True if the operation was successful
- market_cap (float): Total market capitalization in USD
- pe_ratio (float): Trailing Price-to-Earnings ratio (price/earnings per share)
- dividend_yield (float): Annual dividend yield as a percentage (0.02 = 2%)
- beta (float): Stock's beta coefficient measuring volatility vs market
Notes:
- Market Cap: Represents company's total value (shares * price)
- P/E Ratio: Lower may indicate undervalued; higher may indicate growth expectations
- Dividend Yield: Annual dividends as percentage of stock price
- Beta: <1 means less volatile than market; >1 means more volatile
Example:
>>> get_financial_metrics('JNJ')
{
'ticker': 'JNJ',
'success': True,
'market_cap': 385000000000,
'pe_ratio': 15.2,
'dividend_yield': 0.031,
'beta': 0.65
}
"""
stock = yf.Ticker(ticker)
info = stock.info
return {
"ticker": ticker,
"success": True,
"market_cap": info.get("marketCap", "NA"),
"pe_ratio": info.get("trailingPE", "NA"),
"dividend_yield": info.get("dividendYield", "NA"),
"beta": info.get("beta", "NA"),
}
data_analyst = LlmAgent(
name="DataAnalyst",
model=MODEL,
description="Gathers and analyzes basic stock market data using multiple focused tools",
instruction="""
You are a Data Analyst who gathers stock information using 4 specialized tools:
1. **get_company_info(ticker)** - Learn about the company (name, sector, industry)
2. **get_stock_price(ticker, period)** - Get current pricing and trading ranges
3. **get_financial_metrics(ticker)** - Check key financial ratios
Use multiple focused tools to gather different types of data.
Explain what each tool provides and present the information clearly.
""",
tools=[
get_company_info,
get_stock_price,
get_financial_metrics,
],
output_key="data_analyst_result",
)
financial_analyst.py
import yfinance as yf
from google.adk.agents import Agent
from google.adk.models.lite_llm import LiteLlm
MODEL = LiteLlm(model="openai/gpt-4o")
def get_income_statement(ticker: str):
"""
Retrieves the income statement for comprehensive revenue and profitability analysis.
This tool fetches detailed income statement data showing a company's financial
performance over recent reporting periods, including revenues, expenses, and
profit margins at various levels.
Args:
ticker (str): Stock ticker symbol (e.g., 'AAPL' for Apple Inc.)
Returns:
dict: A dictionary containing:
- ticker (str): The input ticker symbol
- success (bool): True if the operation was successful
- income_statement (str): JSON-formatted income statement data including:
* Total Revenue
* Cost of Revenue
* Gross Profit
* Operating Expenses
* Operating Income
* EBITDA
* Net Income
* Earnings Per Share (EPS)
Notes:
- Data typically covers the last 4 quarters and annual periods
- All financial figures are in the company's reporting currency
- Useful for analyzing revenue growth, margin trends, and profitability
Example:
>>> get_income_statement('GOOGL')
{
'ticker': 'GOOGL',
'success': True,
'income_statement': '{"Total Revenue": {...}, "Net Income": {...}}'
}
"""
stock = yf.Ticker(ticker)
# return stock.income_stmt.to_json()
return {
"ticker": ticker,
"success": True,
"income_statement": stock.income_stmt.to_json(),
}
def get_balance_sheet(ticker: str):
"""
Retrieves the balance sheet for analyzing financial position and capital structure.
This tool fetches comprehensive balance sheet data showing a company's assets,
liabilities, and shareholders' equity at specific points in time, providing
insight into financial health and capital efficiency.
Args:
ticker (str): Stock ticker symbol (e.g., 'AAPL' for Apple Inc.)
Returns:
dict: A dictionary containing:
- ticker (str): The input ticker symbol
- success (bool): True if the operation was successful
- balance_sheet (str): JSON-formatted balance sheet data including:
* Current Assets (cash, receivables, inventory)
* Non-Current Assets (PP&E, intangibles, investments)
* Current Liabilities (payables, short-term debt)
* Non-Current Liabilities (long-term debt, deferred items)
* Total Shareholders' Equity
* Working Capital components
Notes:
- Provides snapshot of financial position at quarter/year end
- Essential for calculating liquidity ratios (current ratio, quick ratio)
- Used to assess debt levels, asset efficiency, and book value
- All values in company's reporting currency
Example:
>>> get_balance_sheet('AMZN')
{
'ticker': 'AMZN',
'success': True,
'balance_sheet': '{"Total Assets": {...}, "Total Liabilities": {...}}'
}
"""
stock = yf.Ticker(ticker)
# return stock.balance_sheet.to_json()
return {
"ticker": ticker,
"success": True,
"balance_sheet": stock.balance_sheet.to_json(),
}
def get_cash_flow(ticker: str):
"""
Retrieves the cash flow statement for analyzing cash generation and capital allocation.
This tool fetches detailed cash flow data showing how a company generates and
uses cash across operating, investing, and financing activities, crucial for
assessing financial sustainability and growth capacity.
Args:
ticker (str): Stock ticker symbol (e.g., 'AAPL' for Apple Inc.)
Returns:
dict: A dictionary containing:
- ticker (str): The input ticker symbol
- success (bool): True if the operation was successful
- cash_flow (str): JSON-formatted cash flow statement including:
* Operating Cash Flow (cash from core business)
* Capital Expenditures (CapEx)
* Free Cash Flow (Operating CF - CapEx)
* Investing Activities (acquisitions, investments)
* Financing Activities (debt, dividends, buybacks)
* Net Change in Cash
Notes:
- Operating cash flow indicates core business cash generation
- Free cash flow shows cash available for shareholders/growth
- Negative investing CF often indicates growth investment
- Financing CF reveals capital structure decisions
- Critical for assessing dividend sustainability and growth funding
Example:
>>> get_cash_flow('META')
{
'ticker': 'META',
'success': True,
'cash_flow': '{"Operating Cash Flow": {...}, "Free Cash Flow": {...}}'
}
"""
stock = yf.Ticker(ticker)
# return stock.balance_sheet.to_json()
return {
"ticker": ticker,
"success": True,
"cash_flow": stock.cash_flow.to_json(),
}
financial_analyst = Agent(
name="FinancialAnalyst",
model=MODEL,
description="Analyzes detailed financial statements including income, balance sheet, and cash flow",
instruction="""
You are a Financial Analyst who performs deep financial statement analysis. Your job:
1. **Income Analysis**: Use get_income_statement() to analyze revenue, profitability, and margins
2. **Balance Sheet Analysis**: Use get_balance_sheet() to examine assets, liabilities, and financial position
3. **Cash Flow Analysis**: Use get_cash_flow() to assess cash generation and capital allocation
**Your Financial Tools:**
- **get_income_statement(ticker)**: Revenue, profit margins, and profitability analysis
- **get_balance_sheet(ticker)**: Assets, debt, equity, and financial strength ratios
- **get_cash_flow(ticker)**: Operating cash flow, free cash flow, and capital expenditure
Analyze the financial health and performance of companies using comprehensive financial statement data.
Focus on key financial ratios, trends, and indicators that reveal the company's financial strength.
""",
tools=[
get_income_statement,
get_balance_sheet,
get_cash_flow,
],
output_key="financial_analyst_result",
)
news_analyst.py
from google.adk.agents import Agent
from google.adk.models.lite_llm import LiteLlm
from tools import web_search_tool
MODEL = LiteLlm(model="openai/gpt-4o")
news_analyst = Agent(
name="NewsAnalyst",
model=MODEL,
description="Uses Web Search tools to search and scrape real web content from the web.",
instruction="""
You are a News Analyst Specialist who uses web tools to find current information. Your job:
1. **Web Search**: Use web_search_tool() to find recent news about a company.
3. **Summarize Findings**: Explain what you found and its relevance
**Your Web Tools:**
- **web_search_tool()**: Firecrawl web search for company news
Use external APIs to search and scrape web content for current information.
""",
output_key="news_analyst_result",
tools=[
web_search_tool,
],
)