
Python股票歷史數(shù)據(jù)的獲取
獲取股票數(shù)據(jù)的接口很多,免費(fèi)的接口有新浪、網(wǎng)易、雅虎的API接口,收費(fèi)的就是證券公司及相應(yīng)的公司提供的接口。
收費(fèi)試用的接口一般提供的數(shù)據(jù)只是最近一年或三年的,限制比較多,除非money足夠多。
所以本文主要討論的是免費(fèi)數(shù)據(jù)的獲取及處理。
國內(nèi)提供股票數(shù)據(jù)的接口如sinajs,money.163.com,yahoo,它們提供的API接口不同,每家提供的數(shù)據(jù)大同小異,可以選擇一家的數(shù)據(jù)來處理。
目前,國內(nèi)有一個(gè)開源的財(cái)經(jīng)數(shù)據(jù)獲取包,封裝了上述的接口,不需關(guān)系數(shù)據(jù)源從哪去,它會(huì)優(yōu)先從最快的源來取數(shù)據(jù)。使用起來非常方便。它是TuShare,具體的安裝使用見鏈接。
本文基于TuShare的數(shù)據(jù)獲取基礎(chǔ)上開發(fā),介紹如何獲取A股所有股票的歷史K線數(shù)據(jù)。
一、獲取A股上市公司列表
import tushare as ts
import pandas as pd
def download_stock_basic_info():
try:
df = ts.get_stock_basics()
#直接保存到csv
print 'choose csv'
df.to_csv('stock_basic_list.csv');
print 'download csv finish'
股票列表中包括當(dāng)前A股的2756只股票的基本信息,包括:
code,代碼
name,名稱
industry,所屬行業(yè)
area,地區(qū)
pe,市盈率
outstanding,流通股本
totals,總股本(萬)
totalAssets,總資產(chǎn)(萬)
liquidAssets,流動(dòng)資產(chǎn)
fixedAssets,固定資產(chǎn)
reserved,公積金
reservedPerShare,每股公積金
eps,每股收益
bvps,每股凈資
pb,市凈率
timeToMarket,上市日期
二、獲取單只股票的歷史K線
獲取的日K線數(shù)據(jù)包括:
date : 交易日期 (index)
open : 開盤價(jià)(前復(fù)權(quán),默認(rèn))
high : 最高價(jià)(前復(fù)權(quán),默認(rèn))
close : 收盤價(jià)(前復(fù)權(quán),默認(rèn))
low : 最低價(jià)(前復(fù)權(quán),默認(rèn))
open_nfq : 開盤價(jià)(不復(fù)權(quán))
high_nfq : 最高價(jià)(不復(fù)權(quán))
close_nfq : 收盤價(jià)(不復(fù)權(quán))
low_nfq : 最低價(jià)(不復(fù)權(quán))
open_hfq : 開盤價(jià)(后復(fù)權(quán))
high_hfq : 最高價(jià)(后復(fù)權(quán))
close_hfq : 收盤價(jià)(后復(fù)權(quán))
low_hfq : 最低價(jià)(后復(fù)權(quán))
volume : 成交量
amount : 成交金額
下載股票代碼為code的股票歷史K線,默認(rèn)為上市日期到今天的K線數(shù)據(jù),支持遞增下載,如本地已下載股票60000的數(shù)據(jù)到2015-6-19,再次運(yùn)行則會(huì)從6.20開始下載,追加到本地csv文件中。
# 默認(rèn)為上市日期到今天的K線數(shù)據(jù)
# 可指定開始、結(jié)束日期:格式為"2015-06-28"
def download_stock_kline(code, date_start='', date_end=datetime.date.today()):
code = util.getSixDigitalStockCode(code) # 將股票代碼格式化為6位數(shù)字
try:
fileName = 'h_kline_' + str(code) + '.csv'
writeMode = 'w'
if os.path.exists(cm.DownloadDir+fileName):
#print (">>exist:" + code)
df = pd.DataFrame.from_csv(path=cm.DownloadDir+fileName)
se = df.head(1).index #取已有文件的最近日期
dateNew = se[0] + datetime.timedelta(1)
date_start = dateNew.strftime("%Y-%m-%d")
#print date_start
writeMode = 'a'
if date_start == '':
se = get_stock_info(code)
date_start = se['timeToMarket']
date = datetime.datetime.strptime(str(date_start), "%Y%m%d")
date_start = date.strftime('%Y-%m-%d')
date_end = date_end.strftime('%Y-%m-%d')
# 已經(jīng)是最新的數(shù)據(jù)
if date_start >= date_end:
df = pd.read_csv(cm.DownloadDir+fileName)
return df
print 'download ' + str(code) + ' k-line >>>begin (', date_start+u' 到 '+date_end+')'
df_qfq = ts.get_h_data(str(code), start=date_start, end=date_end) # 前復(fù)權(quán)
df_nfq = ts.get_h_data(str(code), start=date_start, end=date_end) # 不復(fù)權(quán)
df_hfq = ts.get_h_data(str(code), start=date_start, end=date_end) # 后復(fù)權(quán)
if df_qfq is None or df_nfq is None or df_hfq is None:
return None
df_qfq['open_no_fq'] = df_nfq['open']
df_qfq['high_no_fq'] = df_nfq['high']
df_qfq['close_no_fq'] = df_nfq['close']
df_qfq['low_no_fq'] = df_nfq['low']
df_qfq['open_hfq']=df_hfq['open']
df_qfq['high_hfq']=df_hfq['high']
df_qfq['close_hfq']=df_hfq['close']
df_qfq['low_hfq']=df_hfq['low']
if writeMode == 'w':
df_qfq.to_csv(cm.DownloadDir+fileName)
else:
df_old = pd.DataFrame.from_csv(cm.DownloadDir + fileName)
# 按日期由遠(yuǎn)及近
df_old = df_old.reindex(df_old.index[::-1])
df_qfq = df_qfq.reindex(df_qfq.index[::-1])
df_new = df_old.append(df_qfq)
#print df_new
# 按日期由近及遠(yuǎn)
df_new = df_new.reindex(df_new.index[::-1])
df_new.to_csv(cm.DownloadDir+fileName)
#df_qfq = df_new
print '\ndownload ' + str(code) + ' k-line finish'
return pd.read_csv(cm.DownloadDir+fileName)
except Exception as e:
print str(e)
return None
## private methods ##
#######################
# 獲取個(gè)股的基本信息:股票名稱,行業(yè),地域,PE等,詳細(xì)如下
# code,代碼
# name,名稱
# industry,所屬行業(yè)
# area,地區(qū)
# pe,市盈率
# outstanding,流通股本
# totals,總股本(萬)
# totalAssets,總資產(chǎn)(萬)
# liquidAssets,流動(dòng)資產(chǎn)
# fixedAssets,固定資產(chǎn)
# reserved,公積金
# reservedPerShare,每股公積金
# eps,每股收益
# bvps,每股凈資
# pb,市凈率
# timeToMarket,上市日期
# 返回值類型:Series
def get_stock_info(code):
try:
sql = "select * from %s where code='%s'" % (STOCK_BASIC_TABLE, code)
df = pd.read_sql_query(sql, engine)
se = df.ix[0]
except Exception as e:
print str(e)
return se
三、獲取所有股票的歷史K線
# 獲取所有股票的歷史K線
def download_all_stock_history_k_line():
print 'download all stock k-line'
try:
df = pd.DataFrame.from_csv(cm.DownloadDir + cm.TABLE_STOCKS_BASIC + '.csv')
pool = ThreadPool(processes=10)
pool.map(download_stock_kline, df.index)
pool.close()
pool.join()
except Exception as e:
print str(e)
print 'download all stock k-line'
Map來自函數(shù)語言Lisp,map函數(shù)能夠按序映射出另一個(gè)函數(shù)。
urls = ['http://www.yahoo.com', 'http://www.reddit.com']
results = map(urllib2.urlopen, urls)
有兩個(gè)能夠支持通過map函數(shù)來完成并行的庫:一個(gè)是multiprocessing,另一個(gè)是鮮為人知但功能強(qiáng)大的子文件:multiprocessing.dummy。
Dummy就是多進(jìn)程模塊的克隆文件。唯一不同的是,多進(jìn)程模塊使用的是進(jìn)程,而dummy則使用線程(當(dāng)然,它有所有Python常見的限制)。
通過指定processes的個(gè)數(shù)來調(diào)用多線程。
附:文中用到的其他函數(shù)及變量,定義如下:
TABLE_STOCKS_BASIC = 'stock_basic_list'
DownloadDir = os.path.pardir + '/stockdata/' # os.path.pardir: 上級(jí)目錄
# 補(bǔ)全股票代碼(6位股票代碼)
# input: int or string
# output: string
def getSixDigitalStockCode(code):
strZero = ''
for i in range(len(str(code)), 6):
strZero += '0'
return strZero + str(code)
數(shù)據(jù)分析咨詢請(qǐng)掃描二維碼
若不方便掃碼,搜微信號(hào):CDAshujufenxi
LSTM 模型輸入長(zhǎng)度選擇技巧:提升序列建模效能的關(guān)鍵? 在循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)家族中,長(zhǎng)短期記憶網(wǎng)絡(luò)(LSTM)憑借其解決長(zhǎng)序列 ...
2025-07-11CDA 數(shù)據(jù)分析師報(bào)考條件詳解與準(zhǔn)備指南? ? 在數(shù)據(jù)驅(qū)動(dòng)決策的時(shí)代浪潮下,CDA 數(shù)據(jù)分析師認(rèn)證愈發(fā)受到矚目,成為眾多有志投身數(shù) ...
2025-07-11數(shù)據(jù)透視表中兩列相乘合計(jì)的實(shí)用指南? 在數(shù)據(jù)分析的日常工作中,數(shù)據(jù)透視表憑借其強(qiáng)大的數(shù)據(jù)匯總和分析功能,成為了 Excel 用戶 ...
2025-07-11尊敬的考生: 您好! 我們誠摯通知您,CDA Level I和 Level II考試大綱將于 2025年7月25日 實(shí)施重大更新。 此次更新旨在確保認(rèn) ...
2025-07-10BI 大數(shù)據(jù)分析師:連接數(shù)據(jù)與業(yè)務(wù)的價(jià)值轉(zhuǎn)化者? ? 在大數(shù)據(jù)與商業(yè)智能(Business Intelligence,簡(jiǎn)稱 BI)深度融合的時(shí)代,BI ...
2025-07-10SQL 在預(yù)測(cè)分析中的應(yīng)用:從數(shù)據(jù)查詢到趨勢(shì)預(yù)判? ? 在數(shù)據(jù)驅(qū)動(dòng)決策的時(shí)代,預(yù)測(cè)分析作為挖掘數(shù)據(jù)潛在價(jià)值的核心手段,正被廣泛 ...
2025-07-10數(shù)據(jù)查詢結(jié)束后:分析師的收尾工作與價(jià)值深化? ? 在數(shù)據(jù)分析的全流程中,“query end”(查詢結(jié)束)并非工作的終點(diǎn),而是將數(shù) ...
2025-07-10CDA 數(shù)據(jù)分析師考試:從報(bào)考到取證的全攻略? 在數(shù)字經(jīng)濟(jì)蓬勃發(fā)展的今天,數(shù)據(jù)分析師已成為各行業(yè)爭(zhēng)搶的核心人才,而 CDA(Certi ...
2025-07-09【CDA干貨】單樣本趨勢(shì)性檢驗(yàn):捕捉數(shù)據(jù)背后的時(shí)間軌跡? 在數(shù)據(jù)分析的版圖中,單樣本趨勢(shì)性檢驗(yàn)如同一位耐心的偵探,專注于從單 ...
2025-07-09year_month數(shù)據(jù)類型:時(shí)間維度的精準(zhǔn)切片? ? 在數(shù)據(jù)的世界里,時(shí)間是最不可或缺的維度之一,而year_month數(shù)據(jù)類型就像一把精準(zhǔn) ...
2025-07-09CDA 備考干貨:Python 在數(shù)據(jù)分析中的核心應(yīng)用與實(shí)戰(zhàn)技巧? ? 在 CDA 數(shù)據(jù)分析師認(rèn)證考試中,Python 作為數(shù)據(jù)處理與分析的核心 ...
2025-07-08SPSS 中的 Mann-Kendall 檢驗(yàn):數(shù)據(jù)趨勢(shì)與突變分析的有力工具? ? ? 在數(shù)據(jù)分析的廣袤領(lǐng)域中,準(zhǔn)確捕捉數(shù)據(jù)的趨勢(shì)變化以及識(shí)別 ...
2025-07-08備戰(zhàn) CDA 數(shù)據(jù)分析師考試:需要多久?如何規(guī)劃? CDA(Certified Data Analyst)數(shù)據(jù)分析師認(rèn)證作為國內(nèi)權(quán)威的數(shù)據(jù)分析能力認(rèn)證 ...
2025-07-08LSTM 輸出不確定的成因、影響與應(yīng)對(duì)策略? 長(zhǎng)短期記憶網(wǎng)絡(luò)(LSTM)作為循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)的一種變體,憑借獨(dú)特的門控機(jī)制,在 ...
2025-07-07統(tǒng)計(jì)學(xué)方法在市場(chǎng)調(diào)研數(shù)據(jù)中的深度應(yīng)用? 市場(chǎng)調(diào)研是企業(yè)洞察市場(chǎng)動(dòng)態(tài)、了解消費(fèi)者需求的重要途徑,而統(tǒng)計(jì)學(xué)方法則是市場(chǎng)調(diào)研數(shù) ...
2025-07-07CDA數(shù)據(jù)分析師證書考試全攻略? 在數(shù)字化浪潮席卷全球的當(dāng)下,數(shù)據(jù)已成為企業(yè)決策、行業(yè)發(fā)展的核心驅(qū)動(dòng)力,數(shù)據(jù)分析師也因此成為 ...
2025-07-07剖析 CDA 數(shù)據(jù)分析師考試題型:解鎖高效備考與答題策略? CDA(Certified Data Analyst)數(shù)據(jù)分析師考試作為衡量數(shù)據(jù)專業(yè)能力的 ...
2025-07-04SQL Server 字符串截取轉(zhuǎn)日期:解鎖數(shù)據(jù)處理的關(guān)鍵技能? 在數(shù)據(jù)處理與分析工作中,數(shù)據(jù)格式的規(guī)范性是保證后續(xù)分析準(zhǔn)確性的基礎(chǔ) ...
2025-07-04CDA 數(shù)據(jù)分析師視角:從數(shù)據(jù)迷霧中探尋商業(yè)真相? 在數(shù)字化浪潮席卷全球的今天,數(shù)據(jù)已成為企業(yè)決策的核心驅(qū)動(dòng)力,CDA(Certifie ...
2025-07-04CDA 數(shù)據(jù)分析師:開啟數(shù)據(jù)職業(yè)發(fā)展新征程? ? 在數(shù)據(jù)成為核心生產(chǎn)要素的今天,數(shù)據(jù)分析師的職業(yè)價(jià)值愈發(fā)凸顯。CDA(Certified D ...
2025-07-03