编程语言:python
编程工具:pycharm
数据来源:tushare
连接mysql方式:SQLAlchemy
1、创建“股票列表”表结构,存为mysql_tables_structure.py
# coding=utf-8from sqlalchemy import Column, String, Floatfrom sqlalchemy.ext.declarative import declarative_baseBase = declarative_base()class StockBasic(Base):"""股票列表is_hs strN是否沪深港通标的,N否 H沪股通 S深股通list_statusstrN上市状态: L上市 D退市 P暂停上市exchangestrN交易所 SSE上交所 SZSE深交所 HKEX港交所(未上线)"""__tablename__ = 'stock_basic'ts_code = Column(String(10), primary_key=True) # TS代码symbol = Column(String(10)) # 股票代码name = Column(String(10)) # 股票名称area = Column(String(4)) # 所在地域industry = Column(String(4)) # 所属行业fullname = Column(String(30)) # 股票全称enname = Column(String(100)) # 英文全称market = Column(String(3))# 市场类型 (主板/中小板/创业板)exchange = Column(String(4)) # 交易所代码curr_type = Column(String(3)) # 交易货币list_status = Column(String(1))# 上市状态: L上市 D退市 P暂停上市list_date = Column(String(8)) # 上市日期delist_date = Column(String(8))# 退市日期is_hs = Column(String(1)) # 是否沪深港通标的,N否 H沪股通 S深股通
2、建立获取tushare数据函数,存为tushare_data.py
# coding=utf-8import timeimport pandas as pddef get_stock_basic(pro, retry_count=3, pause=2):"""股票列表 数据"""frame = []for status in ['L', 'D', 'P']:for _ in range(retry_count):try:df = pro.stock_basic(exchange='', list_status=status,fields='ts_code,symbol,name,area,industry,fullname,enname,market, \exchange,curr_type,list_status,list_date,delist_date,is_hs')except:time.sleep(pause)else:frame.append(df)breakreturn frame
3、更新“股票列表”数据,存为mysql_functions.py
# coding=utf-8import pandas as pdimport tushare_data as tddef truncate_update(engine, data, table_name):"""删除mysql表所有数据,to_sql追加新数据"""conn = engine.connect()conn.execute('truncate ' + table_name)data.to_sql(table_name, engine, if_exists='append', index=False)def update_stock_basic(engine, pro, retry_count, pause):"""更新 股票信息 所有数据"""data = td.get_stock_basic(pro, retry_count, pause)truncate_update(engine, data, 'stock_basic')
4、主程序
# coding=utf-8import pandas as pdimport tushare as tsfrom sqlalchemy import create_enginefrom mysql_tables_structure import Baseimport mysql_functions as mf# 创建数据库引擎engine = create_engine(mysql://root:****@127.0.0.1/databasename?charset=utf8mb4) conn = engine.connect()# 创建mysql所有表结构Base.metadata.create_all(engine)# 连接 tusharets.set_token(token****)pro = ts.pro_api()# 股票列表mf.update_stock_basic(engine, pro, 3, 2)
tushare注册链接:https://tushare.pro/register?reg=258131