- 具体注册tushre,获取token不多在这里介绍了,官网对操作及接口描述很清晰
- tushare官网地址tushare
- 从tushare返回的数据是pandas.DataFrame数据类型,为了能够将数据写入数据库,需要使用numpy将其转换成列表,逐行写入
- 使用numpy中的array方法将返回的数据表转换成多维数组,再使用tolist方法将多维数组转换成列表
- 代码如下:
import tushare as ts
import pymysql
import numpy as np
ts.set_token('你的token')
pro = ts.pro_api()
data = pro.stock_basic(exchange='', list_status='L',fields='ts_code,symbol,name,area,industry,fullname,enname,market,exchange,curr_type,list_status,list_date,delist_date,is_hs')
print(data)
dataset = np.array(data)
datalist = dataset.tolist()
db = pymysql.connect(host='localhost', port=3306, user='xxx', passwd='xxx', db='tushare', charset='utf8mb4')
cursor = db.cursor()
sql = "delete from stock_list"
try:
cursor.execute(sql)
db.commit()
except Exception as e:
print(e)
db.rollback()
cursor.close()
cursor = db.cursor()
sql = "INSERT INTO stock_list (`ts_code`, `symbol`, `name`, `area`, `industry`, `fullname`, `enname`, `market`, `exchange`, `curr_type`, `list_status`, `list_date`, `delist_date`, `is_hs`) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
try:
cursor.executemany(sql, datalist)
db.commit()
except Exception as e:
print(e)
db.rollback()
cursor.close()
db.close()