最近做了一个基金网站,利用tuhsare获取ETF基金数据,然后存入本地mysql。
先建立获取基金的代码
import numpy as np
import pandas as pd
#from keras.optimizers import Adam
import tushare as ts
pro = ts.pro_api('e6cde7f6165daeaa49d539e2de4b4725944d64c70e1685e563eaebe8')
import time
import glob,os
import pymysql
def get_funds_data(code,start_date,end_date):
df = pro.fund_daily(**{
"trade_date": "",
"start_date":start_date,
"end_date": end_date,
"ts_code": code,
"limit": "",
"offset": ""
}, fields=[
"ts_code",
"trade_date",
"pre_close",
"open",
"high",
"low",
"close",
"change",
"pct_chg",
"vol",
"amount"
])
return df
在写一个存入MySQL的代码
for i in range(len(name)):
df=get_funds_data(name[i],start_date=day1,end_date=day1)
df= np.array(df)
time.sleep(0.3)
#将更新基金数据写入数据库
if(len(df)==0):#如果当天没有数据就跳过
continue;
print(tablename[i])
sql = "INSERT INTO "+tablename[i]+"(ts_code,trade_date,pre_close,open,high,low,close,ts_change,pct_chg,vol,amount) \
VALUES ('%s','%s','%s' ,'%s' ,'%s' ,'%s' ,'%s' ,'%s' ,'%s' ,'%s' ,'%s' )" % \
(df[0][0],day,df[0][2],df[0][3],df[0][4],df[0][5],df[0][6],df[0][7],df[0][8],df[0][9],df[0][10])
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
其中调用获取基金的函数,然后将其存入表中