Python and Yahoo finance weird “YQLQueryError(response['error']['description'])” get_historical

寵の児 提交于 2019-11-28 02:03:10

It looks like this functionality has been discontinued: https://forums.yahoo.net/t5/Yahoo-Finance-help/ichart-not-working-in-my-app/td-p/253560

Here's a workaround (grab the data directly from the history pages):

import urllib2
from BeautifulSoup import BeautifulSoup as bs

def get_historical_data(name, number_of_days):
    data = []
    url = "https://finance.yahoo.com/quote/" + name + "/history/"
    rows = bs(urllib2.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('amzn', 5):
    print i

Output:

{'Date': u'Jun 02, 2017', 'Open': 999.0}
{'Date': u'Jun 01, 2017', 'Open': 998.59}
{'Date': u'May 31, 2017', 'Open': 1000.0}
{'Date': u'May 30, 2017', 'Open': 996.51}
{'Date': u'May 26, 2017', 'Open': 995.0}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!