You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

yahoofinance.py 4.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import logging
  17. import os
  18. import time
  19. from abc import ABC
  20. import pandas as pd
  21. import yfinance as yf
  22. from agent.tools.base import ToolMeta, ToolParamBase, ToolBase
  23. from api.utils.api_utils import timeout
  24. class YahooFinanceParam(ToolParamBase):
  25. """
  26. Define the YahooFinance component parameters.
  27. """
  28. def __init__(self):
  29. self.meta:ToolMeta = {
  30. "name": "yahoo_finance",
  31. "description": "The Yahoo Finance is a service that provides access to real-time and historical stock market data. It enables users to fetch various types of stock information, such as price quotes, historical prices, company profiles, and financial news. The API offers structured data, allowing developers to integrate market data into their applications and analysis tools.",
  32. "parameters": {
  33. "stock_code": {
  34. "type": "string",
  35. "description": "The stock code or company name.",
  36. "default": "{sys.query}",
  37. "required": True
  38. }
  39. }
  40. }
  41. super().__init__()
  42. self.info = True
  43. self.history = False
  44. self.count = False
  45. self.financials = False
  46. self.income_stmt = False
  47. self.balance_sheet = False
  48. self.cash_flow_statement = False
  49. self.news = True
  50. def check(self):
  51. self.check_boolean(self.info, "get all stock info")
  52. self.check_boolean(self.history, "get historical market data")
  53. self.check_boolean(self.count, "show share count")
  54. self.check_boolean(self.financials, "show financials")
  55. self.check_boolean(self.income_stmt, "income statement")
  56. self.check_boolean(self.balance_sheet, "balance sheet")
  57. self.check_boolean(self.cash_flow_statement, "cash flow statement")
  58. self.check_boolean(self.news, "show news")
  59. def get_input_form(self) -> dict[str, dict]:
  60. return {
  61. "stock_code": {
  62. "name": "Stock code/Company name",
  63. "type": "line"
  64. }
  65. }
  66. class YahooFinance(ToolBase, ABC):
  67. component_name = "YahooFinance"
  68. @timeout(os.environ.get("COMPONENT_EXEC_TIMEOUT", 60))
  69. def _invoke(self, **kwargs):
  70. if not kwargs.get("stock_code"):
  71. self.set_output("report", "")
  72. return ""
  73. last_e = ""
  74. for _ in range(self._param.max_retries+1):
  75. yohoo_res = []
  76. try:
  77. msft = yf.Ticker(kwargs["stock_code"])
  78. if self._param.info:
  79. yohoo_res.append("# Information:\n" + pd.Series(msft.info).to_markdown() + "\n")
  80. if self._param.history:
  81. yohoo_res.append("# History:\n" + msft.history().to_markdown() + "\n")
  82. if self._param.financials:
  83. yohoo_res.append("# Calendar:\n" + pd.DataFrame(msft.calendar).to_markdown() + "\n")
  84. if self._param.balance_sheet:
  85. yohoo_res.append("# Balance sheet:\n" + msft.balance_sheet.to_markdown() + "\n")
  86. yohoo_res.append("# Quarterly balance sheet:\n" + msft.quarterly_balance_sheet.to_markdown() + "\n")
  87. if self._param.cash_flow_statement:
  88. yohoo_res.append("# Cash flow statement:\n" + msft.cashflow.to_markdown() + "\n")
  89. yohoo_res.append("# Quarterly cash flow statement:\n" + msft.quarterly_cashflow.to_markdown() + "\n")
  90. if self._param.news:
  91. yohoo_res.append("# News:\n" + pd.DataFrame(msft.news).to_markdown() + "\n")
  92. self.set_output("report", "\n\n".join(yohoo_res))
  93. return self.output("report")
  94. except Exception as e:
  95. last_e = e
  96. logging.exception(f"YahooFinance error: {e}")
  97. time.sleep(self._param.delay_after_error)
  98. if last_e:
  99. self.set_output("_ERROR", str(last_e))
  100. return f"YahooFinance error: {last_e}"
  101. assert False, self.output()
  102. def thoughts(self) -> str:
  103. return "Pulling live financial data for `{}`.".format(self.get_input().get("stock_code", "-_-!"))