如何用Python中Tushare包輕松完成股票篩選(詳細(xì)流程操作)
本文包括安裝以及調(diào)用Tushare包的詳細(xì)流程操作
一、Tushare簡(jiǎn)介Tushare是Python中一個(gè)十分好用的免費(fèi)調(diào)用股票數(shù)據(jù)的接口包。運(yùn)用tushare可以很輕松的調(diào)取各種股票數(shù)據(jù)。
網(wǎng)址:https://tushare.pro/register?reg=427001
可以調(diào)取的數(shù)據(jù)包括但不僅限于:
Windows系統(tǒng)直接在terminal輸入以下代碼
pip install tushare
Mac在terminal輸入
pip3 install tushare
需要注意的是,從tushare上獲取的數(shù)據(jù)類型為Dataframe,所以為了調(diào)用和存儲(chǔ)數(shù)據(jù)同樣需要安裝pandas包,安裝方法同上。
三、調(diào)用tushare為了使用tushare包抓取數(shù)據(jù),我們同時(shí)需要調(diào)用tushare和pandas包。
import tushare as tsfrom pandas import Dataframe
接著我們便需要在tushare官網(wǎng)上進(jìn)行注冊(cè),然后在個(gè)人主頁獲取相當(dāng)于自己的鑰匙的token網(wǎng)址:https://tushare.pro/register?reg=427001
拿到token之后,我們便可以在python中調(diào)用tushare包,格式如下:
ts.set_token(’你的token’)pro = ts.pro_api()stock_info = pro.stock_basic()#股票基本信息
之后在根據(jù)官網(wǎng)上給出的數(shù)據(jù)接口調(diào)用不同種類的數(shù)據(jù)。
需要注意的是,由于tushare采取的是積分制,所以有一些數(shù)據(jù)接口需要積累一定的積分才能調(diào)用,詳細(xì)信息見官網(wǎng)上的說明。
四、代碼分享此處分享一下我編寫的抓取所有股票一段時(shí)間內(nèi)股東人數(shù)變化并將變化量并進(jìn)行排序的代碼:
from pandas import DataFrameimport tushare as tsimport timets.set_token(’be3dddcd0ebf47cb8586afe0428666a1547ae0fc999682d245e8ee1c’)pro = ts.pro_api()stock_info = pro.stock_basic()#獲取所有股票的基本信息#print(len(stock_info))startdate: str = input(’請(qǐng)輸入起始時(shí)間,格式為20210304n’)enddate: str = input(’請(qǐng)輸入結(jié)束時(shí)間n’)code: str = input(’請(qǐng)輸入查詢股票的代碼,輸入0則查詢所有股票n’)variation = {}if code != ’0’: stockholder_num = pro.stk_holdernumber(ts_code=code,start_date=startdate,end_date=enddate) #print(stockholder_num) df=DataFrame(stockholder_num) df.to_excel(’stockholder_num.xlsx’)else: for i in range(0,len(stock_info)):#遍歷所有股票 if i>0 and i % 100 == 0: time.sleep(60)#由于每分鐘調(diào)用限制,每調(diào)用100次等60s code = stock_info.at[i,’ts_code’] #print(code) stockholder_num = pro.stk_holdernumber(ts_code=code,start_date=startdate,end_date=enddate) #print(stockholder_num) try:#由于一段時(shí)間內(nèi)不一定每只股票都公告了股東人數(shù),所以有可能會(huì)報(bào)錯(cuò) later = stockholder_num.at[0,’holder_num’] former = stockholder_num.at[len(stockholder_num)-1,’holder_num’] change = later - former except:#如果沒有公告股東人數(shù)則跳過這一支股票進(jìn)入下一支 continue #print(change) variation[stock_info.at[i,’ts_code’]] = change#將股東人數(shù)變化量存入字典 #print(i) rank = sorted(variation.items(), key = lambda kv:(kv[1], kv[0]), reverse=True)#給字典排序 print(rank) df=DataFrame(rank) df.to_excel(’stockholder_num.xlsx’)#將數(shù)據(jù)存入Excel表中
到此這篇關(guān)于如何用Python中Tushare包輕松完成股票篩選(詳細(xì)流程操作)的文章就介紹到這了,更多相關(guān)Python Tushare股票篩選內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. ajax post下載flask文件流以及中文文件名問題2. 如何通過vscode運(yùn)行調(diào)試javascript代碼3. 利用CSS3新特性創(chuàng)建透明邊框三角4. python 使用raw socket進(jìn)行TCP SYN掃描實(shí)例5. python dict如何定義6. IntelliJ IDEA導(dǎo)入jar包的方法7. 使用css實(shí)現(xiàn)全兼容tooltip提示框8. 使用Docker的NFS-Ganesha鏡像搭建nfs服務(wù)器的詳細(xì)過程9. WML語言的基本情況10. JSP+Servlet實(shí)現(xiàn)文件上傳到服務(wù)器功能
