Python大資料分析——多執行緒獲取滬深股票歷史資料
要進行資料分析,得獲取資料。對於金融資料,我們有很多獲取方式,如雅虎金融,谷歌金融,QuantQuote,EODData,下面列出它們具體的地址:
當然,如果要獲取國外金融資料,我們主要從上面這些網站上獲取;但如要獲取國內股票資料,下面有一個很方便的介面,且是用python寫的,所以使用起來很方便:
下面我使用tushare來獲取國內滬深3000多支股票歷史資料,並存入本地資料庫(使用sqlite3):
程式碼如下:
import time
import tushare as ts
import sqlite3
import threading
import grouppopulation as group
import threadlocker
cont = sqlite3.connect("mydb.db")
sqlstr1 = 'delete from ' + STOCKHISTDATA
cont.execute(sqlstr1)
cont.commit()
def getStockHistData(column, table, threadnum):
eng = sqlite3.connect("mydb.db")
print('thread ' + threadnum + ' start at: ' + time.asctime(time.localtime(time.time())))
sqlstr = 'drop table if exists ' + table
#print('jhm: ' + sqlstr)
eng.execute(sqlstr)
for name in column:
dfd = ts.get_hist_data(name)
dfd['code'] = name
#time.sleep(0.1)
#locker.incr();
s1.acquire()
dfd.to_sql(table, con=eng,if_exists='append')
eng.commit()
#locker.decr();
s1.release()
eng.execute(mergesql % table)
eng.commit()
eng.execute(sqlstr)
print('thread ' + threadnum + 'ends at: ' + time.asctime( time.localtime(time.time()) ))
程式碼使用多執行緒獲取3000多支股票歷史資料,在我本機上測試,共需5分鐘,存入sqlite3資料庫,以備後續資料分析處理。
歡迎批評指正。