real_time_update_qbh_hlfx_1025.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. from jqdatasdk import *
  2. import pandas as pd
  3. import pymysql
  4. from sqlalchemy import create_engine
  5. import threading
  6. from datetime import datetime as dt
  7. from jqdatasdk.technical_analysis import *
  8. auth('18616891214', 'Ea?*7f68nD.dafcW34d!')
  9. # auth('18521506014', 'Abc123!@#')
  10. stocks = list(get_all_securities(['stock'], date=dt.today().strftime('%Y-%m-%d')).index)
  11. # stocks = stocks[0:200]
  12. def hlfx(stocks, engine_stock, engine_hlfx):
  13. for thd.stock in stocks:
  14. print(thd.stock)
  15. if ('stk%s_%s' % (thd.stock, fre)) in table_list:
  16. # 有历史数据
  17. index_len = pd.read_sql_table('stk%s_%s' % (thd.stock, fre), con=engine_hlfx).iloc[-1, 0]
  18. startdate = pd.read_sql_table('stk%s_%s' % (thd.stock, fre), con=engine_hlfx).iloc[-1, 1]
  19. # thd.get_price = pd.read_sql_query(
  20. # 'select date,open,close,high,low,volume,money from `stk%s_%s`' % (thd.stock, fre), engine_stock)
  21. # thd.get_price = thd.get_price.loc[thd.get_price['date'] > startdate]
  22. thd.get_price = df.loc[thd.stock]
  23. thd.df_day = pd.read_sql_query(
  24. 'select date,open,close,high,low,volume,money,HL from `stk%s_%s`' % (thd.stock, fre), engine_hlfx)
  25. # 先处理去包含
  26. for i in thd.get_price.index:
  27. # 不包含
  28. if (thd.df_day.iloc[-1, 3] > thd.get_price.loc[i, 'high']
  29. and thd.df_day.iloc[-1, 4] > thd.get_price.loc[i, 'low']) \
  30. or (thd.df_day.iloc[-1, 3] < thd.get_price.loc[i, 'high']
  31. and thd.df_day.iloc[-1, 4] < thd.get_price.loc[i, 'low']):
  32. thd.df_day = pd.concat([thd.df_day, thd.get_price.loc[[i]]], ignore_index=True)
  33. # 包含
  34. else:
  35. # (new_df.iloc[-1,3]>=df_day.loc[i,'high'] and new_df.iloc[-1,4]<= df_day.loc[i,'low']):
  36. # 左高,下降
  37. if thd.df_day.iloc[-2, 3] > thd.df_day.iloc[-1, 3]:
  38. thd.df_day.iloc[-1, 3] = min(thd.df_day.iloc[-1, 3], thd.get_price.loc[i, 'high'])
  39. thd.df_day.iloc[-1, 4] = min(thd.df_day.iloc[-1, 4], thd.get_price.loc[i, 'low'])
  40. else:
  41. # 右高,上升
  42. thd.df_day.iloc[-1, 3] = max(thd.df_day.iloc[-1, 3], thd.get_price.loc[i, 'high'])
  43. thd.df_day.iloc[-1, 4] = max(thd.df_day.iloc[-1, 4], thd.get_price.loc[i, 'low'])
  44. # 寻找顶底分型
  45. if len(thd.df_day.index) > 2:
  46. x = len(thd.df_day.index)-1
  47. m = x - 1
  48. # 底
  49. if ((thd.df_day.loc[x, 'high'] > thd.df_day.loc[x - 1, 'high']) and (
  50. thd.df_day.loc[x - 2, 'high'] > thd.df_day.loc[x - 1, 'high'])):
  51. # if ((stk.df_day.loc[i-2, 'date'] != stk.fxdf.iloc[-1,0]) and (stk.df_day.loc[i-3,'date'] != stk.fxdf.iloc[-1,0]) and (stk.df_day.loc[i-1,'date'] != stk.fxdf.iloc[-1,0])):
  52. # stk.fxdf = pd.concat([stk.fxdf, stk.df_day.iloc[[i]]], ignore_index=True)
  53. thd.df_day.loc[x, 'HL'] = 'L*'
  54. while m:
  55. if thd.df_day.loc[m, 'HL'] == 'H':
  56. if (x - m) > 3:
  57. thd.df_day.loc[x, 'HL'] = 'L'
  58. # 此处可以获得MACD指标
  59. # pre-macd_dif, pre-macd_dea, pre-macd_macd = MACD(thd.stock,check_date=thd.df_day.loc[m, 'datetime'], SHORT = 12, LONG = 26, MID = 9)
  60. # pass
  61. print(thd.stock, '$$$$$$$', '\n', thd.df_day.loc[x, 'date'], '\n',
  62. '笔形成————买买买买买!!')
  63. results.append(thd.stock)
  64. print('222')
  65. # break
  66. elif (thd.df_day.loc[m, 'HL'] == 'L'):
  67. if thd.df_day.loc[x - 1, 'low'] < thd.df_day.loc[m - 1, 'low']:
  68. # 前一个为底,且中间存在不包含 or 更低的底
  69. thd.df_day.loc[x, 'HL'] = 'L'
  70. x_macd_dif, x_macd_dea, x_macd_macd = MACD(thd.stock,
  71. check_date=thd.df_day.loc[x, 'date'],
  72. SHORT=12, LONG=26, MID=9, unit=fre)
  73. m_macd_dif, m_macd_dea, m_macd_macd = MACD(thd.stock,
  74. check_date=thd.df_day.loc[m, 'date'],
  75. SHORT=12, LONG=26, MID=9, unit=fre)
  76. if x_macd_dif[thd.stock] > m_macd_dif[thd.stock]:
  77. # pass
  78. # print(thd.df_day.loc[m, 'date'], thd.df_day.loc[m, 'low'],
  79. # m_macd_dif[thd.stock])
  80. # print(thd.df_day.loc[x, 'date'], thd.df_day.loc[x, 'low'],
  81. # x_macd_dif[thd.stock])
  82. print(thd.stock, '$$$$$$$', '\n', thd.df_day.loc[x, 'date'], 'MACD背驰————买吗?!')
  83. results.append(thd.stock)
  84. print('333')
  85. break
  86. else:
  87. # 底更低但没有背驰
  88. break
  89. m = m - 1
  90. if m == 0:
  91. # 第一个底
  92. thd.df_day.loc[x, 'HL'] = 'L'
  93. results.append(thd.stock)
  94. print('444')
  95. # 顶
  96. elif ((thd.df_day.loc[x, 'high'] < thd.df_day.loc[x - 1, 'high']) and (
  97. thd.df_day.loc[x - 2, 'high'] < thd.df_day.loc[x - 1, 'high'])):
  98. # if ((stk.df_day.loc[i-2, 'date'] != stk.fxdf.iloc[-1,0]) and (stk.df_day.loc[i-3,'date'] != stk.fxdf.iloc[-1,0]) and (stk.df_day.loc[i-1,'date'] != stk.fxdf.iloc[-1,0])):
  99. # stk.fxdf = pd.concat([stk.fxdf, stk.df_day.iloc[[i]]], ignore_index=True)
  100. thd.df_day.loc[x, 'HL'] = 'H*'
  101. while m:
  102. if thd.df_day.loc[m, 'HL'] == 'L':
  103. if x - m > 3:
  104. thd.df_day.loc[x, 'HL'] = 'H'
  105. print(thd.stock, '!!!!!!!', '\n', thd.df_day.loc[x, 'date'], '笔形成————卖卖卖卖卖卖卖!')
  106. # pass
  107. results_short.append(thd.stock)
  108. if thd.stock in results:
  109. results.remove(thd.stock)
  110. # break
  111. elif (thd.df_day.loc[m, 'HL'] == 'H'):
  112. if thd.df_day.loc[x - 1, 'high'] > thd.df_day.loc[m - 1, 'high']:
  113. # 前一个为顶,且中间存在不包含 or 更高的顶
  114. thd.df_day.loc[x, 'HL'] = 'H'
  115. x_macd_dif, x_macd_dea, x_macd_macd = MACD(thd.stock,
  116. check_date=thd.df_day.loc[x, 'date'],
  117. SHORT=12, LONG=26, MID=9, unit=fre)
  118. m_macd_dif, m_macd_dea, m_macd_macd = MACD(thd.stock,
  119. check_date=thd.df_day.loc[m, 'date'],
  120. SHORT=12, LONG=26, MID=9, unit=fre)
  121. if x_macd_dif[thd.stock] < m_macd_dif[thd.stock]:
  122. # pass
  123. print(thd.stock, '/\/\/\/\/\/\/', '顶背离了!!!!')
  124. results_short.append(thd.stock)
  125. if thd.stock in results:
  126. results.remove(thd.stock)
  127. break
  128. break
  129. m = m - 1
  130. if m == 0:
  131. thd.df_day.loc[x, 'HL'] = 'H'
  132. results_short.append(thd.stock)
  133. if thd.stock in results:
  134. results.remove(thd.stock)
  135. else:
  136. thd.df_day.loc[x, 'HL'] = '-'
  137. # 更新数据库
  138. # 可以使用normalize_code(code) 方法 改变代码格式
  139. # thd.df_day[index_len + 1:].to_sql('stk%s_%s' % (thd.stock, fre), con=engine_hlfx, index=True, if_exists='append')
  140. else:
  141. # 没有历史数据表
  142. thd.df_day = pd.DataFrame(columns=('date', 'open', 'close', 'high', 'low', 'volume', 'money', 'HL'))
  143. thd.get_price = pd.read_sql_query(
  144. 'select date,open,close,high,low,volume,money from `stk%s_%s`' % (thd.stock, fre), engine_stock)
  145. # 先处理去包含
  146. for i in thd.get_price.index:
  147. if i == 0 or i == 1:
  148. thd.df_day = pd.concat([thd.df_day, thd.get_price.iloc[[i]]], ignore_index=True)
  149. # 不包含
  150. elif (thd.df_day.iloc[-1, 3] > thd.get_price.loc[i, 'high']
  151. and thd.df_day.iloc[-1, 4] > thd.get_price.loc[i, 'low']) \
  152. or (thd.df_day.iloc[-1, 3] < thd.get_price.loc[i, 'high']
  153. and thd.df_day.iloc[-1, 4] < thd.get_price.loc[i, 'low']):
  154. thd.df_day = pd.concat([thd.df_day, thd.get_price.loc[[i]]], ignore_index=True)
  155. # 包含
  156. else:
  157. # 左高,下降
  158. if thd.df_day.iloc[-2, 3] > thd.df_day.iloc[-1, 3]:
  159. thd.df_day.iloc[-1, 3] = min(thd.df_day.iloc[-1, 3], thd.get_price.loc[i, 'high'])
  160. thd.df_day.iloc[-1, 4] = min(thd.df_day.iloc[-1, 4], thd.get_price.loc[i, 'low'])
  161. else:
  162. # 右高,上升
  163. thd.df_day.iloc[-1, 3] = max(thd.df_day.iloc[-1, 3], thd.get_price.loc[i, 'high'])
  164. thd.df_day.iloc[-1, 4] = max(thd.df_day.iloc[-1, 4], thd.get_price.loc[i, 'low'])
  165. if len(thd.df_day.index) > 2:
  166. # 寻找顶底分型
  167. x = len(thd.df_day.index)-1
  168. m = x - 1
  169. # 底
  170. if ((thd.df_day.loc[x, 'high'] > thd.df_day.loc[x - 1, 'high']) and (
  171. thd.df_day.loc[x - 2, 'high'] > thd.df_day.loc[x - 1, 'high'])):
  172. # if ((stk.df_day.loc[i-2, 'date'] != stk.fxdf.iloc[-1,0]) and (stk.df_day.loc[i-3,'date'] != stk.fxdf.iloc[-1,0]) and (stk.df_day.loc[i-1,'date'] != stk.fxdf.iloc[-1,0])):
  173. # stk.fxdf = pd.concat([stk.fxdf, stk.df_day.iloc[[i]]], ignore_index=True)
  174. thd.df_day.loc[x, 'HL'] = 'L*'
  175. while m:
  176. if thd.df_day.loc[m, 'HL'] == 'H':
  177. if (x - m) > 3:
  178. thd.df_day.loc[x, 'HL'] = 'L'
  179. # 此处可以获得MACD指标
  180. # pre-macd_dif, pre-macd_dea, pre-macd_macd = MACD(thd.stock,check_date=thd.df_day.loc[m, 'datetime'], SHORT = 12, LONG = 26, MID = 9)
  181. # pass
  182. print(thd.stock, '$$$$$$$', '\n', thd.df_day.loc[x, 'date'], '买买买买买!!')
  183. results.append(thd.stock)
  184. # break
  185. elif (thd.df_day.loc[m, 'HL'] == 'L'):
  186. if thd.df_day.loc[x - 1, 'low'] < thd.df_day.loc[m - 1, 'low']:
  187. # 前一个为底,且中间存在不包含 or 更低的底
  188. thd.df_day.loc[x, 'HL'] = 'L'
  189. x_macd_dif, x_macd_dea, x_macd_macd = MACD(thd.stock,
  190. check_date=thd.df_day.loc[x, 'date'],
  191. SHORT=12, LONG=26, MID=9, unit=fre)
  192. m_macd_dif, m_macd_dea, m_macd_macd = MACD(thd.stock,
  193. check_date=thd.df_day.loc[m, 'date'],
  194. SHORT=12, LONG=26, MID=9, unit=fre)
  195. if x_macd_dif[thd.stock] > m_macd_dif[thd.stock]:
  196. # pass
  197. # print(thd.df_day.loc[m, 'date'], thd.df_day.loc[m, 'low'],
  198. # m_macd_dif[thd.stock])
  199. # print(thd.df_day.loc[x, 'date'], thd.df_day.loc[x, 'low'],
  200. # x_macd_dif[thd.stock])
  201. print(thd.stock, '$$$$$$$', '\n', thd.df_day.loc[x, 'date'],
  202. 'MACD背驰————买吗?!')
  203. results.append(thd.stock)
  204. break
  205. else:
  206. break
  207. m = m - 1
  208. if m == 0:
  209. thd.df_day.loc[x, 'HL'] = 'L'
  210. results.append(thd.stock)
  211. # 顶
  212. elif ((thd.df_day.loc[x, 'high'] < thd.df_day.loc[x - 1, 'high']) and (
  213. thd.df_day.loc[x - 2, 'high'] < thd.df_day.loc[x - 1, 'high'])):
  214. # if ((stk.df_day.loc[i-2, 'date'] != stk.fxdf.iloc[-1,0]) and (stk.df_day.loc[i-3,'date'] != stk.fxdf.iloc[-1,0]) and (stk.df_day.loc[i-1,'date'] != stk.fxdf.iloc[-1,0])):
  215. # stk.fxdf = pd.concat([stk.fxdf, stk.df_day.iloc[[i]]], ignore_index=True)
  216. thd.df_day.loc[x, 'HL'] = 'H*'
  217. while m:
  218. if thd.df_day.loc[m, 'HL'] == 'L':
  219. if x - m > 3:
  220. thd.df_day.loc[x, 'HL'] = 'H'
  221. print(thd.stock, '!!!!!!!', '\n', '卖卖卖卖卖卖卖!')
  222. # pass
  223. results.remove(thd.stock)
  224. # break
  225. elif (thd.df_day.loc[m, 'HL'] == 'H'):
  226. if thd.df_day.loc[x - 1, 'high'] > thd.df_day.loc[m - 1, 'high']:
  227. # 前一个为顶,且中间存在不包含 or 更高的顶
  228. thd.df_day.loc[x, 'HL'] = 'H'
  229. x_macd_dif, x_macd_dea, x_macd_macd = MACD(thd.stock,
  230. check_date=thd.df_day.loc[x, 'date'],
  231. SHORT=12, LONG=26, MID=9, unit=fre)
  232. m_macd_dif, m_macd_dea, m_macd_macd = MACD(thd.stock,
  233. check_date=thd.df_day.loc[m, 'date'],
  234. SHORT=12, LONG=26, MID=9, unit=fre)
  235. if x_macd_dif[thd.stock] < m_macd_dif[
  236. thd.stock]:
  237. # pass
  238. print(thd.stock, '/\/\/\/\/\/\/', '顶背离了!!!!')
  239. results.remove(thd.stock)
  240. break
  241. break
  242. m = m - 1
  243. if m == 0:
  244. thd.df_day.loc[x, 'HL'] = 'H'
  245. results.remove(thd.stock)
  246. else:
  247. thd.df_day.loc[x, 'HL'] = '-'
  248. # print(thd.df_day[-20:])
  249. # 更新数据库
  250. # thd.df_day.to_sql('stk%s_%s' % (thd.stock, fre), con=engine_hlfx, index=True, if_exists='append')
  251. start = dt.now()
  252. while True:
  253. now_date = dt.now()
  254. date_morning_begin = now_date.replace(hour=9, minute=25, second=0)
  255. date_morning_end = now_date.replace(hour=11, minute=31, second=0)
  256. date_afternooe_begin = now_date.replace(hour=13, minute=0, second=0)
  257. date_afternooe_end = now_date.replace(hour=15, minute=0, second=0)
  258. # print(now_date,date_morning_begin,date_morning_end,date_afternooe_begin,date_afternooe_end)
  259. # if date_morning_begin < now_date < date_afternooe_end:
  260. if True:
  261. for fre in ['1d']:
  262. start = dt.now()
  263. print(fre)
  264. # 连接数据库
  265. db = pymysql.connect(host='localhost',
  266. user='root',
  267. port=3307,
  268. password='r6kEwqWU9!v3',
  269. database='hlfx')
  270. cursor = db.cursor()
  271. cursor.execute("show tables like '%%%s%%' " % fre)
  272. table_list = [tuple[0] for tuple in cursor.fetchall()]
  273. print('取得 table_list %s' % fre)
  274. db_pool = pymysql.connect(host='localhost',
  275. user='root',
  276. port=3307,
  277. password='r6kEwqWU9!v3',
  278. database='hlfx_pool')
  279. cursor_pool = db_pool.cursor()
  280. stk = locals()
  281. thd = threading.local()
  282. # 进程准备
  283. step = 400
  284. thread_list = []
  285. engine_stock = []
  286. engine_hlfx = []
  287. times_engine = 0
  288. engine_hlfx_pool = create_engine('mysql+pymysql://root:r6kEwqWU9!v3@localhost:3307/hlfx_pool?charset=utf8')
  289. # 获得hlfx_pool池子
  290. # results = pd.read_sql_query(
  291. # 'select value from `%s`' % fre, engine_hlfx_pool)
  292. # for i in range(0, len(results)):
  293. # print(len(results.iloc[i, 0].split(",")))
  294. results = pd.read_sql_query(
  295. 'select value from `%s`' % fre, engine_hlfx_pool).iloc[-1, 0].split(",")
  296. results_short = []
  297. print('数据库读取', len(results))
  298. df = get_bars(stocks, count=5, unit=fre,
  299. fields=['date', 'open', 'close', 'high', 'low', 'volume', 'money'], include_now=True, df=True)
  300. print(df, type(df))
  301. print(df.loc['603566.XSHG'])
  302. print(dt.now(), 'get_bars 成功')
  303. exit()
  304. for i in range(0, len(stocks), step):
  305. engine_stock.append(create_engine('mysql+pymysql://root:r6kEwqWU9!v3@localhost:3307/stocks?charset=utf8'))
  306. engine_hlfx.append(create_engine('mysql+pymysql://root:r6kEwqWU9!v3@localhost:3307/hlfx?charset=utf8'))
  307. thread = threading.Thread(target=hlfx, args=(stocks[i:i + step], engine_stock[times_engine], engine_hlfx[times_engine]))
  308. times_engine = times_engine + 1
  309. thread.start()
  310. thread_list.append(thread)
  311. for thread in thread_list:
  312. thread.join()
  313. db.close()
  314. time = dt.now().strftime('%Y-%m-%d %H:%M:%S')
  315. results_list =','.join(set(results))
  316. print(set(results))
  317. sql = "INSERT INTO %s (date,value) VALUES('%s','%s')" % (fre, dt.now().strftime('%Y-%m-%d %H:%M:%S'), results_list)
  318. cursor_pool.execute(sql)
  319. db_pool.commit()
  320. print(fre, '\n', '做多:', len(set(results)), set(results))
  321. print('做空', len(set(results_short)), set(results_short))
  322. end= dt.now()
  323. print('总时长:', (end - start).seconds)
  324. elif now_date>date_afternooe_end:
  325. pass
  326. # print("HLFX_收盘了",now_date)
  327. # break