ranaroussi / yfinance

Download market data from Yahoo! Finance's API
https://aroussi.com/post/python-yahoo-finance
Apache License 2.0
13k stars 2.3k forks source link

yfinance ticker.info internally throwing a TypeError exception #1395

Closed Matt-Seath closed 1 year ago

Matt-Seath commented 1 year ago

Hi, I've recently started encountering an error while retrieving ticker.info for multiple stocks with a script I've been using for a while. I'm using version 0.2.9, my script is limited to a maximum of 0.4 ticker.info requests p/sec, and I am using Endeavor-OS "Kernel: 6.1.9-arch1-1".

The error returned is as follows:

  File "/home/seath/Projects/FlashFire/backtest/pipelines/yfinance_pls.py", line 73, in extract
    [yf.Ticker(self.symbols[i]).info]))
  File "/home/seath/Projects/FlashFire/venv/lib/python3.10/site-packages/yfinance/ticker.py", line 142, in info
    return self.get_info()
  File "/home/seath/Projects/FlashFire/venv/lib/python3.10/site-packages/yfinance/base.py", line 1268, in get_info
    data = self._quote.info
  File "/home/seath/Projects/FlashFire/venv/lib/python3.10/site-packages/yfinance/scrapers/quote.py", line 104, in info
    self._scrape_complementary(self.proxy)
  File "/home/seath/Projects/FlashFire/venv/lib/python3.10/site-packages/yfinance/scrapers/quote.py", line 296, in _scrape_complementary
    key_stats = json_data["timeseries"]["result"][0]
TypeError: 'NoneType' object is not subscriptable

I'm only a newb so my workaround was to just wrap the problem in a try block and set variable "v" to "None" on Exception. This appears to solve the issue but I doubt its an optimal solution.

Is this a known issue? and if so, could someone please provide a fix or point me to an existing thread as I haven't been able to find one. My changes are shown below:

python3.10/site-packages/yfinance/scrapers/quote.py (Line 296)

            json_data = json.loads(json_str)
            try:
                key_stats = json_data["timeseries"]["result"][0]
                if k not in key_stats:
                    # Yahoo website prints N/A, indicates Yahoo lacks necessary data to calculate
                    v = None
                else:
                    # Select most recent (last) raw value in list:
                    v = key_stats[k][-1]["reportedValue"]["raw"]
            except:
                v = None
            self._info[k] = v
ValueRaider commented 1 year ago

0.4 p/sec is high for info data, so probably triggering Yahoo spam which then cause Yahoo to return incomplete data.

The fix is fine, submit in a pull request (read #1084).

Matt-Seath commented 1 year ago

Thanks for your reply, I should have clarified my script is only capped to 0.4 p/sec, but because I live off Australias NBN, it takes about 7 - 8 sec each request on average. Because of this, I don't think the issue is spam related..

For now the workaround is still working so I'll put in a pull request shortly, thanks.