1. 程式人生 > >利用Python中的matplotlib模組抓取yahoo finance裡的歷史資料並繪圖

利用Python中的matplotlib模組抓取yahoo finance裡的歷史資料並繪圖

       如何自動獲取各個公司的股票歷史資料並繪圖是金融文字情感分析專案裡的必要部分,誠然這些資料在finance.yahoo.com裡可以很方便的看到,但如何利用程式自動獲取、實時顯示卻是個問題。之前一直考慮寫爬蟲來抓取資料,顯然這樣做很費力且效率不高,而Python.matplotlib  module有一finance module能夠很便捷的實現這一功能。 

       finance.py is a collection of modules for collecting , collecting ,analying and plotting financial data.讓我們先看一個example 關於利用matplotlib模組獲取finance.yahoo.com裡的歷史資料並繪圖,先貼程式碼

from pylab import figure, show
from matplotlib.finance import quotes_historical_yahoo
from matplotlib.dates import YearLocator, MonthLocator, DateFormatter
import datetime
date1 = datetime.date( 2012, 1, 1 )
date2 = datetime.date( 2012, 11, 11 )

daysFmt  = DateFormatter('%m-%d-%Y')

quotes = quotes_historical_yahoo('MSFT', date1, date2)
if len(quotes) == 0:
    raise SystemExit

dates = [q[0] for q in quotes]
opens = [q[1] for q in quotes]

fig = figure()
ax = fig.add_subplot(111)
ax.plot_date(dates, opens, '-')

# format the ticks
ax.xaxis.set_major_formatter(daysFmt)
ax.autoscale_view()

# format the coords message box
def price(x): return '$%1.2f'%x
ax.fmt_xdata = DateFormatter('%Y-%m-%d')
ax.fmt_ydata = price
ax.grid(True)

fig.autofmt_xdate()
show()

date1、date2分別是所要查詢資料的起止時間,比如這個例子就是要查詢微軟2012.1.1至2012.11.11之間的歷史股價。

quotes_historical_yahoo是一個獲取yahoo歷史資料的函式,需要輸入公司的Ticker Symbol和查詢起止日期,輸出為一緩衝檔案,具體程式碼如下:

def quotes_historical_yahoo(ticker, date1, date2, asobject=False,
                                        adjusted=True, cachename=None):
    """
    Get historical data for ticker between date1 and date2.  date1 and
    date2 are datetime instances or (year, month, day) sequences.

    See :func:`parse_yahoo_historical` for explanation of output formats
    and the *asobject* and *adjusted* kwargs.

    Ex:
    sp = f.quotes_historical_yahoo('^GSPC', d1, d2,
                                asobject=True, adjusted=True)
    returns = (sp.open[1:] - sp.open[:-1])/sp.open[1:]
    [n,bins,patches] = hist(returns, 100)
    mu = mean(returns)
    sigma = std(returns)
    x = normpdf(bins, mu, sigma)
    plot(bins, x, color='red', lw=2)

    cachename is the name of the local file cache.  If None, will
    default to the md5 hash or the url (which incorporates the ticker
    and date range)
    """
    # Maybe enable a warning later as part of a slow transition
    # to using None instead of False.
    #if asobject is False:
    #    warnings.warn("Recommend changing to asobject=None")

    fh = fetch_historical_yahoo(ticker, date1, date2, cachename)

    try:
        ret = parse_yahoo_historical(fh, asobject=asobject,
                                            adjusted=adjusted)
        if len(ret) == 0:
            return None
    except IOError as exc:
        warnings.warn('fh failure\n%s'%(exc.strerror[1]))
        return None

    return ret
def fetch_historical_yahoo(ticker, date1, date2, cachename=None,dividends=False):
    """
    Fetch historical data for ticker between date1 and date2.  date1 and
    date2 are date or datetime instances, or (year, month, day) sequences.

    Ex:
    fh = fetch_historical_yahoo('^GSPC', (2000, 1, 1), (2001, 12, 31))

    cachename is the name of the local file cache.  If None, will
    default to the md5 hash or the url (which incorporates the ticker
    and date range)
    
    set dividends=True to return dividends instead of price data.  With
    this option set, parse functions will not work

    a file handle is returned
    """

    ticker = ticker.upper()


    if iterable(date1):
        d1 = (date1[1]-1, date1[2], date1[0])
    else:
        d1 = (date1.month-1, date1.day, date1.year)
    if iterable(date2):
        d2 = (date2[1]-1, date2[2], date2[0])
    else:
        d2 = (date2.month-1, date2.day, date2.year)


    if dividends:
        g='v'
        verbose.report('Retrieving dividends instead of prices')
    else:
        g='d'

    urlFmt = 'http://table.finance.yahoo.com/table.csv?a=%d&b=%d&c=%d&d=%d&e=%d&f=%d&s=%s&y=0&g=%s&ignore=.csv'


    url =  urlFmt % (d1[0], d1[1], d1[2],
                     d2[0], d2[1], d2[2], ticker, g)


    if cachename is None:
        cachename = os.path.join(cachedir, md5(url).hexdigest())
    if os.path.exists(cachename):
        fh = open(cachename)
        verbose.report('Using cachefile %s for %s'%(cachename, ticker))
    else:
        mkdirs(cachedir)
        urlfh = urlopen(url)

        fh = open(cachename, 'wb')
        fh.write(urlfh.read())
        fh.close()
        verbose.report('Saved %s data to cache file %s'%(ticker, cachename))
        fh = open(cachename, 'r')

    return fh

parse_yahoo_historical函式可對歷史資料進行解析,讀取檔案,對檔案部分內容進行操作,程式碼如下:

def parse_yahoo_historical(fh, adjusted=True, asobject=False):
    """
    Parse the historical data in file handle fh from yahoo finance.

    *adjusted*
      If True (default) replace open, close, high, and low prices with
      their adjusted values. The adjustment is by a scale factor, S =
      adjusted_close/close. Adjusted prices are actual prices
      multiplied by S.

      Volume is not adjusted as it is already backward split adjusted
      by Yahoo. If you want to compute dollars traded, multiply volume
      by the adjusted close, regardless of whether you choose adjusted
      = True|False.


    *asobject*
      If False (default for compatibility with earlier versions)
      return a list of tuples containing

        d, open, close, high, low, volume

      If None (preferred alternative to False), return
      a 2-D ndarray corresponding to the list of tuples.

      Otherwise return a numpy recarray with

        date, year, month, day, d, open, close, high, low,
        volume, adjusted_close

      where d is a floating poing representation of date,
      as returned by date2num, and date is a python standard
      library datetime.date instance.

      The name of this kwarg is a historical artifact.  Formerly,
      True returned a cbook Bunch
      holding 1-D ndarrays.  The behavior of a numpy recarray is
      very similar to the Bunch.

    """

    lines = fh.readlines()

    results = []

    datefmt = '%Y-%m-%d'

    for line in lines[1:]:

        vals = line.split(',')
        if len(vals)!=7:
            continue      # add warning?
        datestr = vals[0]
        #dt = datetime.date(*time.strptime(datestr, datefmt)[:3])
        # Using strptime doubles the runtime. With the present
        # format, we don't need it.
        dt = datetime.date(*[int(val) for val in datestr.split('-')])
        dnum = date2num(dt)
        open, high, low, close =  [float(val) for val in vals[1:5]]
        volume = float(vals[5])
        aclose = float(vals[6])

        results.append((dt, dt.year, dt.month, dt.day,
                        dnum, open, close, high, low, volume, aclose))
    results.reverse()
    d = np.array(results, dtype=stock_dt)
    if adjusted:
        scale = d['aclose'] / d['close']
        scale[np.isinf(scale)] = np.nan
        d['open'] *= scale
        d['close'] *= scale
        d['high'] *= scale
        d['low'] *= scale

    if not asobject:
        # 2-D sequence; formerly list of tuples, now ndarray
        ret = np.zeros((len(d), 6), dtype=np.float)
        ret[:,0] = d['d']
        ret[:,1] = d['open']
        ret[:,2] = d['close']
        ret[:,3] = d['high']
        ret[:,4] = d['low']
        ret[:,5] = d['volume']
        if asobject is None:
            return ret
        return [tuple(row) for row in ret]

    return d.view(np.recarray)  # Close enough to former Bunch return

 另外,如果無需操作歷史資料,只需下載儲存到本地檔案可參考下面程式碼:

#this example can download the data in finance.yahoo and put in our computers

import os,urllib2,urllib

ticker = 'MSFT'           #the Ticker Symbol
date1 = ( 2012, 1, 1 )    #begining time
date2 = ( 2012, 11, 11 )  #ending time


d1 = (date1[1]-1, date1[2], date1[0])
    
d2 = (date2[1]-1, date2[2], date2[0])

g='d'

urlFmt = 'http://table.finance.yahoo.com/table.csv?a=%d&b=%d&c=%d&d=%d&e=%d&f=%d&s=%s&y=0&g=%s&ignore=.csv'
url =  urlFmt % (d1[0], d1[1], d1[2],
                     d2[0], d2[1], d2[2], ticker, g)  #the url of historical data
print url

path = r'C:\Users\yinyao\Desktop\Python code'  #Saving path
file_name = r'\ticker.csv'                #file name
dest_dir = os.path.join(path,file_name)   #located file
urllib.urlretrieve(url,dest_dir)        #download the data and put in located file

相關推薦

利用Pythonmatplotlib模組yahoo finance歷史資料繪圖

       如何自動獲取各個公司的股票歷史資料並繪圖是金融文字情感分析專案裡的必要部分,誠然這些資料在finance.yahoo.com裡可以很方便的看到,但如何利用程式自動獲取、實時顯示卻是個問題。之前一直考慮寫爬蟲來抓取資料,顯然這樣做很費力且效率不高,而Pytho

如何利用Python網絡爬蟲微信朋友圈的動態(上)

Python 網絡爬蟲 微信 朋友圈 Python開發 今天小編給大家分享一下如何利用Python網絡爬蟲抓取微信朋友圈的動態信息,實際上如果單獨的去爬取朋友圈的話,難度會非常大,因為微信沒有提供向網易雲音樂這樣的API接口,所以很容易找不到門。不過不要慌,小編在網上找到了第三方工具,它可

如何利用Python網絡爬蟲微信好友數量以及微信好友的男女比例

zha 成功 函數 通訊 好友列表 是否 ID 爬蟲 實現 前幾天給大家分享了利用Python網絡爬蟲抓取微信朋友圈的動態(上)和利用Python網絡爬蟲爬取微信朋友圈動態——附代碼(下),並且對抓取到的數據進行了Python詞雲和wordart可視化,感興趣的夥伴可以戳這

利用Python網絡爬蟲微信好友的所在省位和城市分布及其可視化

Python網絡爬蟲 微信好友 微信朋友圈 可視化 數據采集 前幾天給大家分享了如何利用Python網絡爬蟲抓取微信好友數量以及微信好友的男女比例,感興趣的小夥伴可以點擊鏈接進行查看。今天小編給大家介紹如何利用Python網絡爬蟲抓取微信好友的省位和城市,並且將其進行可視化,具體的教程如下

利用Python網絡爬蟲微信好友的簽名及其可視化展示

完成 mage 小白 lin 朋友圈 簽名 教程 技術分享 ctu 前幾天給大家分享了如何利用Python詞雲和wordart可視化工具對朋友圈數據進行可視化,利用Python網絡爬蟲抓取微信好友數量以及微信好友的男女比例,以及利用Python網絡爬蟲抓取微信好友的所在省位

PythonMatplotlib模組的簡單使用

目錄 Matplotlib pyplot類 pyplot.plot() 配置屬性 pyplot.subplot() Matplotlib Matplotlib 是 Python 2D 繪圖領域使用最廣泛的套件。它能讓使用者很輕鬆地將資料圖形化,並且提供多樣化的輸出格式

Python使用PhantomJSJavascript網頁資料

有些網頁不是靜態載入的,而是通過javascirpt函式動態載入網頁,比如下面這個網頁,表格中的看漲合約和看跌合約的資料都是通過javascirpt函式從後臺載入。僅僅使用beautifulsoup並不能抓到這個表格中的資料。 查詢資料,發現可以使用P

python自動規則化百度百科詞條資料

程式碼已同步到GitHub中,以後會陸陸續續整理之前的程式碼,放在GitHub共享,歡迎圍觀。 qingmm的GitHub 百科詞條資料整體較為規範,至少在網頁上看起來是這樣。但實際抓取時可以發現正文內容不論標題還是內容都在同一級下,無法直接獲取到某一

Python 利用urllib2簡單實現網頁

         網頁抓取就是把URL地址中指定的網路資源從網路流中讀取出來,儲存到本地。 在Python中,可以使用urllib2這個模組來抓取網頁,模組提供了讀取web頁面資料的介面,我們可以像讀

利用python爬蟲技術動態爬地理空間資料的元資料(selenium)

python爬取地理空間資料雲selenium動態點選 爬取的網址秀一下: 爬取的資訊是什麼呢? 這個資訊的爬取涉及到右邊按鈕的點選,這屬於動態爬取的範疇,需要用到selenium 好了,那麼開始寫程式碼吧 首先匯入selenium from seleni

利用python指令碼執行tcpdump包,支援傳參、併發多個包、檔案迴圈覆蓋

#!/usr/bin/env python # AUTH: [email protected] """ tcpdump -i any -s 0 -w /opt/log/tcpdump/2018-07-19--10-43-30.pcap tcp and

利用python的gzip模組壓縮和解壓資料流和檔案

直接給出原始碼實現, 分為兩種情況: 1.網路連線中的資料流的壓縮和解壓,或是開啟的檔案讀取一部分 2.開啟檔案壓縮或是解壓 #!/usr/bin/env python #encoding: utf-8 #filename: gzip_demo.py #author: [

Python常用模組re,matplotlib,pandas,sys,mysql

模組是一個包含所有你定義的函式和變數的檔案,其後綴名是.py windows python -m pip install -U pip setuptools python -m pip install matplotlib python -m pip i

Python實例之淘寶商品數據(json型數據)保存為TXT

sel range ats 表達 隨著 request nic rom .get 本實例實現了抓取淘寶網中以‘python’為關鍵字的搜索結果,經詳細查看數據存儲於html文檔中的js腳本中,數據類型為JSON 通過瀏覽器相關工具發現捧腹網笑話頁面的數據存儲在HTML頁面而

Python實例之網易雲課堂搜索數據(post方式json型數據)保存為TXT

網易雲 pytho sco 關鍵詞 page json ner urn 頁碼 本實例實現了抓取網易雲課堂中以‘java’為關鍵字的搜索結果,經詳細查看請求的方式為post,請求的結果為JSON數據 具體實現代碼如下: import requests import json

pythonmatplotlib的顏色及線條控制

hex 可選 技術 擴展 gen har hot deep for 參考網址: http://stackoverflow.com/questions/22408237/named-colors-in-matplotlib http://stackoverflow.com

Python爬蟲東方財富網股票數據實現MySQL數據庫存儲

alt 插入 pytho width 重新 tab 空值 utf word Python爬蟲可以說是好玩又好用了。現想利用Python爬取網頁股票數據保存到本地csv數據文件中,同時想把股票數據保存到MySQL數據庫中。需求有了,剩下的就是實現了。 在開始之前,保證已經

Macwireshark如何HTTPS流量?

菜單欄 cnblogs mas pro 跟蹤 ces dev prot protocol 概述 某些場景下,我們需要分析網站https流量,chrome提供的DevTools工具在頁面跳轉時無法查看之前的請求。 使用wireshark能夠全量抓取整個流程,本文主要是將網上查

pythonmatplotlib實現最小二乘法擬合的過程詳解

ast array plt atp ons 正則 key code 擬合 這篇文章主要給大家介紹了關於python中matplotlib實現最小二乘法擬合的相關資料,文中通過示例代碼詳細介紹了關於最小二乘法擬合直線和最小二乘法擬合曲線的實現過程,需要的朋友可以參考借鑒,下

如何利用Python網絡爬蟲爬微信朋友圈動態--附代碼(下)

CA external 令行 sta 項目 程序 str 輸入 tar 前天給大家分享了如何利用Python網絡爬蟲爬取微信朋友圈數據的上篇(理論篇),今天給大家分享一下代碼實現(實戰篇),接著上篇往下繼續深入。 一、代碼實現 1、修改Scrapy項目中的ite