Question

I have a python function getstock() that pulls market data for random companies from yahoo for analysis. Occasionally, at a particular point in the script, if my function enters in a company that Yahoo Finance doesn't recognize, I'll get the following error:

Traceback (most recent call last):
  File "<pyshell#65>", line 8, in <module>
    stockhistory=pandas.io.data.get_data_yahoo(stock, start=datetime(1900,1,1), end=datetime(2014,1,1))
  File "/usr/lib/python2.7/dist-packages/pandas/io/data.py", line 405, in get_data_yahoo
    adjust_price, ret_index, chunksize, 'yahoo', name)
  File "/usr/lib/python2.7/dist-packages/pandas/io/data.py", line 351, in _get_data_from
    hist_data = src_fn(symbols, start, end, retry_count, pause)
  File "/usr/lib/python2.7/dist-packages/pandas/io/data.py", line 200, in _get_hist_yahoo
    return _retry_read_url(url, retry_count, pause, 'Yahoo!')
  File "/usr/lib/python2.7/dist-packages/pandas/io/data.py", line 177, in _retry_read_url
    "return a 200 for url %r" % (retry_count, name, url))
IOError: after 3 tries, Yahoo! did not return a 200 for url 'http://ichart.finance.yahoo.com/table.csv?s=LE&a=0&b=1&c=1900&d=0&e=1&f=2014&g=d&ignore=.csv'

This can be remedied by just using a different company (calling the function again).

My Question is: how might I write an if-statement that effectively says "If the error above occurs, run the function getstock() again."

Was it helpful?

Solution

Generally, I would do it like this:

for stock in stocks:
    try: 
        stockhistory = pandas.io.data.get_data_yahoo(stock, ...)
    except IOError:
        pass # it failed, skip on to next stock in stocks
    else:
        # it succeeded, process stockhistory here
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top