system.agents.finance_agent package¶
Submodules¶
system.agents.finance_agent.agent module¶
module to configure the main root agent
- system.agents.finance_agent.agent.root_agent() LlmAgent[source]¶
Create the root Research Coordinator agent that orchestrates stock analysis.
This function initializes and returns a root LLM agent that coordinates the entire research and analysis workflow. The agent acts as a Research Coordinator, making autonomous decisions about research strategy, invoking appropriate tools, and synthesizing findings into actionable investment recommendations.
The agent has access to tools: 1. build_and_save_plot: A tool for creating and saving plots based on analyzed data. 2. google_search: A tool for performing web searches to gather qualitative information and identify if the stock is foreign or local.
The agent is instructed to: - Maintain autonomy in choosing research approach and depth - Synthesize information into clear, factual summaries - Document any data gaps or ambiguities - Prioritize accuracy, transparency, and reproducibility
- Returns:
- A fully configured Research Coordinator agent instance that can:
Receive ticker symbols as input
Execute multi-step research workflows
Call available tools with appropriate parameters
Return structured analysis results with investment verdicts
- Return type:
LlmAgent
- Raises:
RuntimeError – If the LLM model cannot be loaded or API keys are not set.
Example
agent = root_agent() # The agent can then be used in workflows to analyze stocks
system.agents.finance_agent.data_tools module¶
module to configure agent tools
- system.agents.finance_agent.data_tools.build_and_save_plot(x: list[float], y: list[float], key: str | None = None, plot_kwargs: dict[str, Any] | None = None) str[source]¶
Create a matplotlib plot from x and y values and save the figure into the in-memory plot_store.
- Parameters:
x – X-axis values.
y – Y-axis values.
key – Optional storage key. A UUID is generated if omitted.
plot_kwargs – Optional plotting configuration.
- Returns:
Storage key on success, otherwise an error message.
- Return type:
str
- system.agents.finance_agent.data_tools.clear_plots() None[source]¶
Clear all stored plots from the in-memory plot_store.
- system.agents.finance_agent.data_tools.read_skills(skill: str) str[source]¶
Extract instructions that serve as guiding skills.
- Parameters:
skill (str) – The skill name to retrieve. Available skills include: - visualizations - financial_analysis
- Raises:
ValueError – May raise value error exception if a non-existent skill is requested.
These are logged but may propagate up. –
- Returns:
The full text of the requested skill instructions.
- Return type:
str
system.agents.finance_agent.market_data_tools module¶
- system.agents.finance_agent.market_data_tools.analyse_ticker(symbol: str) str[source]¶
Execute a comprehensive financial analysis pipeline for a given stock ticker.
This is a high-level wrapper function that orchestrates a complete research and analysis workflow for a stock. It fetches current company data, extracts financial metrics, analyzes news sentiment, and produces a buy/sell/hold verdict.
The analysis steps are executed in sequence: 1. Fetch company data and financials from yfinance 2. Extract key financial metrics (P/E ratios, revenue, debt, etc.) 3. Retrieve and analyze recent news headlines for sentiment 4. Apply decision rules to produce a buy/sell/hold recommendation
- Parameters:
symbol (str) – The stock ticker symbol to analyze (e.g., “AAPL”, “MSFT”, “GOOGL”). Will be converted to uppercase. Must be a valid ticker symbol recognized by yfinance.
- Returns:
- A comprehensive analysis result containing:
symbol (str): The stock ticker symbol in uppercase
company (str): The company name or long name
- metrics (Dict): Financial metrics including:
current_price (float): Current stock price
trailing_pe (float): Trailing price-to-earnings ratio
forward_pe (float): Forward P/E ratio
market_cap (float): Market capitalization
revenue (float): Annual revenue
net_income (float): Annual net income
revenue_growth_pct (float): Year-over-year revenue growth percentage
total_debt (float): Total company debt
total_equity (float): Total stockholder equity
debt_to_equity (float): Debt-to-equity ratio
headlines (List[str]): Recent news headlines for the company
- sentiment_score (float): Aggregate sentiment score (-1.0 to 1.0)
where positive indicates bullish sentiment
verdict (str): Investment decision: “BUY”, “SELL”, or “HOLD”
- verdict_details (Dict): Detailed reasoning for the decision including:
score (int): Net score from decision rules
reasons (List[str]): List of factors that influenced the decision
recommendation (str): Full recommendation text
- Return type:
Dict[str, Any]
- Raises:
Exception – May raise various exceptions if yfinance fails to fetch data, if the ticker symbol is invalid, or if network issues occur. These are logged but may propagate up.
Example
result = analyse_ticker(“AAPL”) print(f”Verdict for {result[‘symbol’]}: {result[‘verdict’]}”) print(f”Current Price: ${result[‘metrics’][‘current_price’]}”) print(f”Sentiment: {result[‘sentiment_score’]}”)
- system.agents.finance_agent.market_data_tools.financial_data_tool(symbol: str, include: Sequence[Literal['historical', 'fundamentals', 'news', 'sentiment']] = ('historical', 'fundamentals'), start_date: str | None = None, end_date: str | None = None, fundamentals_filter: str | None = None, news_limit: int = 5) dict[str, Any][source]¶
Retrieve issuer-specific financial data for a market instrument from EOD Historical Data (EODHD).
- PURPOSE
Use this tool when the agent needs information directly related to a company/security rather than country-level macroeconomic context.
- SUPPORTED DATASETS
- historical:
Daily end-of-day OHLCV observations. When dates are omitted, the tool intentionally limits the request to approximately the most recent 365 calendar days to avoid returning an unnecessarily large dataset.
- fundamentals:
Company profile, valuation, technical metrics, earnings, dividends/splits, ownership, and/or financial statements, depending on EODHD coverage and the fundamentals_filter. EODHD may return missing fields for securities whose underlying issuer does not report them.
- news:
Recent financial-news articles associated with the requested ticker. Each article may contain title, publication date, link, mentioned symbols, tags, and sentiment fields.
- sentiment:
EODHD daily aggregated sentiment observations for the requested ticker over the requested date range.
- SYMBOL FORMAT
Pass EODHD’s exchange-qualified symbol, not merely the local ticker. Example for AIICO on the Nigerian Exchange:
“AIICO.XNSA”
- DATE SEMANTICS
Dates must use YYYY-MM-DD. start_date and end_date apply to historical, news, and sentiment requests. If historical data is requested and no dates are supplied, the tool uses the previous 365 calendar days. If only start_date is supplied, end_date defaults to today. If only end_date is supplied, start_date is one year before it.
- FUNDAMENTALS FILTER
fundamentals_filter is passed directly to EODHD’s filter parameter. Omit it to request EODHD’s complete fundamentals object. Use filters to reduce response size, for example:
“General” “Highlights,Valuation,Technicals” “Financials::Income_Statement::yearly” “Financials::Balance_Sheet::yearly” “General,Highlights,Valuation,Earnings”
- ERROR SEMANTICS
This function NEVER raises an HTTP/API error to the agent. Instead, it returns an errors array containing:
code message source endpoint retryable http_status (when available) details (when available)
- status is:
“success” -> every requested dataset succeeded. “partial” -> at least one dataset succeeded and at least one
dataset failed.
“error” -> all requested datasets failed.
When status is “partial”, the agent must use only the successfully returned datasets and must not infer missing information.
- RETURNS
- A JSON-serializable dictionary with:
tool status ok request data errors
- system.agents.finance_agent.market_data_tools.macro_context_tool(country_code: str = 'ng', *, include_signals: bool = True, include_fx: bool = True, include_indicators: bool = False, include_trade: bool = False, base_currency: str = 'USD', quote_currencies: Sequence[str] = ('NGN',), metric_keys: Sequence[str] | None = None, indicator_category: str | None = None, start_year: int | None = None, end_year: int | None = None, latest: bool = True, trade_top_limit: int = 5) dict[str, Any][source]¶
Retrieve country-level macroeconomic and market-context data from Africa API.
- PURPOSE
Use this tool when the agent needs contextual information about the economic environment surrounding a company or market. This tool does not provide issuer-specific financial statements; those belong in financial_data_tool.
- COUNTRY
country_code is a two-letter country code. The default “ng” means Nigeria.
- SIGNALS
- include_signals=True requests:
GET /v1/countries/{country_code}/signals
Country signals can contain current/selected observations such as policy rates, inflation, official exchange rates, FX observations, market snapshots, commodity benchmarks, trade summaries, and other country-linked records depending on the country’s available coverage.
The returned records can have different frequencies and reporting periods. The agent must inspect their dates/freshness rather than assuming every value represents today’s condition.
- FX
- include_fx=True requests the latest FX rates through:
GET /v1/markets/fx-rates
base_currency defaults to USD. quote_currencies defaults to (“NGN”,).
- INDICATORS
- include_indicators=True queries:
GET /v1/data
- Use metric_keys when the agent needs specific metrics, for example:
“gdp_current_usd” “trade_balance_usd” “exports_goods_services_usd” “imports_goods_services_usd” “policy_rate_pct”
indicator_category may be used to request a category such as “economy” when specific metric keys are not supplied.
latest=True means “latest stored observation available from the provider”; it does NOT mean “measured today.”
- TRADE
- include_trade=True requests:
GET /v1/trade/overview/{country_code}
This can return aggregate trade series, latest snapshots, leading export/import partners, and leading product categories where coverage exists.
- ERROR SEMANTICS
This function NEVER raises an API/HTTP error to the agent. It returns structured errors with:
code message source endpoint retryable http_status (when available) details (when available)
- status is:
“success” -> all requested datasets succeeded. “partial” -> some datasets succeeded and some failed. “error” -> all requested datasets failed.
If an optional dataset fails, the agent must not fabricate or infer its missing values from another dataset.
- IMPORTANT DATA-PROVENANCE RULE
Africa API aggregates observations from external sources. Every returned indicator should be interpreted using its source, reporting year/period, frequency, and freshness when those fields are present.
- RETURNS
- A JSON-serializable dictionary with:
tool status ok request data errors
system.agents.finance_agent.prompts module¶
module serving system prompts
- system.agents.finance_agent.prompts.foreign_stocks_prompt() str[source]¶
Prompt for foreign stocks agent
system.agents.finance_agent.sub_agents module¶
module to configure sub agents
- system.agents.finance_agent.sub_agents.foreign_stocks_agent() LlmAgent[source]¶
Create a sub-agent for foreign company investigation.
The agent extracts financial information about non-african foreign stocks.
- Returns:
A configured sub agent with yfinance access. The agent is intended to be invoked by the root coordinator agent.
- Return type:
Agent
- Raises:
RuntimeError – If the model cannot be loaded or required API keys are missing.
- system.agents.finance_agent.sub_agents.local_stocks_agent() LlmAgent[source]¶
Create a local stocks agent for analyzing Nigerian and African stocks.
The agent uses pythonRepl to run python codes performing analysis requested for by the root agent.
- Returns:
A configured local stocks sub agent with programming capability. The agent is intended to be invoked by the root coordinator agent.
- Return type:
Agent
- Raises:
RuntimeError – If the model cannot be loaded or required API keys are missing.