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

熱線電話:13121318867

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

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

數(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(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個(gè)參數(shù)驗(yàn)證碼對(duì)象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個(gè)配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺(tái)檢測(cè)極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時(shí)表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請(qǐng)參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計(jì)時(shí)完成 $(".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 = '請(qǐng)輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請(qǐng)輸入正確的'+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); }