download_data_whole.py 3.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. from xtquant import xtdata
  2. from datetime import datetime as dt
  3. import pandas as pd
  4. import math
  5. from sqlalchemy import create_engine, text
  6. import multiprocessing as mp
  7. import os
  8. from apscheduler.schedulers.blocking import BlockingScheduler
  9. import traceback
  10. import psutil
  11. pd.set_option('display.max_columns', None) # 设置显示最大行
  12. path = 'C:\\qmt\\userdata_mini'
  13. field = ['time', 'open', 'close', 'high', 'low', 'volume', 'amount']
  14. cpu_count = mp.cpu_count()
  15. def err_call_back(err):
  16. print(f'问题在这里~ error:{str(err)}')
  17. traceback.print_exc()
  18. def to_sql(stock_list):
  19. print(f'{dt.now()}开始循环入库! MyPid is {os.getpid()}')
  20. m = 0
  21. for stock in stock_list:
  22. eng_w = create_engine('mysql+pymysql://root:r6kEwqWU9!v3@localhost:3307/qmt_stocks_whole?charset=utf8',
  23. pool_recycle=3600, pool_pre_ping=True, pool_size=1)
  24. # 后复权数据
  25. data_back = xtdata.get_market_data(field, [stock], '1d', end_time='', count=-1, dividend_type='back')
  26. df_back = pd.concat([data_back[i].loc[stock].T for i in ['time', 'open', 'high', 'low', 'close', 'volume',
  27. 'amount']], axis=1)
  28. df_back.columns = ['time', 'open_back', 'high_back', 'low_back', 'close_back', 'volume_back', 'amount_back']
  29. df_back['time'] = df_back['time'].apply(lambda x: dt.fromtimestamp(x / 1000.0))
  30. df_back.reset_index(drop=True, inplace=True)
  31. # 前复权数据
  32. data_front = xtdata.get_market_data(field, [stock], '1d', end_time='', count=-1, dividend_type='front')
  33. df_front = pd.concat([data_front[i].loc[stock].T for i in ['time', 'open', 'high', 'low', 'close', 'volume',
  34. 'amount']], axis=1)
  35. df_front.columns = ['time', 'open_front', 'high_front', 'low_front', 'close_front', 'volume_front',
  36. 'amount_front']
  37. df_front['time'] = df_front['time'].apply(lambda x: dt.fromtimestamp(x / 1000.0))
  38. df = pd.merge_asof(df_back, df_front, 'time')
  39. # print(df)
  40. try:
  41. # eng_w.connect().execute(text("truncate table `%s_1d`" % stock))
  42. df.to_sql('%s_1d' % stock, con=eng_w, index=False, if_exists='replace', chunksize=20000)
  43. except BaseException as e:
  44. print(stock, e)
  45. pass
  46. else:
  47. m += 1
  48. eng_w.dispose()
  49. print(f'Pid:{os.getpid()}已经完工了.应入库{len(stock_list)},共入库{m}支个股')
  50. def download_data():
  51. stock_list = xtdata.get_stock_list_in_sector('沪深A股')
  52. stock_list.sort()
  53. print(dt.now(), '开始下载!')
  54. xtdata.download_history_data2(stock_list=stock_list, period='1d', start_time='', end_time='')
  55. print(dt.now(), '下载完成,准备入库!')
  56. step = math.ceil(len(stock_list) / mp.cpu_count())
  57. pool = mp.Pool(processes=mp.cpu_count())
  58. # pool = mp.Pool(processes=8)
  59. # step = math.ceil(len(stock_list) / 8)
  60. for i in range(0, len(stock_list), step):
  61. pool.apply_async(func=to_sql, args=(stock_list[i:i+step],), error_callback=err_call_back)
  62. pool.close()
  63. pool.join()
  64. print(f'今日数据下载完毕 {dt.now()}')
  65. if __name__ == '__main__':
  66. field = ['time', 'open', 'close', 'high', 'low', 'volume', 'amount']
  67. cpu_count = mp.cpu_count()
  68. pus = psutil.Process()
  69. # pus.cpu_affinity([12, 13, 14, 15, 16, 17, 18, 19])
  70. # download_data()
  71. scheduler = BlockingScheduler()
  72. scheduler.add_job(func=download_data, trigger='cron', day_of_week='0-4', hour='20', minute='05',
  73. timezone="Asia/Shanghai", max_instances=10)
  74. try:
  75. scheduler.start()
  76. except (KeyboardInterrupt, SystemExit):
  77. pass