99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀Python股票歷史數(shù)據(jù)的獲取
Python股票歷史數(shù)據(jù)的獲取
2018-02-20
收藏

Python股票歷史數(shù)據(jù)的獲取

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

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

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

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

獲取的日K線數(shù)據(jù)包括:

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線數(shù)據(jù),支持遞增下載,如本地已下載股票60000的數(shù)據(jù)到2015-6-19,再次運行則會從6.20開始下載,追加到本地csv文件中。

# 默認為上市日期到今天的K線數(shù)據(jù)
# 可指定開始、結束日期:格式為"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) # 前復權
        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  ##
#######################

# 獲取個股的基本信息:股票名稱,行業(yè),地域,PE等,詳細如下
#     code,代碼
#     name,名稱
#     industry,所屬行業(yè)
#     area,地區(qū)
#     pe,市盈率
#     outstanding,流通股本
#     totals,總股本(萬)
#     totalAssets,總資產(chǎn)(萬)
#     liquidAssets,流動資產(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ù)能夠按序映射出另一個函數(shù)。

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

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

通過指定processes的個數(shù)來調用多線程。

附:文中用到的其他函數(shù)及變量,定義如下:
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)

數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師考試動態(tài)
數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調,回調的第一個參數(shù)驗證碼對象,之后可以使用它調用相應的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }