金融Matplotlib

时间:2017-11-07 01:31:31

标签: python matplotlib finance

我正在尝试使下面的短代码工作。我的重点是fetch_historical_yahoo似乎没有用。我试图在更大的代码中使用它。

import datetime
import matplotlib.finance as finance
import matplotlib.mlab as mlab

startdate = datetime.date(2005,1,1)
today = enddate = datetime.date.today()
ticker = 'nvda'

fh = finance.fetch_historical_yahoo(ticker, startdate, enddate)

r = mlab.csv2rec(fh); fh.close()

r.sort()

当我运行代码时,我收到以下错误。当我去打开finance.py时,我似乎无法将手指放在url问题上。

有什么想法吗?

我尝试了mlp_finance,但我没有能够安装它。

fh = finance.fetch_historical_yahoo(ticker, startdate, enddate)

Traceback (most recent call last):

  File "<ipython-input-61-e83eb3d28a19>", line 1, in <module>
    fh = finance.fetch_historical_yahoo(ticker, startdate, enddate)

  File "C:\Users\dvargas\Anaconda3\lib\site-packages\matplotlib\finance.py", line 362, in fetch_historical_yahoo
    with contextlib.closing(urlopen(url)) as urlfh:

  File "C:\Users\dvargas\Anaconda3\lib\urllib\request.py", line 163, in urlopen
    return opener.open(url, data, timeout)

  File "C:\Users\dvargas\Anaconda3\lib\urllib\request.py", line 466, in open
    response = self._open(req, data)

  File "C:\Users\dvargas\Anaconda3\lib\urllib\request.py", line 484, in _open
    '_open', req)

  File "C:\Users\dvargas\Anaconda3\lib\urllib\request.py", line 444, in _call_chain
    result = func(*args)

  File "C:\Users\dvargas\Anaconda3\lib\urllib\request.py", line 1282, in http_open
    return self.do_open(http.client.HTTPConnection, req)

  File "C:\Users\dvargas\Anaconda3\lib\urllib\request.py", line 1256, in do_open
    raise URLError(err)

URLError: <urlopen error [Errno 11004] getaddrinfo failed>

1 个答案:

答案 0 :(得分:1)

我不得不使用解决方法。

from urllib.request import urlopen
from bs4 import BeautifulSoup as bs

def get_historical_data(name, number_of_days):
    data = []
    url = "https://finance.yahoo.com/quote/" + name + "/history/"
    rows = bs(urlopen(url).read()).findAll('table')[0].tbody.findAll('tr')

    for each_row in rows:
        divs = each_row.findAll('td')
        if divs[1].span.text  != 'Dividend': #Ignore this row in the table
            #I'm only interested in 'Open' price; For other values, play with divs[1 - 5]
            data.append({'Date': divs[0].span.text, 'Open': float(divs[1].span.text.replace(',',''))})

    return data[:number_of_days]

#Test
for i in get_historical_data('googl', 5):   
    print(i)