Python股票歷史數據的獲取


獲取股票數據的接口很多,免費的接口有新浪、網易、雅虎的API接口,收費的就是證券公司及相應的公司提供的接口。
收費試用的接口一般提供的數據只是最近一年或三年的,限制比較多,除非money足夠多。
所以本文主要討論的是免費數據的獲取及處理。

國內提供股票數據的接口如sinajs,money.163.com,yahoo,它們提供的API接口不同,每家提供的數據大同小異,可以選擇一家的數據來處理。

目前,國內有一個開源的財經數據獲取包,封裝了上述的接口,不需關系數據源從哪去,它會優先從最快的源來取數據。使用起來非常方便。它是TuShare,具體的安裝使用見鏈接。

本文基於TuShare的數據獲取基礎上開發,介紹如何獲取A股所有股票的歷史K線數據。
一、獲取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'
股票列表中包括當前A股的2756只股票的基本信息,包括:
code,代碼
name,名稱
industry,所屬行業
area,地區
pe,市盈率
outstanding,流通股本
totals,總股本(萬)
totalAssets,總資產(萬)
liquidAssets,流動資產
fixedAssets,固定資產
reserved,公積金
reservedPerShare,每股公積金
eps,每股收益
bvps,每股凈資
pb,市凈率
timeToMarket,上市日期
二、獲取單只股票的歷史K線

獲取的日K線數據包括:

date : 交易日期 (index)
open : 開盤價(前復權,默認)
high : 最高價(前復權,默認)
close : 收盤價(前復權,默認)
low : 最低價(前復權,默認)
open_nfq : 開盤價(不復權)
high_nfq : 最高價(不復權)
close_nfq : 收盤價(不復權)
low_nfq : 最低價(不復權)
open_hfq : 開盤價(后復權)
high_hfq : 最高價(后復權)
close_hfq : 收盤價(后復權)
low_hfq : 最低價(后復權)
volume : 成交量
amount : 成交金額

下載股票代碼為code的股票歷史K線,默認為上市日期到今天的K線數據,支持遞增下載,如本地已下載股票60000的數據到2015-6-19,再次運行則會從6.20開始下載,追加到本地csv文件中。

# 默認為上市日期到今天的K線數據
# 可指定開始、結束日期:格式為"2015-06-28"
def download_stock_kline(code, date_start='', date_end=datetime.date.today()):

    code = util.getSixDigitalStockCode(code) # 將股票代碼格式化為6位數字

    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')  

       # 已經是最新的數據
       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) # 前復權
       df_nfq = ts.get_h_data(str(code), start=date_start, end=date_end) # 不復權
       df_hfq = ts.get_h_data(str(code), start=date_start, end=date_end) # 后復權

       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)

           # 按日期由遠及近
           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

           # 按日期由近及遠
           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  ##
#######################

# 獲取個股的基本信息:股票名稱,行業,地域,PE等,詳細如下
#    code,代碼
#    name,名稱
#    industry,所屬行業
#    area,地區
#    pe,市盈率
#    outstanding,流通股本
#    totals,總股本(萬)
#    totalAssets,總資產(萬)
#    liquidAssets,流動資產
#    fixedAssets,固定資產
#    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來自函數語言Lisp,map函數能夠按序映射出另一個函數。

urls = ['http://www.yahoo.com', 'http://www.reddit.com']
results = map(urllib2.urlopen, urls)

有兩個能夠支持通過map函數來完成並行的庫:一個是multiprocessing,另一個是鮮為人知但功能強大的子文件:multiprocessing.dummy。
Dummy就是多進程模塊的克隆文件。唯一不同的是,多進程模塊使用的是進程,而dummy則使用線程(當然,它有所有Python常見的限制)。

通過指定processes的個數來調用多線程。

附:文中用到的其他函數及變量,定義如下:
TABLE_STOCKS_BASIC = 'stock_basic_list'
DownloadDir = os.path.pardir '/stockdata/' # os.path.pardir: 上級目錄

# 補全股票代碼(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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM