python 通过tushare.pro获取股票日线数据并写入mysql数据库

#通过tushare.pro下载股票日线数据
import pandas as pd
import tushare as ts
import pymysql
pymysql.install_as_MySQLdb()

""" www.jjddlc.com"""
"""作者:Pgabc"""

def stock_daily_get(code_wm,start_dt,end_dt):
    #先要建立mysql数据库
    from sqlalchemy import create_engine
    #root后面为mysql数据库root密码
    cn = create_engine('mysql+pymysql://root:XXXXXXXXXXX@localhost:3306/stock?charset=utf8')
    #tushare.pro注册并获得token
    #设置tushare pro的token并获取连接
    ts.set_token('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
    pro = ts.pro_api()
    stock_fields = 'ts_code,trade_date,open,high,low,close,pre_close,change,pct_chg,vol,amount'
    df = pro.daily(ts_code=code_wm, start_date=start_dt, end_date=end_dt,fields=stock_fields)
    df.to_sql('stock_{}'.format(code_wm),cn,index=False)
    print('{}日线行情成功导入数据库'.format(code_wm))

if __name__=='__main__':
    code_wm = '600666.SH'
    start_dt = '20010101'
    end_dt = '20190519'
    stock_daily_get(code_wm, start_dt, end_dt)


你可能感兴趣的:(python 通过tushare.pro获取股票日线数据并写入mysql数据库)