update_data_tosql.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. fre = '1d'
  10. print('ready to write to mysql')
  11. for stock in stocks[0:80]:
  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. startdate = pd.read_sql_table('stk%s_%s' % (stock, fre), con=engine).iloc[-1, 1] + datetime.timedelta(days=1)
  17. print(startdate)
  18. df_stock = get_price(stock, start_date=startdate, end_date=dt.today().strftime('%Y-%m-%d %H:%M:%S'),
  19. frequency=fre, fields=['open', 'close', 'high', 'low', 'volume', 'money'],
  20. skip_paused=False,
  21. fq='pre', count=None, panel=False)
  22. df_stock = df_stock.dropna(axis=0)
  23. df_stock.reset_index(inplace=True)
  24. df_stock.rename(columns={'index': 'date'}, inplace=True)
  25. df_stock.index = df_stock.index + index_len + 1
  26. df_stock.to_sql('stk%s_%s' % (stock, fre), con=engine, index=True, if_exists='append')
  27. except BaseException:
  28. df_stock = get_price(stock, start_date='2022-01-01 00:00:00', end_date=dt.today().strftime('%Y-%m-%d %H:%M:%S'),
  29. frequency=fre, fields=['open', 'close', 'high', 'low', 'volume', 'money'],
  30. skip_paused=False,
  31. fq='pre', count=None, panel=False)
  32. df_stock = df_stock.dropna(axis=0)
  33. df_stock.reset_index(inplace=True)
  34. df_stock.rename(columns={'index': 'date'}, inplace=True)
  35. df_stock.to_sql('stk%s_%s' % (stock, fre), con=engine, index=True, if_exists='append')
  36. with engine.connect() as con:
  37. con.execute("ALTER TABLE `stk%s_%s` ADD PRIMARY KEY (`date`);" % (stock, fre))