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.

wencai.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 pywencai
  22. from agent.tools.base import ToolParamBase, ToolMeta, ToolBase
  23. from api.utils.api_utils import timeout
  24. class WenCaiParam(ToolParamBase):
  25. """
  26. Define the WenCai component parameters.
  27. """
  28. def __init__(self):
  29. self.meta:ToolMeta = {
  30. "name": "iwencai",
  31. "description": """
  32. iwencai search: search platform is committed to providing hundreds of millions of investors with the most timely, accurate and comprehensive information, covering news, announcements, research reports, blogs, forums, Weibo, characters, etc.
  33. robo-advisor intelligent stock selection platform: through AI technology, is committed to providing investors with intelligent stock selection, quantitative investment, main force tracking, value investment, technical analysis and other types of stock selection technologies.
  34. fund selection platform: through AI technology, is committed to providing excellent fund, value investment, quantitative analysis and other fund selection technologies for foundation citizens.
  35. """,
  36. "parameters": {
  37. "query": {
  38. "type": "string",
  39. "description": "The question/conditions to select stocks.",
  40. "default": "{sys.query}",
  41. "required": True
  42. }
  43. }
  44. }
  45. super().__init__()
  46. self.top_n = 10
  47. self.query_type = "stock"
  48. def check(self):
  49. self.check_positive_integer(self.top_n, "Top N")
  50. self.check_valid_value(self.query_type, "Query type",
  51. ['stock', 'zhishu', 'fund', 'hkstock', 'usstock', 'threeboard', 'conbond', 'insurance',
  52. 'futures', 'lccp',
  53. 'foreign_exchange'])
  54. def get_input_form(self) -> dict[str, dict]:
  55. return {
  56. "query": {
  57. "name": "Query",
  58. "type": "line"
  59. }
  60. }
  61. class WenCai(ToolBase, ABC):
  62. component_name = "WenCai"
  63. @timeout(os.environ.get("COMPONENT_EXEC_TIMEOUT", 12))
  64. def _invoke(self, **kwargs):
  65. if not kwargs.get("query"):
  66. self.set_output("report", "")
  67. return ""
  68. last_e = ""
  69. for _ in range(self._param.max_retries+1):
  70. try:
  71. wencai_res = []
  72. res = pywencai.get(query=kwargs["query"], query_type=self._param.query_type, perpage=self._param.top_n)
  73. if isinstance(res, pd.DataFrame):
  74. wencai_res.append(res.to_markdown())
  75. elif isinstance(res, dict):
  76. for item in res.items():
  77. if isinstance(item[1], list):
  78. wencai_res.append(item[0] + "\n" + pd.DataFrame(item[1]).to_markdown())
  79. elif isinstance(item[1], str):
  80. wencai_res.append(item[0] + "\n" + item[1])
  81. elif isinstance(item[1], dict):
  82. if "meta" in item[1].keys():
  83. continue
  84. wencai_res.append(pd.DataFrame.from_dict(item[1], orient='index').to_markdown())
  85. elif isinstance(item[1], pd.DataFrame):
  86. if "image_url" in item[1].columns:
  87. continue
  88. wencai_res.append(item[1].to_markdown())
  89. else:
  90. wencai_res.append(item[0] + "\n" + str(item[1]))
  91. self.set_output("report", "\n\n".join(wencai_res))
  92. return self.output("report")
  93. except Exception as e:
  94. last_e = e
  95. logging.exception(f"WenCai error: {e}")
  96. time.sleep(self._param.delay_after_error)
  97. if last_e:
  98. self.set_output("_ERROR", str(last_e))
  99. return f"WenCai error: {last_e}"
  100. assert False, self.output()
  101. def thoughts(self) -> str:
  102. return "Pulling live financial data for `{}`.".format(self.get_input().get("query", "-_-!"))