update_data_tosql.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. from jqdatasdk import *
  2. from sqlalchemy import create_engine
  3. import pandas as pd
  4. from datetime import datetime as dt
  5. import datetime
  6. auth('18616891214', 'Ea?*7f68nD.dafcW34d!')
  7. stocks = list(get_all_securities(['stock'], date=dt.today().strftime('%Y-%m-%d')).index)
  8. engine = create_engine('mysql+pymysql://root:r6kEwqWU9!v3@localhost:3307/stocks?charset=utf8')
  9. for fre in ['30m', '1d']:
  10. print('ready to write to mysql %s' % fre)
  11. for stock in stocks:
  12. print(stock)
  13. try:
  14. index_len = pd.read_sql_table('stk%s_%s' % (stock, fre), con=engine).iloc[-1, 0]
  15. # 注意修改time delta
  16. if fre == '1d':
  17. startdate = pd.read_sql_table('stk%s_%s' % (stock, fre), con=engine).iloc[-1, 1] + datetime.timedelta(
  18. days=1)
  19. elif fre == '30m':
  20. startdate = pd.read_sql_table('stk%s_%s' % (stock, fre), con=engine).iloc[-1, 1] + datetime.timedelta(
  21. minutes=5)
  22. print(startdate)
  23. df_stock = get_price(stock, start_date=startdate, end_date=dt.today().strftime('%Y-%m-%d %H:%M:%S'),
  24. frequency=fre, fields=['open', 'close', 'high', 'low', 'volume', 'money'],
  25. skip_paused=False,
  26. fq='pre', count=None, panel=False)
  27. df_stock = df_stock.dropna(axis=0)
  28. df_stock.reset_index(inplace=True)
  29. df_stock.rename(columns={'index': 'date'}, inplace=True)
  30. df_stock.index = df_stock.index + index_len + 1
  31. df_stock.to_sql('stk%s_%s' % (stock, fre), con=engine, index=True, if_exists='append')
  32. except BaseException:
  33. df_stock = get_price(stock, start_date='2022-01-01 00:00:00', end_date=dt.today().strftime('%Y-%m-%d %H:%M:%S'),
  34. frequency=fre, fields=['open', 'close', 'high', 'low', 'volume', 'money'],
  35. skip_paused=False,
  36. fq='pre', count=None, panel=False)
  37. df_stock = df_stock.dropna(axis=0)
  38. df_stock.reset_index(inplace=True)
  39. df_stock.rename(columns={'index': 'date'}, inplace=True)
  40. df_stock.to_sql('stk%s_%s' % (stock, fre), con=engine, index=True, if_exists='append')
  41. with engine.connect() as con:
  42. con.execute("ALTER TABLE `stk%s_%s` ADD PRIMARY KEY (`date`);" % (stock, fre))