download_data_whole.py 3.5 KB

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