yfinance: Getting 429 error (rate-limit) when in loop, suggestion to add try-catch if fails
Describe bug
When running a loop over multiple tickers, yahoo flags me even when using a VPN and switching servers multiple times per day. I found that there are many yahoo data sources where this happens, and I’ll be happy to go through all of them and share them here if this is approved to be implemented.
Simple code that reproduces your problem
It’s a bit tricky to reproduce this error because you would have to run numerous requests over a period of time in order for yahoo to flag you. However, if it returns 429 error we can fix it with the following code block:
try:
<current code> # (say you set data = requests.get(url)
except data.status_code == 429:
data = requests.get(url, headers={'User-agent': '<some auto-generated value (e.g. hash) that pretty much never gets repeated.>'})
example where it fails for me
import yfinance as yf
>>> import requests
>>> url = 'https://query2.finance.yahoo.com/v10/finance/quoteSummary//013A.F?modules=institutionOwnership%2CfundOwnership%2CmajorDirectHolders%2CmajorHoldersBreakdown%2CinsiderTransactions%2CinsiderHolders%2CnetSharePurchaseActivity&corsDomain=finance.yahoo.com&'
>>> data = requests.get(url)
>>> data.text
'Too Many Requests\r\n'
>>> data.json
<bound method Response.json of <Response [429]>>
>>> data
<Response [429]>
>>> data2 = requests.get(url, headers={'User-agent': 'some bot generate new value'})
>>> data2
<Response [200]>
Debug log
Bad data proof
No response
yfinance version
0.2.38
Python version
3.10.12
Operating system
using both linux and MacOS
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Reactions: 4
- Comments: 41 (5 by maintainers)
Yes, seems so, I was able to fetch info for 320 tickers using small code changes:
@nike576 there is a Patreon link on the repo’s main page: https://patreon.com/ranaroussi You could send a little donation to the developers of this useful module.
You shouldn’t need to do this anymore. #2277 with the latest release
I fixed the problem by updating the user agent headers.
By default yfinance (v0.2.37) set the user agent in the class
yfinance.data.YfDataas a static parameter (lines 59-60):I noticed the very old version of Chrome (39.0.2171.95) and I decided to amend it to a more recent version (133.0.0.0):
With this I have no more problem in downloading the data.
I hope this helps.
Yeah i’m having some issues and concerns over the possible rate limiting on their end. Im doing a less than 100 tickers daily data retrieval and yet im not able to retrieve any data (or only a 1 or 2 times per day trial basis)
Hitting the 429 error less than 100 tickers in, and also started past day or two. Seems like yahoo has some new rule?