Python tushare 股票数据

tushare 是一个开源的股票数据获取接口,通过它我们可以获取很多股票的详细的数据。
本文主要实现一个简单的历史明细数据获取。
主要涉及,对一个列表内的股票进行遍历,然后查询每支股票过去30天的明细数据,判断当天是不是交易日。然后把这些数据存入数据库。

\# --coding:utf-8 --
import tushare as ts
import time
import datetime #导入日期时间模块
import MySQLdb
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
conn= MySQLdb.connect(
        host='127.0.0.1',
        port = 3306,
        user='root',
        passwd='123',
        db ='test',
        charset="utf8",
        )
cur = conn.cursor()
today = datetime.date.today() #获得今天的日期
codelist =['600000','600036','600001','600016']
for j in range(len(codelist)):
   for k in range(30):
     try:
         yesterday = today - datetime.timedelta(days=k)
         df = ts.get_tick_data(codelist[j],date = str(yesterday),pause = 0.2)
         lines = df.iloc[:,0].size
         if lines == 3:
             continue
         for i in range(lines):

             print df.iloc[i]['time']
             # value = [codelist[j], str(yesterday), str(df.irow(i)['time']), str(df.irow(i)['price']),df.irow(i)['type'],str(df.irow(i)['amount'])]
             # print value
             # sql = "INSERT INTO stock_test(code,date_time,price,type,amount) VALUES (%s, %s,%s,%s,%s)" % (codelist[j],yesterday,df.irow(i)['time'],df.irow(i)['price'],df.irow(i)['type'],df.irow(i)['amount'])
             sql = "INSERT INTO stock_test (code,datec,price,type,amount,timee) VALUES (\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\')" % (
                 codelist[j], str(yesterday), df.iloc[i]['price'], df.iloc[i]['type'], df.iloc[i]['amount'],
             df.iloc[i]['time'])
             cur.execute(sql)
             conn.commit()
             print codelist[j],str(yesterday)+"写入数据库"
             # print codelist[j],yesterday,df.irow(i)['time'],df.irow(i)['price'],df.irow(i)['type'],df.irow(i)['amount']
         # time.sleep(2)
     except :
         time.sleep(2)
         continue
        # print df.head(100)
conn.close()

你可能感兴趣的:(数据库,python)