ths_api.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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, Days='', Interval='', ExtraPars=''):
  106. strExtra = ','.join(map(str, ExtraPars))
  107. print(strExtra)
  108. funcParas = []
  109. if Days:
  110. funcParas.append(f"Days:{Days}")
  111. if Interval:
  112. funcParas.append(f"Interval:{Interval}")
  113. funcPara = ",".join(funcParas)
  114. thsEDBDataQuery = THS.THS_DS(StockCode, SingleEdbCode, strExtra, funcPara, StartDate, EndDate)
  115. print(thsEDBDataQuery)
  116. result = json.dumps(ths_data_to_dict(thsEDBDataQuery))
  117. return result
  118. @hug.get('/edbInfo/ths/ds')
  119. def GetEdbDataByThsDs(StockCode, EdbCode, StartDate, EndDate, Days='', Interval='', ExtraPars=''):
  120. print(
  121. "GetEdbDataByThsDs-> StockCode: {}; EdbCode: {}; StartDate: {}; EndDate: {}; Days: {}; Interval: {}; ExtraPars: {}".format(
  122. StockCode,
  123. EdbCode,
  124. StartDate,
  125. EndDate,
  126. Days,
  127. Interval,
  128. ExtraPars))
  129. result_list = []
  130. if isinstance(EdbCode, list):
  131. for SingleEdbCode in EdbCode:
  132. result_list.append(
  133. process_single_edb_code(StockCode, SingleEdbCode, StartDate, EndDate, Days, Interval, ExtraPars))
  134. print("THS_DS end")
  135. print(result_list)
  136. return result_list
  137. else:
  138. # 如果不包含逗号,直接处理
  139. result = process_single_edb_code(StockCode, EdbCode, StartDate, EndDate, Days, Interval, ExtraPars)
  140. print(result)
  141. return result
  142. @hug.get('/edbInfo/ths/hf')
  143. def GetEdbDataByThsHf(codes, indicators, function_para, start_time, end_time):
  144. print("codes: {}; indicators: {}; function_para: {}; start_time: {}; end_time: {}".format(codes, indicators,
  145. function_para, start_time,
  146. end_time))
  147. data_query = THS.THS_HF(codes, indicators, function_para, start_time, end_time)
  148. print("data_query: {}".format(data_query))
  149. if data_query.errorcode == -1010 or data_query.errorcode == -209:
  150. ths_login = THS.THS_iFinDLogin(username, password)
  151. print("登录一次")
  152. print("ths_login: {}".format(ths_login))
  153. if ths_login == 0 or ths_login == -201:
  154. repeat_query = THS.THS_HF(codes, indicators, function_para, start_time, end_time)
  155. print("repeat_query: {}".format(repeat_query))
  156. return json.dumps(ths_data_to_dict(repeat_query), indent=2)
  157. else:
  158. return json.dumps(ths_data_to_dict(data_query), indent=2)
  159. if __name__ == "__main__":
  160. # ths登录函数
  161. thslogin()
  162. app = __hug__.http.server()
  163. run(app=app, reloader=True, host='0.0.0.0', port=7000)