akshare.py
Overview
The akshare.py file defines a component within the InfiniFlow system that integrates with the AkShare financial data interface to fetch and process stock news data. This component is designed to retrieve the latest news articles related to a specific stock symbol and present them in a structured pandas DataFrame format. It leverages the akshare Python package, which provides a wide range of financial and economic data APIs.
This file mainly consists of two classes:
AkShareParam: Defines and validates parameters for the AkShare component.
AkShare: Implements the component logic to fetch stock news using AkShare's API.
The file is structured as a component module that fits into a larger agent or workflow system, extending base classes defined elsewhere in the project.
Classes, Functions, and Methods
Class: AkShareParam
class AkShareParam(ComponentParamBase):
Description
Parameter container class for the AkShare component. It extends from ComponentParamBase (presumably a base class for component parameters in the system).
Properties / Attributes
top_n(int): Specifies the number of top news articles to retrieve. Default is 10.
Methods
init(self)Initializes the parameter with default values.
check(self)Validates the parameters to ensure correctness before usage. Specifically, it checks that
top_nis a positive integer.Raises an error if validation fails.
Usage Example
params = AkShareParam()
params.top_n = 5
params.check() # Raises error if top_n is invalid
Class: AkShare
class AkShare(ComponentBase, ABC):
Description
This class implements the main logic for the AkShare component. It inherits from ComponentBase (the base class for components in the system) and Python's ABC (Abstract Base Class) for interface enforcement.
The key functionality is encapsulated in the _run method, which:
Retrieves input data (expected to contain stock symbols).
Calls AkShare's
stock_news_emAPI to fetch recent stock news.Processes the news data into HTML-formatted links with metadata.
Returns the results as a pandas DataFrame.
Class Attributes
component_name(str): The unique name identifier of the component ("AkShare").
Methods
_run(self, history, **kwargs)Core execution method invoked by the system when running the component.
Parameters:
history: Context or previous execution data (not explicitly used in the method).**kwargs: Additional keyword arguments for extensibility.
Workflow:
Imports the
aksharepackage locally to avoid global dependency issues.Calls
self.get_input()to fetch input data, expecting a dictionary with a"content"key containing stock symbols.Joins all stock symbols into a single comma-separated string.
Queries the
ak.stock_news_em()API with the symbol(s).Limits results to
top_narticles (configured viaAkShareParam.top_n).Constructs a list of dictionaries with HTML-formatted news links and metadata.
Returns a pandas DataFrame of the results.
Handles any exceptions by returning an error string wrapped by
AkShare.be_output().
Return Value:
pandas.DataFramecontaining news items with HTML links and additional metadata fields.Or an empty response / error message wrapped via
be_output.
Usage Example
akshare_component = AkShare()
# Assume input is set somewhere in the system to include stock symbols
result_df = akshare_component._run(history=None)
print(result_df)
Important Implementation Details
Dynamic Import: The
aksharepackage is imported inside the_runmethod to avoid unnecessary global imports or dependency failures if the package is not installed but the component is not used.Input Handling: The component expects input as a dictionary with a
"content"key containing a list of stock symbols. These are joined into a single comma-separated string to query multiple symbols simultaneously.Output Formatting: Each news article is transformed into a dictionary containing an HTML anchor tag linking to the news source and additional text fields describing the news content, publication time, and source.
Error Handling: Any exceptions during the AkShare API call or data processing are caught, and a formatted error message is returned as output.
Parameter Validation: The component parameter
top_nis validated to ensure it is a positive integer before use.
Interaction with Other System Components
Base Classes: This file depends on
ComponentBaseandComponentParamBasefromagent.component.base, which provide foundational behavior and interfaces for components and their parameters within the larger InfiniFlow framework.Input/Output Mechanism: The component uses inherited methods like
get_input()to retrieve input data andbe_output()to format outputs, implying a standardized communication protocol within the agent system.External Library: Utilizes the third-party
aksharepackage to fetch financial news data, making it a bridge between external financial APIs and internal data workflows.Data Pipeline: The pandas DataFrame output is likely consumed by downstream components or UI layers for display, analysis, or further processing.
Mermaid Class Diagram
classDiagram
class AkShareParam {
+int top_n
+__init__()
+check()
}
class AkShare {
+str component_name = "AkShare"
+_run(history, **kwargs) pandas.DataFrame
}
AkShareParam <|-- AkShare : uses
AkShare ..|> ComponentBase
AkShareParam ..|> ComponentParamBase
Summary
The akshare.py file implements a modular component for fetching real-time stock news via the AkShare financial data API. With parameter validation, error handling, and structured output, it integrates seamlessly into the InfiniFlow agent system to enrich workflows with financial news insights. Its design follows best practices for component-based architectures, with clear separation of parameters and execution logic.
If you need further details or examples for integration, please let me know!