【手把手教你】Python獲取數(shù)據(jù)

抓住自己最有興趣的東西,由淺入深,循序漸進(jìn)地學(xué)。

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ——華羅庚

引 言

數(shù)據(jù)獲取是金融量化分析的第一步,找不到可靠、真實(shí)的數(shù)據(jù),量化分析就無從談起。隨著信息技術(shù)的不斷發(fā)展,數(shù)據(jù)獲取渠道也越來越多,尤其是Python網(wǎng)絡(luò)爬蟲,近幾年愈來愈火,網(wǎng)絡(luò)培訓(xùn)視頻和教程滿天飛。然而,很多人畢竟精力有限,沒有時(shí)間專門去學(xué)習(xí)網(wǎng)絡(luò)爬蟲技術(shù)。當(dāng)然,不會(huì)網(wǎng)絡(luò)爬蟲不要緊,我們還可以借助Python的開源數(shù)據(jù)包(其本質(zhì)也是網(wǎng)絡(luò)爬蟲),如:tushare、baostock、pandas_datareader和yahool等財(cái)經(jīng)數(shù)據(jù)API,這樣可以節(jié)省不少精力。本文將以股票行情數(shù)據(jù)為例,逐一、簡要介紹如何使用這幾個(gè)開源庫獲取數(shù)據(jù)并進(jìn)行可視化。在介紹使用Python的API獲取數(shù)據(jù)之前,本文首先給出了根據(jù)股票漲跌驅(qū)動(dòng)因素,廣泛獲取求證信息來源,如下面圖1、2、3所示,很多網(wǎng)站提供了非結(jié)構(gòu)化的數(shù)據(jù)(信息),如股票論壇,信息含量非常大,后期考慮使用網(wǎng)絡(luò)爬蟲爬取股票論壇評(píng)論數(shù)據(jù),建立輿情指標(biāo),探討群體性交易情緒與股價(jià)走勢(shì)的關(guān)系。本篇屬于Python金融量化入門學(xué)習(xí)的分享之一,希望能起到拋磚引玉的作用。

圖1 股票漲跌驅(qū)動(dòng)因素

圖2 公司基本面信息源

圖3 知名股票論壇

01 Tushare 社區(qū)

公眾號(hào)上不少文章使用了tushare庫獲取財(cái)經(jīng)和股票交易數(shù)據(jù),當(dāng)時(shí)用的是舊版本(tushare)。Tushare社區(qū)目前主要維護(hù)新版本:tushare pro,數(shù)據(jù)更穩(wěn)定質(zhì)量更高,可獲取滬深股票行情、財(cái)務(wù)、市場(chǎng)參考等數(shù)據(jù),以及指數(shù)(含國外股指)、基金、期貨、期權(quán)、宏觀經(jīng)濟(jì)、行業(yè)經(jīng)濟(jì)等財(cái)經(jīng)數(shù)據(jù),為金融量化愛好者節(jié)省了大量寶貴時(shí)間。此外,近期還增加了新聞聯(lián)播的文本數(shù)據(jù),為文本分析和數(shù)據(jù)挖掘提供了很好的素材。不過,新版本需要注冊(cè)獲取token才能免費(fèi)使用,注冊(cè)網(wǎng)址: https://tushare.pro/register?reg=218422 。安裝(進(jìn)入cmd模式):pip install tushare,或升級(jí):pip install tushare --upgrade。下面以股票行情數(shù)據(jù)為例,展示下tushare如何獲取數(shù)據(jù)。股票行情數(shù)據(jù)以股票行情數(shù)據(jù)為例,簡要介紹如何獲取數(shù)據(jù)。

#先引入后面分析、可視化等可能用到的庫

importtushareasts

importpandasaspd

importmatplotlib.pyplotasplt

#正常顯示畫圖時(shí)出現(xiàn)的中文和負(fù)號(hào)

frompylabimportmpl

mpl.rcParams['font.sans-serif']=['SimHei']

mpl.rcParams['axes.unicode_minus']=False

#設(shè)置token

token='你的token'

#ts.set_token(token)

pro?=?ts.pro_api(token)

個(gè)股行情數(shù)據(jù):

pro.stock_basic()

參數(shù):is_hs:是否滬深港通標(biāo)的,N否、H滬股通、S深股通;list_status:上市狀態(tài),L上市、D退市、P暫停上市;exchange:交易所 SSE上交所,SZSE深交所,HKEX港交所。?

pro.daily(ts_code= 或 trade_date=)

日行情:daily;周行情:weekly;月行情:monthly

#獲取當(dāng)前上市的股票代碼、簡稱、注冊(cè)地、行業(yè)、上市時(shí)間等數(shù)據(jù)

basic=pro.stock_basic(list_status='L')

#查看前五行數(shù)據(jù)

#basic.head(5)

#獲取平安銀行日行情數(shù)據(jù)

pa=pro.daily(ts_code='000001.SZ',?start_date='20180101',

end_date='20190106')

#pa.head()

#K線圖可視化

frompyechartsimportKline

pa.index=pd.to_datetime(pa.trade_date)

pa=pa.sort_index()

v1=list(pa.loc[:,['open','close','low','high']].values)

t=pa.index

v0=list(t.strftime('%Y%m%d'))

kline?=?Kline("平安銀行K線圖",title_text_size=15)

kline.add("",?v0,?v1,is_datazoom_show=True,

mark_line=["average"],

mark_point=["max","min"],

mark_point_symbolsize=60,

mark_line_valuedim=['highest','lowest']?)

#kline.render("上證指數(shù)圖.html")

kline

#定義獲取多只股票函數(shù):

defget_stocks_data(stocklist,start,end):

all_data={}

forcodeinstocklist:

all_data[code]=pro.daily(ts_code=code,

start_date=start,?end_date=end)

returnall_data

#保存本地

defsave_data(all_data):

forcode,datainall_data.items():

data.to_csv('c:/zjy/stock_data/'+code+'.csv',

header=True,?index=False)

stocklist=list(basic.ts_code)[:15]

start=''

end=''

all_data=get_stocks_data(stocklist,start,end)

all_data['000002.SZ'].tail()

#將數(shù)據(jù)保存到本地

save_data(all_data)

#讀取本地文件夾里所有文件

importos

#文件存儲(chǔ)路徑

file='c:/zjy/stock_data/'

g=os.walk(file)

filenames=[]

forpath,d,filelisting:

forfilenameinfilelist:

filenames.append(os.path.join(filename))

print(filenames)

#將讀取的數(shù)據(jù)文件放入一個(gè)字典中

df={}

#從文件名中分離出股票代碼

code=[name.split('.')[0]fornameinfilenames]

foriinrange(len(filenames)):

filename=file+filenames[i]

df[code[i]]=pd.read_csv(filename)

#查看第一只股票前五行數(shù)據(jù)

#df[code[0]].head()

指數(shù)數(shù)據(jù):pro.index_daily(ts_code=)

defget_index_data(indexs):

'''indexs是字典格式'''

index_data={}

forname,codeinindexs.items():

df=pro.index_daily(ts_code=code)

df.index=pd.to_datetime(df.trade_date)

index_data[name]=df.sort_index()

returnindex_data

#獲取常見股票指數(shù)行情

indexs={'上證綜指':'000001.SH','深證成指':'399001.SZ',

'滬深300':'000300.SH','創(chuàng)業(yè)板指':'399006.SZ',

'上證50':'000016.SH','中證500':'000905.SH',

'中小板指':'399005.SZ','上證180':'000010.SH'}

index_data=get_index_data(indexs)

#index_data['上證綜指'].head()

#對(duì)股價(jià)走勢(shì)進(jìn)行可視化分析

subjects?=list(index_data.keys())

#每個(gè)子圖的title

plot_pos?=?[421,422,423,424,425,426,427,428]#?每個(gè)子圖的位置

new_colors?=?['#1f77b4','#ff7f0e','#2ca02c','#d62728',

'#9467bd','#8c564b','#e377c2',

'#7f7f7f','#bcbd22','#17becf']

fig?=?plt.figure(figsize=(16,18))

fig.suptitle('A股股指走勢(shì)',fontsize=18)

forposinnp.arange(len(plot_pos)):

ax?=?fig.add_subplot(plot_pos[pos])

y_data?=index_data[subjects[pos]]['close']

b?=?ax.plot(y_data,color=new_colors[pos])

ax.set_title(subjects[pos])

#?將右上邊的兩條邊顏色設(shè)置為空,相當(dāng)于抹掉這兩條邊

ax?=?plt.gca()

ax.spines['right'].set_color('none')

ax.spines['top'].set_color('none')

plt.show()

02 Baostock 證券寶

baostock也是免費(fèi)、開源的證券數(shù)據(jù)平臺(tái)。提供了大量準(zhǔn)確、完整的證券歷史行情數(shù)據(jù)、上市公司財(cái)務(wù)數(shù)據(jù)等。 通過python API獲取證券數(shù)據(jù)信息,可以滿足量化交易投資者、數(shù)量金融愛好者、計(jì)量經(jīng)濟(jì)從業(yè)者數(shù)據(jù)需求。返回的數(shù)據(jù)格式: pandas DataFrame類型,以便于用pandas/NumPy/Matplotlib進(jìn)行數(shù)據(jù)分析和可視化。

證券寶鏈接地址:http://baostock.com/baostock/index.php/Python_API文檔 ?。安裝:進(jìn)入cmd模式,pip install baostock

importbaostockasbs

####?登陸系統(tǒng)?####

lg?=?bs.login()

####?獲取歷史K線數(shù)據(jù)?####

#?query_history_k_data()

fields="date,code,open,high,low,close"

rs?=?bs.query_history_k_data("sh.000001",?fields,

start_date='2000-01-01',?end_date='2018-09-07',

frequency="d",?adjustflag="2")

#frequency="d"取日k線,adjustflag="3"默認(rèn)不復(fù)權(quán),

#1:后復(fù)權(quán);2:前復(fù)權(quán)

data_list?=?[]

while(rs.error_code?=='0')?&?rs.next():

#?獲取一條記錄,將記錄合并在一起

data_list.append(rs.get_row_data())

result?=?pd.DataFrame(data_list,?columns=rs.fields)

result.index=pd.to_datetime(result.date)

####?結(jié)果集輸出到csv文件?####

#result.to_csv("c:/zjy/history_k_data.csv",?

#????????encoding="gbk",?index=False)

result.head()

####?登出系統(tǒng)?####

#bs.logout()

result.info()

#將某些object轉(zhuǎn)化numeric

result=result.apply(pd.to_numeric,?errors='ignore')

result.info()

result.close.plot(figsize=(16,8))

ax?=?plt.gca()

ax.spines['right'].set_color('none')

ax.spines['top'].set_color('none')

plt.show()

03 雅虎財(cái)經(jīng)API

原來的雅虎財(cái)經(jīng)Python開源庫2018年后已不在維護(hù),還好有大神推出了雅虎財(cái)經(jīng)的修復(fù)版本,使用pip install fix_yahoo_finance安裝。

importfix_yahoo_financeasfy

fy.pdr_override()

defget_data(tick,start_date="2000-01-01",?end_date="2019-01-07"):

data?=?fy.download(tick,?start=start_date,?end=end_date)

returndata

tickers=['AAPL','GOOG','AMZN','FB']

all_data?=?{}

fortickerintickers:

all_data[ticker]=get_data(ticker)

subjects?=?['蘋果公司股價(jià)走勢(shì)','谷歌公司股價(jià)走勢(shì)',

'亞馬遜公司股價(jià)走勢(shì)','FaceBook公司股價(jià)走勢(shì)']

#每個(gè)子圖的title

plot_pos?=?[221,222,223,224]#?每個(gè)子圖的位置

new_colors?=?['#1f77b4','#ff7f0e','#2ca02c','#d62728',

'#9467bd','#8c564b','#e377c2',

'#7f7f7f','#bcbd22','#17becf']

fig?=?plt.figure(figsize=(16,9))

fig.suptitle('美股&指數(shù)走勢(shì)',fontsize=18)

forposinnp.arange(len(plot_pos)):

ax?=?fig.add_subplot(plot_pos[pos])

y_data?=?all_data[tickers[pos]]['Adj?Close']

b?=?ax.plot(y_data,color=new_colors[pos])

ax.set_title(subjects[pos])

ax?=?plt.gca()

ax.spines['right'].set_color('none')

ax.spines['top'].set_color('none')

plt.show()???

WorldStockIndexList?=?{

'000001.SS':'中國上證指數(shù)',

'^DJI':'道瓊斯工業(yè)平均指數(shù)',

'^IXIC':'納斯達(dá)克綜合指數(shù)',

'^N225':'日本日經(jīng)225指數(shù)',

'^HSI':'香港恒生指數(shù)',

'^FCHI':'法國CAC40指數(shù)',

'^FTSE':'英國富時(shí)100指數(shù)',

'^GDAXI':'德國法蘭克福DAX指數(shù)'}

world_data={}

fortickerinWorldStockIndexList.keys():

world_data[ticker]=get_data(ticker)

subjects?=list(WorldStockIndexList.values())

tickers=list(WorldStockIndexList)

#每個(gè)子圖的title

plot_pos?=?[421,422,423,424,425,426,427,428]

#?每個(gè)子圖的位置

new_colors?=?['#1f77b4','#ff7f0e','#2ca02c','#d62728',

'#9467bd','#8c564b','#e377c2',

'#7f7f7f','#bcbd22','#17becf']

fig?=?plt.figure(figsize=(16,18))

fig.suptitle('全球股指走勢(shì)',fontsize=18)

forposinnp.arange(len(plot_pos)):

ax?=?fig.add_subplot(plot_pos[pos])

y_data?=world_data[tickers[pos]]['Adj?Close']

b?=?ax.plot(y_data,color=new_colors[pos])

ax.set_title(subjects[pos])

ax?=?plt.gca()

ax.spines['right'].set_color('none')

ax.spines['top'].set_color('none')

plt.show()

關(guān)于Python金融量化

專注于分享Python在金融領(lǐng)域的實(shí)際應(yīng)用,包括金融數(shù)據(jù)分析與挖掘(含文本分析)、金融建模與量化投資等。公眾號(hào)本身具有AI自動(dòng)回復(fù)功能,具有查詢天氣、星座運(yùn)勢(shì)、專業(yè)名詞、中英翻譯、講笑話、小故事等功能,關(guān)于公眾號(hào)文章源碼及其他資料,可回復(fù)“指南”查看詳情。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • # -*- coding: utf-8 -*- from __future__ import division f...
    小豆角lch閱讀 1,534評(píng)論 0 1
  • 一、概述 深度學(xué)習(xí)的一個(gè)重要手段是訓(xùn)練數(shù)據(jù)和訓(xùn)練過程的可視化,因此,我們關(guān)于深度學(xué)習(xí)的系列介紹文章就從Matplo...
    aoqingy閱讀 6,575評(píng)論 0 24
  • 前言 有時(shí)候?yàn)榱酥庇^,我們需要將數(shù)據(jù)可視化,Python編程中最為常用的一個(gè)庫是matplotlib。那么什么是m...
    開發(fā)者也閱讀 5,520評(píng)論 2 46
  • 這套書是小石榴一歲的時(shí)候就買了,怕他亂撕,一歲半這樣才拿出來看,每一頁都是一副風(fēng)景畫,內(nèi)容豐富,色彩斑斕,...
    小石榴ai媽媽閱讀 828評(píng)論 0 0
  • 認(rèn)識(shí)你 會(huì)假裝說嘿,在意什么 我們要珍惜的是現(xiàn)在 卻不知道我會(huì)一次次翻看你的過往 并不是嫉妒 只是有些深情你未曾給...
    念南卿閱讀 237評(píng)論 0 3

友情鏈接更多精彩內(nèi)容