yahoofinance.py
Overview
The yahoofinance.py file provides a component for accessing and retrieving financial market data from Yahoo Finance using the yfinance Python library. It is designed as part of the InfiniFlow system, offering a structured interface to fetch real-time and historical stock data, financial statements, company information, and relevant news. This component enables easy integration of Yahoo Finance data into applications or analysis workflows by wrapping the API calls and formatting the results in markdown-friendly tabular forms.
The file defines two main classes:
YahooFinanceParam— encapsulates the configuration parameters for the component.YahooFinance— the core class that interacts with Yahoo Finance viayfinance.Tickerto retrieve requested data.
The component supports a range of data retrieval options, such as company info, historical prices, financial statements (balance sheet, cash flow, income statement), and news articles related to the stock.
Classes and Functions
Class: YahooFinanceParam (inherits from ToolParamBase)
Purpose
Defines and validates the parameters used to configure the YahooFinance component. It also provides metadata describing the component, including the expected input format.
Attributes
meta: ToolMeta
Metadata dictionary describing the component, including its name, description, and a dictionary of input parameters.Boolean flags controlling output data fields:
info(default:True) — retrieve general stock/company information.history(default:False) — retrieve historical market price data.count(default:False) — retrieve share count information (not explicitly used in implementation).financials(default:False) — retrieve financial calendar data.income_stmt(default:False) — retrieve income statement data (flag exists but not used in_invoke).balance_sheet(default:False) — retrieve balance sheet data.cash_flow_statement(default:False) — retrieve cash flow statement data.news(default:True) — retrieve related news articles.
Methods
init(self):
Initializes the parameter object with default values and sets the component metadata.check(self):
Validates that the boolean flags are of correct type usingself.check_boolean(). Raises errors if invalid.get_input_form(self) -> dict[str, dict]:
Returns a dictionary describing the expected input form for the component, specifying thestock_codeparameter as a single-line string input.
Usage Example
params = YahooFinanceParam()
params.info = True
params.history = True
params.check() # Validates parameters
input_form = params.get_input_form()
Class: YahooFinance (inherits from ToolBase, ABC)
Purpose
Implements the main functionality to query Yahoo Finance for stock data based on parameters defined in YahooFinanceParam. It handles retries, timeout, error logging, and formatting of the output.
Class Attributes
component_name:
Static identifier string"YahooFinance"for the component.
Methods
_invoke(self, **kwargs)
Decorator:@timeout(uses environment variableCOMPONENT_EXEC_TIMEOUT, default 60 seconds)
Purpose: Core method invoked to fetch data for a given stock code and selected data categories.
Parameters:stock_code(required, via kwargs) — the ticker symbol or company name string to query.
Returns:Markdown-formatted string report of requested financial data or an empty string if no
stock_codeprovided.On errors, returns a string with an error message and sets an error output key.
Implementation Details:
Uses
yfinance.Tickerinstance to fetch data.Collects requested data sections (info, history, financials, balance sheet, cashflow, news) according to boolean flags in
self._param.Converts pandas DataFrames or Series to markdown tables for readability.
Implements retry logic, attempting requests up to
max_retries + 1times with delay after errors.Logs exceptions with
logging.exceptionfor debugging.Uses
self.set_output()andself.output()methods (fromToolBase) to manage component outputs.
thoughts(self) -> str
Returns a short status string indicating the component is fetching live data for the requested stock code.
Usage Example
component = YahooFinance()
component._param = YahooFinanceParam()
component._param.info = True
component._param.history = True
result = component._invoke(stock_code="AAPL")
print(result)
Important Implementation Details and Algorithms
Timeout Handling:
The_invokemethod is wrapped with a@timeoutdecorator that enforces execution time limits using an environment-configurable timeout value.Retry Mechanism:
On exceptions during data retrieval, the method waits for a delay defined byself._param.delay_after_errorand retries up to the maximum retry count. This improves robustness against transient API or network failures.Data Formatting:
Usespandas.DataFrame.to_markdown()andpandas.Series.to_markdown()to convert data into markdown tables, facilitating easy display in markdown-supported interfaces.Selective Data Retrieval:
Boolean flags inYahooFinanceParamallow users to control which data sections to fetch, optimizing performance and output size.Logging and Error Reporting:
Exceptions are logged with full stack traces, and errors are propagated to the output for transparency.
Interaction with Other Parts of the System
Imports and Dependencies:
Uses
yfinancefor Yahoo Finance API calls.Uses
pandasfor data handling and formatting.Extends base classes
ToolBaseandToolParamBasefromagent.tools.base, integrating into the InfiniFlow agent tool framework.Uses a
timeoutdecorator fromapi.utils.api_utilsto manage execution time.
Component Framework Integration:
The class uses
self._paramto reference the current parameter object, which must be set externally.Output is managed via
self.set_output()andself.output(), consistent with the tool interface.The
thoughts()method provides a human-readable status string, possibly for UI or logging.
Configuration:
Timeout duration and retry parameters can be controlled via environment variables and parameter attributes.
Visual Diagram
classDiagram
class YahooFinanceParam {
+meta: ToolMeta
+info: bool
+history: bool
+count: bool
+financials: bool
+income_stmt: bool
+balance_sheet: bool
+cash_flow_statement: bool
+news: bool
+__init__()
+check()
+get_input_form() dict
}
class YahooFinance {
+component_name: str = "YahooFinance"
+_invoke(**kwargs) str
+thoughts() str
}
YahooFinance --> YahooFinanceParam : uses
YahooFinance ..|> ToolBase
YahooFinanceParam ..|> ToolParamBase
Summary
The yahoofinance.py file encapsulates a reusable component for querying Yahoo Finance data within the InfiniFlow platform. By abstracting parameter handling, API querying, error management, and output formatting, it simplifies integration of comprehensive financial data into larger applications or automated workflows. The design emphasizes configurability, robustness, and clear, markdown-friendly output suited for user interfaces or reports.