get_hisbars_tosql.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from jqdatasdk import *
  2. auth('18616891214','Ea?*7f68nD.dafcW34d!')
  3. from sqlalchemy import create_engine
  4. import pandas as pd
  5. import threading
  6. from datetime import datetime as dt
  7. import pymysql
  8. starttime = dt.now()
  9. stocks = list(get_all_securities(['stock'], date='2021-12-31').index)
  10. print('ready to get bars')
  11. # df = get_bars(stocks, count=2000, unit='1d',
  12. # fields=['date', 'open', 'close', 'high', 'low', 'volume', 'money'], include_now=False, df=True)
  13. # db = pymysql.connect(host='localhost',
  14. # user='root',
  15. # password='r6kEwqWU9!v3',
  16. # database='stocks',
  17. # connect_timeout=600)
  18. # # db_stk_sql = pymysql.connect(host='chenzheshi.myds.me',
  19. # port=3456,
  20. # user='root',
  21. # password='r6kEwqWU9!v3',
  22. # database='stocks',
  23. # connect_timeout=600)
  24. # cursor = db.cursor()
  25. engine = create_engine('mysql+pymysql://root:r6kEwqWU9!v3@localhost:3307/stocks?charset=utf8')
  26. print('ready to write to mysql')
  27. fre = '30m'
  28. for stock in stocks:
  29. # df_stock =df.loc[stock]
  30. print(stock)
  31. df_stock = get_price(stock, start_date='2010-01-01 00:00:00', end_date=dt.today().strftime('%Y-%m-%d %H:%M:%S'),
  32. frequency=fre, fields=['open', 'close', 'high', 'low', 'volume', 'money'], skip_paused=False,
  33. fq='pre', count=None, panel=False)
  34. df_stock.reset_index(inplace=True)
  35. df_stock.rename(columns={'index': 'date'}, inplace=True)
  36. df_stock.to_sql('stk%s_%s' % (stock[:6], fre), con=engine, index=True, if_exists='replace')
  37. with engine.connect() as con:
  38. con.execute('ALTER TABLE stk%s_%s ADD PRIMARY KEY (`date`);' % (stock[:6], fre))
  39. endtime = dt.now()
  40. # db_stk_sql.close()
  41. print((endtime-starttime).seconds)