ths_api.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. import hug
  2. from bottle import route, run, NORUN
  3. import iFinDPy as THS
  4. import json
  5. import time
  6. import logging
  7. logger = logging.getLogger('ths_api')
  8. logger.setLevel(logging.DEBUG) # 设置日志级别
  9. hug.API(__name__).http.output_format = hug.output_format.json
  10. username = ""
  11. password = ""
  12. file_handler = logging.FileHandler('ths_api.log')
  13. file_handler.setLevel(logging.DEBUG)
  14. formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  15. file_handler.setFormatter(formatter)
  16. logger.addHandler(file_handler)
  17. @hug.get('/hz_server')
  18. def hello():
  19. return 1
  20. # return 'wind true'
  21. # 同花顺登录函数
  22. def thslogin():
  23. # 输入用户的帐号和密码
  24. thsLogin = THS.THS_iFinDLogin(username, password)
  25. print(thsLogin)
  26. if (thsLogin == 0 or thsLogin == -201):
  27. print('ths 登录成功')
  28. logger.info('ths login success')
  29. else:
  30. print('ths 登录失败')
  31. logger.info('ths login fail')
  32. @hug.get('/edbInfo/ths')
  33. def GetEdbDataByThs(EdbCode, StartDate, EndDate):
  34. print("GetEdbDataByThs")
  35. logger.info('GetEdbDataByThs')
  36. thsEDBDataQuery = THS.THS_EDBQuery(EdbCode, StartDate, EndDate, True)
  37. print(thsEDBDataQuery)
  38. logger.info(thsEDBDataQuery)
  39. print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":start GetEdbDataByThs")
  40. print("thsEDBDataQuery")
  41. print(thsEDBDataQuery)
  42. thsEDBDataQuery = thsEDBDataQuery.decode("unicode_escape")
  43. result = json.loads(thsEDBDataQuery)
  44. print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":end GetEdbDataByThs")
  45. if result["errorcode"] == -1010:
  46. thsLogin = THS.THS_iFinDLogin(username, password)
  47. print("登录一次")
  48. print(thsLogin)
  49. logger.info("ths login")
  50. if (thsLogin == 0 or thsLogin == -201):
  51. thsEDBDataQuery = THS.THS_EDBQuery(EdbCode, StartDate, EndDate, True)
  52. thsEDBDataQuery = thsEDBDataQuery.decode("unicode_escape")
  53. result = json.loads(thsEDBDataQuery)
  54. logger.info("login success")
  55. else:
  56. print("已登录")
  57. return result
  58. @hug.get('/edbInfo/ths/future_good')
  59. def GetFutureGoodEdbDataByThs(EdbCode, StartDate, EndDate):
  60. print("THS_HistoryQuotes start")
  61. logger.info('THS_HistoryQuotes get')
  62. filed = 'lastclose,open,high,low,close,avgprice,change,changeper,volume,amount,hsl,lastsettlement,settlement,zdsettlement,zdfsettlement,ccl,ccbd,zf,zjlx,zjcd'
  63. # filed = 'open,high,low,close,volume,amount,settlement,ccl,zjlx'
  64. params = 'Interval:D,CPS:1,baseDate:1900-01-01,Currency:YSHB,fill:Previous'
  65. # params = 'YSHB;Tradedays'
  66. # print(params)
  67. thsEDBDataQuery = THS.THS_HistoryQuotes(EdbCode, filed, params, StartDate, EndDate, True)
  68. # thsEDBDataQuery = THS.THS_HQ(EdbCode, filed, params, StartDate, EndDate)
  69. # thsEDBDataQuery = THS.THS_EDBQuery(EdbCode, StartDate, EndDate, True)
  70. print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":start GetFutureGoodEdbDataByThs")
  71. print("THS_HistoryQuotes end")
  72. print(thsEDBDataQuery)
  73. logger.info(thsEDBDataQuery)
  74. thsEDBDataQuery = thsEDBDataQuery.decode("unicode_escape")
  75. result = json.loads(thsEDBDataQuery)
  76. if result["errorcode"] == -1010:
  77. thsLogin = THS.THS_iFinDLogin(username, password)
  78. print("登录一次")
  79. print(thsLogin)
  80. logger.info('THS_HistoryQuotes login')
  81. if (thsLogin == 0 or thsLogin == -201):
  82. thsEDBDataQuery = THS.THS_HistoryQuotes(EdbCode, filed, params, StartDate, EndDate, True)
  83. thsEDBDataQuery = thsEDBDataQuery.decode("unicode_escape")
  84. result = json.loads(thsEDBDataQuery)
  85. else:
  86. print("已登录")
  87. print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":end GetFutureGoodEdbDataByThs")
  88. return result
  89. def ths_data_to_dict(ths_instance):
  90. if ths_instance is not None and ths_instance.data is not None:
  91. return {
  92. 'errorcode': ths_instance.errorcode,
  93. 'errmsg': ths_instance.errmsg,
  94. 'data': ths_instance.data.to_dict(orient='records')
  95. }
  96. else:
  97. # 处理 ths_instance 为 None 的情况
  98. return {
  99. 'errorcode': 'N/A',
  100. 'errmsg': 'N/A',
  101. 'data': []
  102. }
  103. def has_comma(input_string):
  104. return isinstance(input_string, str) and ',' in input_string
  105. def process_single_edb_code(StockCode, SingleEdbCode, StartDate, EndDate, ExtraPars=''):
  106. strExtra = ','.join(map(str, ExtraPars))
  107. print(strExtra)
  108. thsEDBDataQuery = THS.THS_DS(StockCode, SingleEdbCode, strExtra, '', StartDate, EndDate)
  109. print(thsEDBDataQuery)
  110. result = json.dumps(ths_data_to_dict(thsEDBDataQuery))
  111. return result
  112. @hug.get('/edbInfo/ths/ds')
  113. def GetEdbDataByThsDs(StockCode, EdbCode, StartDate, EndDate, ExtraPars=''):
  114. print("GetEdbDataByThsDs-> StockCode: {}; EdbCode: {}; StartDate: {}; EndDate: {}; ExtraPars: {}".format(StockCode,
  115. EdbCode,
  116. StartDate,
  117. EndDate,
  118. ExtraPars))
  119. result_list = []
  120. if isinstance(EdbCode, list):
  121. for SingleEdbCode in EdbCode:
  122. result_list.append(process_single_edb_code(StockCode, SingleEdbCode, StartDate, EndDate, ExtraPars))
  123. print("THS_DS end")
  124. print(result_list)
  125. return result_list
  126. else:
  127. # 如果不包含逗号,直接处理
  128. result = process_single_edb_code(StockCode, EdbCode, StartDate, EndDate, ExtraPars)
  129. print(result)
  130. return result
  131. @hug.get('/edbInfo/ths/hf')
  132. def GetEdbDataByThsHf(codes, indicators, function_para, start_time, end_time):
  133. print("codes: {}; indicators: {}; function_para: {}; start_time: {}; end_time: {}".format(codes, indicators,
  134. function_para, start_time,
  135. end_time))
  136. data_query = THS.THS_HF(codes, indicators, function_para, start_time, end_time)
  137. print("data_query: {}".format(data_query))
  138. if data_query.errorcode == -1010 or data_query.errorcode == -209:
  139. ths_login = THS.THS_iFinDLogin(username, password)
  140. print("登录一次")
  141. print("ths_login: {}".format(ths_login))
  142. if ths_login == 0 or ths_login == -201:
  143. repeat_query = THS.THS_HF(codes, indicators, function_para, start_time, end_time)
  144. print("repeat_query: {}".format(repeat_query))
  145. return json.dumps(ths_data_to_dict(repeat_query), indent=2)
  146. else:
  147. return json.dumps(ths_data_to_dict(data_query), indent=2)
  148. if __name__ == "__main__":
  149. # ths登录函数
  150. thslogin()
  151. app = __hug__.http.server()
  152. run(app=app, reloader=True, host='0.0.0.0', port=7000)