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.

tushare.py 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 json
  17. from abc import ABC
  18. import pandas as pd
  19. import time
  20. import requests
  21. from agent.component.base import ComponentBase, ComponentParamBase
  22. class TuShareParam(ComponentParamBase):
  23. """
  24. Define the TuShare component parameters.
  25. """
  26. def __init__(self):
  27. super().__init__()
  28. self.token = "xxx"
  29. self.src = "eastmoney"
  30. self.start_date = "2024-01-01 09:00:00"
  31. self.end_date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  32. self.keyword = ""
  33. def check(self):
  34. self.check_valid_value(self.src, "Quick News Source",
  35. ["sina", "wallstreetcn", "10jqka", "eastmoney", "yuncaijing", "fenghuang", "jinrongjie"])
  36. class TuShare(ComponentBase, ABC):
  37. component_name = "TuShare"
  38. def _run(self, history, **kwargs):
  39. ans = self.get_input()
  40. ans = ",".join(ans["content"]) if "content" in ans else ""
  41. if not ans:
  42. return TuShare.be_output("")
  43. try:
  44. tus_res = []
  45. params = {
  46. "api_name": "news",
  47. "token": self._param.token,
  48. "params": {"src": self._param.src, "start_date": self._param.start_date,
  49. "end_date": self._param.end_date}
  50. }
  51. response = requests.post(url="http://api.tushare.pro", data=json.dumps(params).encode('utf-8'))
  52. response = response.json()
  53. if response['code'] != 0:
  54. return TuShare.be_output(response['msg'])
  55. df = pd.DataFrame(response['data']['items'])
  56. df.columns = response['data']['fields']
  57. tus_res.append({"content": (df[df['content'].str.contains(self._param.keyword, case=False)]).to_markdown()})
  58. except Exception as e:
  59. return TuShare.be_output("**ERROR**: " + str(e))
  60. if not tus_res:
  61. return TuShare.be_output("")
  62. return pd.DataFrame(tus_res)