download_data_whole.py 3.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. pool_recycle=3600, pool_pre_ping=True, pool_size=100)
  17. def err_call_back(err):
  18. print(f'问题在这里~ error:{str(err)}')
  19. traceback.print_exc()
  20. def to_sql(stock_list):
  21. print(f'{dt.now()}开始循环入库! MyPid is {os.getpid()}')
  22. m = 0
  23. for stock in stock_list:
  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. df.to_sql('%s_1d' % stock, con=eng_w, index=True, if_exists='replace')
  42. except BaseException:
  43. print(stock)
  44. pass
  45. else:
  46. m += 1
  47. print(f'Pid:{os.getpid()}已经完工了.应入库{len(stock_list)},共入库{m}支个股')
  48. def download_data():
  49. stock_list = xtdata.get_stock_list_in_sector('沪深A股')
  50. stock_list.sort()
  51. print(dt.now(), '开始下载!')
  52. xtdata.download_history_data2(stock_list=stock_list, period='1d', start_time='', end_time='')
  53. print(dt.now(), '下载完成,准备入库!')
  54. step = math.ceil(len(stock_list) / mp.cpu_count())
  55. pool = mp.Pool(processes=mp.cpu_count())
  56. # pool = mp.Pool(processes=8)
  57. # step = math.ceil(len(stock_list) / 8)
  58. for i in range(0, len(stock_list), step):
  59. pool.apply_async(func=to_sql, args=(stock_list[i:i+step],), error_callback=err_call_back)
  60. pool.close()
  61. pool.join()
  62. print(f'今日数据下载完毕 {dt.now()}')
  63. if __name__ == '__main__':
  64. field = ['time', 'open', 'close', 'high', 'low', 'volume', 'amount']
  65. cpu_count = mp.cpu_count()
  66. pus = psutil.Process()
  67. # pus.cpu_affinity([12, 13, 14, 15, 16, 17, 18, 19])
  68. download_data()
  69. scheduler = BlockingScheduler()
  70. scheduler.add_job(func=download_data, trigger='cron', day_of_week='0-4', hour='20', minute='05',
  71. timezone="Asia/Shanghai")
  72. try:
  73. scheduler.start()
  74. except (KeyboardInterrupt, SystemExit):
  75. pass