跳到内容

金融

FinanceAgentToolSpec #

基础: BaseToolSpec

源代码位于 llama-index-integrations/tools/llama-index-tools-finance/llama_index/tools/finance/base.py
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
class FinanceAgentToolSpec(BaseToolSpec):
    spec_functions = [
        "find_similar_companies",
        "get_earnings_history",
        "get_stocks_with_upcoming_earnings",
        "get_current_gainer_stocks",
        "get_current_loser_stocks",
        "get_current_undervalued_growth_stocks",
        "get_current_technology_growth_stocks",
        "get_current_most_traded_stocks",
        "get_current_undervalued_large_cap_stocks",
        "get_current_aggressive_small_cap_stocks",
        "get_trending_finance_news",
        "get_google_trending_searches",
        "get_google_trends_for_query",
        "get_latest_news_for_stock",
        "get_current_stock_price_info",
    ]

    def __init__(
        self,
        polygon_api_key: str,
        finnhub_api_key: str,
        alpha_vantage_api_key: str,
        newsapi_api_key: str,
    ):
        self._api_key = {
            "ALPHA_VANTAGE": alpha_vantage_api_key,
            "POLYGON": polygon_api_key,
            "FINNHUB": finnhub_api_key,
            "NEWSAPI": newsapi_api_key,
        }

    def find_similar_companies(self, symbol: str) -> List[str]:
        """Given a stock's ticker symbol, returns a list of similar companies."""
        return comparisons.find_similar_companies(self._api_key, symbol)

    def get_earnings_history(self, symbol: str) -> pd.DataFrame:
        """Given a stock's ticker symbol, returns a dataframe storing actual and estimated earnings over past K quarterly reports."""
        return earnings.get_earnings_history(self._api_key, symbol)

    def get_latest_earning_estimate(self, symbol: str) -> float:
        """Given a stock's ticker symbol, returns it's earnings estimate for the upcoming quarterly report."""
        return earnings.get_latest_earning_estimate(symbol)

    def get_stocks_with_upcoming_earnings(
        self, num_days_from_now: int, only_sp500: bool
    ) -> pd.DataFrame:
        """
        Returns a pandas dataframe containing all stocks which are announcing earnings in upcoming days.

        Arguments:
         num_days_from_now: only returns stocks which announcing earnings from today's date to num_days_from_now.
         only_sp500: only returns sp500 stocks.

        """
        start_date = datetime.now().strftime("%Y-%m-%d")
        end_date = (datetime.now() + timedelta(num_days_from_now)).strftime("%Y-%m-%d")
        return earnings.get_upcoming_earnings(
            self._api_key,
            start_date=start_date,
            end_date=end_date,
            country="USD",
            only_sp500=only_sp500,
        )

    def get_current_gainer_stocks(self) -> pd.DataFrame:
        """
        Return US stocks which are classified as day gainers as per Yahoo Finance.

        A US stock is classified as day gainer if %change in price > 3, price >=5, volume > 15_000

        """
        return news.get_current_gainer_stocks()

    def get_current_loser_stocks(self) -> pd.DataFrame:
        """
        Returns US stocks which are classified as day losers as per Yahoo Finance.

        A US stock is classified as day loser if %change in price < -2.5, price >=5, volume > 20_000

        """
        return news.get_current_loser_stocks()

    def get_current_undervalued_growth_stocks(self) -> pd.DataFrame:
        """
        Get list of undervalued growth stocks in US market as per Yahoo Finance.

        A stock with Price to Earnings ratio between 0-20, Price / Earnings to Growth < 1

        """
        return news.get_current_undervalued_growth_stocks()

    def get_current_technology_growth_stocks(self) -> pd.DataFrame:
        """
        Returns a data frame of growth stocks in technology sector in US market.

        If a stocks's quarterly revenue growth YoY% > 25%.

        """
        return news.get_current_technology_growth_stocks()

    def get_current_most_traded_stocks(self) -> pd.DataFrame:
        """
        Returns a dataframe storing stocks which were traded the most in current market.

        Stocks are ordered in decreasing order of activity i.e stock traded the most on top.

        """
        return news.get_current_most_traded_stocks()

    def get_current_undervalued_large_cap_stocks(self) -> pd.DataFrame:
        """Returns a dataframe storing US market large cap stocks with P/E < 20."""
        return news.get_current_undervalued_large_cap_stocks()

    def get_current_aggressive_small_cap_stocks(self) -> pd.DataFrame:
        """Returns a dataframe storing US market small cap stocks with 1 yr % change in earnings per share > 25."""
        return news.get_current_aggressive_small_cap_stocks()

    def get_trending_finance_news(self) -> List[str]:
        """Returns a list of top 10 trending news in financial market as per seekingalpha."""
        trends = news.get_topk_trending_news()
        return [t["title"] for t in trends]

    def get_google_trending_searches(self) -> Optional[pd.DataFrame]:
        """
        Returns trending searches in US as per google trends.

        If unable to find any trends, returns None.

        """
        return news.get_google_trending_searches(region="united_states")

    def get_google_trends_for_query(self, query: str) -> Optional[pd.DataFrame]:
        """
        Finds google search trends for a given query in United States.

        Returns None if unable to find any trends.

        """
        return news.get_google_trends_for_query(query=query, region="united_states")

    def get_latest_news_for_stock(self, stock_id: str) -> List[str]:
        """Given a stock_id representing the name of a company or the stock ticker symbol, Returns a list of news published related to top business articles in US in last 7 days from now."""
        articles = news.get_latest_news_for_stock(self._api_key, stock_id=stock_id)
        return [a["title"] for a in articles]

    def get_current_stock_price_info(
        self, stock_ticker_symbol: str
    ) -> Optional[Dict[str, Any]]:
        """
        Given a stock's ticker symbol, returns current price information of the stock.

        Returns None if the provided stock ticker symbol is invalid.
        """
        price_info = news.get_current_stock_price_info(
            self._api_key, stock_ticker_symbol
        )
        if price_info is not None:
            return {
                "Current Price": price_info["c"],
                "High Price of the day": price_info["h"],
                "Low Price of the day": price_info["l"],
                "Open Price of the day": price_info["o"],
                "Percentage change": price_info["dp"],
            }
        return None

查找相似公司 #

find_similar_companies(symbol: str) -> List[str]

给定股票代码,返回相似公司列表。

源代码位于 llama-index-integrations/tools/llama-index-tools-finance/llama_index/tools/finance/base.py
42
43
44
def find_similar_companies(self, symbol: str) -> List[str]:
    """Given a stock's ticker symbol, returns a list of similar companies."""
    return comparisons.find_similar_companies(self._api_key, symbol)

获取财报历史 #

get_earnings_history(symbol: str) -> DataFrame

给定股票代码,返回一个数据框,其中存储了过去 K 个季度的实际和预计收益。

源代码位于 llama-index-integrations/tools/llama-index-tools-finance/llama_index/tools/finance/base.py
46
47
48
def get_earnings_history(self, symbol: str) -> pd.DataFrame:
    """Given a stock's ticker symbol, returns a dataframe storing actual and estimated earnings over past K quarterly reports."""
    return earnings.get_earnings_history(self._api_key, symbol)

获取最新财报预期 #

get_latest_earning_estimate(symbol: str) -> float

给定股票代码,返回其即将发布的季度报告的收益预期。

源代码位于 llama-index-integrations/tools/llama-index-tools-finance/llama_index/tools/finance/base.py
50
51
52
def get_latest_earning_estimate(self, symbol: str) -> float:
    """Given a stock's ticker symbol, returns it's earnings estimate for the upcoming quarterly report."""
    return earnings.get_latest_earning_estimate(symbol)

获取即将发布财报的股票 #

get_stocks_with_upcoming_earnings(num_days_from_now: int, only_sp500: bool) -> DataFrame

返回一个包含所有即将在未来几天宣布财报的股票的 pandas 数据框。

参数

名称 类型 描述 默认值
num_days_from_now int

只返回从今天起到 num_days_from_now 天内宣布财报的股票。

必需
only_sp500 bool

只返回标普 500 指数的股票。

必需
源代码位于 llama-index-integrations/tools/llama-index-tools-finance/llama_index/tools/finance/base.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def get_stocks_with_upcoming_earnings(
    self, num_days_from_now: int, only_sp500: bool
) -> pd.DataFrame:
    """
    Returns a pandas dataframe containing all stocks which are announcing earnings in upcoming days.

    Arguments:
     num_days_from_now: only returns stocks which announcing earnings from today's date to num_days_from_now.
     only_sp500: only returns sp500 stocks.

    """
    start_date = datetime.now().strftime("%Y-%m-%d")
    end_date = (datetime.now() + timedelta(num_days_from_now)).strftime("%Y-%m-%d")
    return earnings.get_upcoming_earnings(
        self._api_key,
        start_date=start_date,
        end_date=end_date,
        country="USD",
        only_sp500=only_sp500,
    )

获取当前上涨股票 #

get_current_gainer_stocks() -> DataFrame

根据 Yahoo Finance 返回被归类为日内上涨股的美国股票。

如果价格变化百分比 > 3%,价格 >= 5,交易量 > 15,000,则将美国股票归类为日内上涨股。

源代码位于 llama-index-integrations/tools/llama-index-tools-finance/llama_index/tools/finance/base.py
75
76
77
78
79
80
81
82
def get_current_gainer_stocks(self) -> pd.DataFrame:
    """
    Return US stocks which are classified as day gainers as per Yahoo Finance.

    A US stock is classified as day gainer if %change in price > 3, price >=5, volume > 15_000

    """
    return news.get_current_gainer_stocks()

获取当前下跌股票 #

get_current_loser_stocks() -> DataFrame

根据 Yahoo Finance 返回被归类为日内下跌股的美国股票。

如果价格变化百分比 < -2.5%,价格 >= 5,交易量 > 20,000,则将美国股票归类为日内下跌股。

源代码位于 llama-index-integrations/tools/llama-index-tools-finance/llama_index/tools/finance/base.py
84
85
86
87
88
89
90
91
def get_current_loser_stocks(self) -> pd.DataFrame:
    """
    Returns US stocks which are classified as day losers as per Yahoo Finance.

    A US stock is classified as day loser if %change in price < -2.5, price >=5, volume > 20_000

    """
    return news.get_current_loser_stocks()

获取当前被低估的成长股 #

get_current_undervalued_growth_stocks() -> DataFrame

根据 Yahoo Finance 获取美国市场的被低估成长股列表。

市盈率在 0-20 之间,市盈增长比 < 1 的股票。

源代码位于 llama-index-integrations/tools/llama-index-tools-finance/llama_index/tools/finance/base.py
 93
 94
 95
 96
 97
 98
 99
100
def get_current_undervalued_growth_stocks(self) -> pd.DataFrame:
    """
    Get list of undervalued growth stocks in US market as per Yahoo Finance.

    A stock with Price to Earnings ratio between 0-20, Price / Earnings to Growth < 1

    """
    return news.get_current_undervalued_growth_stocks()

获取当前科技成长股 #

get_current_technology_growth_stocks() -> DataFrame

返回美国市场科技板块的成长股数据框。

如果股票的季度收入同比增长率 > 25%。

源代码位于 llama-index-integrations/tools/llama-index-tools-finance/llama_index/tools/finance/base.py
102
103
104
105
106
107
108
109
def get_current_technology_growth_stocks(self) -> pd.DataFrame:
    """
    Returns a data frame of growth stocks in technology sector in US market.

    If a stocks's quarterly revenue growth YoY% > 25%.

    """
    return news.get_current_technology_growth_stocks()

获取当前交易最活跃股票 #

get_current_most_traded_stocks() -> DataFrame

返回一个数据框,其中包含当前市场中交易最活跃的股票。

股票按活跃度降序排列,即交易最活跃的股票排在最前面。

源代码位于 llama-index-integrations/tools/llama-index-tools-finance/llama_index/tools/finance/base.py
111
112
113
114
115
116
117
118
def get_current_most_traded_stocks(self) -> pd.DataFrame:
    """
    Returns a dataframe storing stocks which were traded the most in current market.

    Stocks are ordered in decreasing order of activity i.e stock traded the most on top.

    """
    return news.get_current_most_traded_stocks()

获取当前被低估的大盘股 #

get_current_undervalued_large_cap_stocks() -> DataFrame

返回一个数据框,其中包含市盈率 < 20 的美国市场大盘股。

源代码位于 llama-index-integrations/tools/llama-index-tools-finance/llama_index/tools/finance/base.py
120
121
122
def get_current_undervalued_large_cap_stocks(self) -> pd.DataFrame:
    """Returns a dataframe storing US market large cap stocks with P/E < 20."""
    return news.get_current_undervalued_large_cap_stocks()

获取当前激进型小盘股 #

get_current_aggressive_small_cap_stocks() -> DataFrame

返回一个数据框,其中包含一年内每股收益变化百分比 > 25 的美国市场小盘股。

源代码位于 llama-index-integrations/tools/llama-index-tools-finance/llama_index/tools/finance/base.py
124
125
126
def get_current_aggressive_small_cap_stocks(self) -> pd.DataFrame:
    """Returns a dataframe storing US market small cap stocks with 1 yr % change in earnings per share > 25."""
    return news.get_current_aggressive_small_cap_stocks()
get_trending_finance_news() -> List[str]

根据 seekingalpha 返回金融市场中排名前 10 的热门新闻列表。

源代码位于 llama-index-integrations/tools/llama-index-tools-finance/llama_index/tools/finance/base.py
128
129
130
131
def get_trending_finance_news(self) -> List[str]:
    """Returns a list of top 10 trending news in financial market as per seekingalpha."""
    trends = news.get_topk_trending_news()
    return [t["title"] for t in trends]
get_google_trending_searches() -> Optional[DataFrame]

根据 Google Trends 返回美国的热门搜索。

如果找不到任何趋势,返回 None。

源代码位于 llama-index-integrations/tools/llama-index-tools-finance/llama_index/tools/finance/base.py
133
134
135
136
137
138
139
140
def get_google_trending_searches(self) -> Optional[pd.DataFrame]:
    """
    Returns trending searches in US as per google trends.

    If unable to find any trends, returns None.

    """
    return news.get_google_trending_searches(region="united_states")
get_google_trends_for_query(query: str) -> Optional[DataFrame]

在美国查找给定查询的 Google 搜索趋势。

如果找不到任何趋势,返回 None。

源代码位于 llama-index-integrations/tools/llama-index-tools-finance/llama_index/tools/finance/base.py
142
143
144
145
146
147
148
149
def get_google_trends_for_query(self, query: str) -> Optional[pd.DataFrame]:
    """
    Finds google search trends for a given query in United States.

    Returns None if unable to find any trends.

    """
    return news.get_google_trends_for_query(query=query, region="united_states")

获取股票最新新闻 #

get_latest_news_for_stock(stock_id: str) -> List[str]

给定表示公司名称或股票代码的 stock_id,返回过去 7 天内与美国热门商业文章相关的已发布新闻列表。

源代码位于 llama-index-integrations/tools/llama-index-tools-finance/llama_index/tools/finance/base.py
151
152
153
154
def get_latest_news_for_stock(self, stock_id: str) -> List[str]:
    """Given a stock_id representing the name of a company or the stock ticker symbol, Returns a list of news published related to top business articles in US in last 7 days from now."""
    articles = news.get_latest_news_for_stock(self._api_key, stock_id=stock_id)
    return [a["title"] for a in articles]

获取当前股票价格信息 #

get_current_stock_price_info(stock_ticker_symbol: str) -> Optional[Dict[str, Any]]

给定股票代码,返回该股票的当前价格信息。

如果提供的股票代码无效,返回 None。

源代码位于 llama-index-integrations/tools/llama-index-tools-finance/llama_index/tools/finance/base.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def get_current_stock_price_info(
    self, stock_ticker_symbol: str
) -> Optional[Dict[str, Any]]:
    """
    Given a stock's ticker symbol, returns current price information of the stock.

    Returns None if the provided stock ticker symbol is invalid.
    """
    price_info = news.get_current_stock_price_info(
        self._api_key, stock_ticker_symbol
    )
    if price_info is not None:
        return {
            "Current Price": price_info["c"],
            "High Price of the day": price_info["h"],
            "Low Price of the day": price_info["l"],
            "Open Price of the day": price_info["o"],
            "Percentage change": price_info["dp"],
        }
    return None