YFRateLimitError: Too Many Requests. Rate limited. Try after a while. looks like a simple wait-and-retry problem. In practice, the same message can mean a rejected client fingerprint, a shared cloud IP that Yahoo has already throttled, or a symbol and date combination that never had data. Worse, yf.download() can log the 429 and return an empty DataFrame, so the exception never reaches your except block.
This walkthrough gives you a diagnostic order: prove the limit is real, reproduce the silent empty result, then apply four fixes in the order that removes causes instead of guessing. It is written for scheduled jobs and notebooks pulling many tickers, especially from cloud runners where the outbound IP is shared with other users.
Table of Contents
- Confirm the failure before changing code
- Reproduce the silent empty DataFrame
- Fix 1: Upgrade yfinance and curl_cffi
- Fix 2: Remove custom sessions and caches
- Fix 3: Batch tickers and reuse cached bars
- Fix 4: Retry empty frames with bounded backoff
- Put the fixes in one resumable loader
- When to stop retrying
- Diagnostic checklist
- Conclusion
Confirm the failure before changing code
A 429 is an HTTP response, but YFRateLimitError is not proof that you exceeded a published quota. Yahoo does not publish a numeric limit for the endpoints yfinance uses, and the exception carries the same fixed message whether the refusal came from request volume, a client that does not look like a browser, or a shared IP.
Start by separating three cases:
| Symptom | Likely cause | How to confirm |
|---|---|---|
| 429 on the first call for a liquid symbol | Client rejected before volume matters, or a flagged IP | Try the same probe from another network and check the yfinance session setup |
Empty frame plus a log line containing Failed download and YFRateLimitError
|
A real throttle that yf.download() swallowed |
Read the error log, not just the return value |
| Empty frame plus "possibly delisted" or no error at all | Wrong symbol, delisted ticker, or a date range with no sessions | Test a known-good symbol with the same dates |
A useful probe is to call Ticker.history() rather than download(), because history() propagates the rate-limit error while download() catches it. Run the probe for a liquid symbol and for the suspect symbol with the same dates:
import logging
import yfinance as yf
from yfinance.exceptions import YFRateLimitError
logging.basicConfig(level=logging.INFO)
yf.config.debug.logging = True
yf.config.debug.hide_exceptions = False
def probe(symbol: str, start: str, end: str) -> str:
try:
frame = yf.Ticker(symbol).history(start=start, end=end, auto_adjust=False)
except YFRateLimitError:
return "rate limited (raised)"
except Exception as exc:
return f"{type(exc).__name__}: {exc}"
if frame.empty:
return "empty frame"
return f"ok: {len(frame)} rows, {frame.index.min().date()} to {frame.index.max().date()}"
print(probe("AAPL", "2026-01-01", "2026-02-01"))
print(probe("THISISNOTATICKER", "2026-01-01", "2026-02-01"))
If AAPL also fails with a 429, treat it as a client, network, or IP problem. If AAPL returns rows and only the suspect symbol is empty, fix the symbol or date range before touching retry logic.
Date handling matters here. The yfinance.download API reference notes that end is exclusive, so end="2026-02-01" stops at the last session before 1 February. A range that starts and ends on a weekend or holiday can legitimately produce no rows even though the ticker is valid. Check frame.shape and the log before assuming the worst.
Reproduce the silent empty DataFrame
yf.download() is designed for bulk jobs, and its error handling is different from Ticker.history(). The yfinance download implementation catches each ticker's exception, records it in the error log, substitutes an empty frame, and continues with the rest of the batch. That means a try/except YFRateLimitError wrapped around yf.download() will not fire when Yahoo returns 429 for a ticker.
You can prove the behavior without waiting for a real block by making the ticker's history() method raise the same exception:
from unittest.mock import patch
import yfinance as yf
from yfinance.exceptions import YFRateLimitError
with patch("yfinance.multi.Ticker") as ticker:
ticker.return_value.history.side_effect = YFRateLimitError()
frame = yf.download("AAPL", period="5d", progress=False)
print(frame.shape, frame.empty)
On yfinance 1.8.0 this prints (0, 6) True and logs a failed download. The exact column count can change between versions, but the important part is empty being True. A real 429 produces the same result after the library logs the error; the mock just removes the wait.
This is why the retry condition must be based on the result, not only on exceptions. Check the whole frame, and for a multi-ticker download check each ticker's columns as well:
import pandas as pd
def ticker_frame(frame: pd.DataFrame, symbol: str) -> pd.DataFrame:
if frame is None:
return pd.DataFrame()
if isinstance(frame.columns, pd.MultiIndex):
level = 0 if symbol in frame.columns.get_level_values(0) else 1
if symbol not in frame.columns.get_level_values(level):
return pd.DataFrame()
if level == 0:
frame = frame[symbol]
else:
frame = frame.xs(symbol, axis=1, level=1)
return frame.dropna(how="all")
If one ticker succeeds, frame.empty is False even when another ticker in the same batch failed. The per-ticker check is what lets you retry only the symbols that are actually missing.
Fix 1: Upgrade yfinance and curl_cffi
The first fix is version hygiene. The current release, yfinance 1.8.0, came out on 3 November 2026, and its release notes state that it forces curl_cffi 0.17 or newer for security updates. Modern yfinance uses curl_cffi to build its default session; a very old pin from 2025 may predate fixes for false rate-limit errors and the current session behavior.
Upgrade both packages together:
python -m pip install -U yfinance curl_cffi
Then verify that the import path yfinance expects is actually available:
import importlib.metadata as md
from yfinance import _http
print("yfinance", md.version("yfinance"))
print("curl_cffi", md.version("curl_cffi"))
print("curl_cffi backend:", _http.HAS_CURL_CFFI)
HAS_CURL_CFFI should be True. If it is False, yfinance has fallen back to plain requests, which does not reproduce the browser TLS and HTTP/2 behavior that curl_cffi provides. Fix the installation before adding retries; a retry loop will not repair a client that Yahoo refuses from the first request.
If your project pins yfinance, check whether the pin is older than the current 1.x line. A pin that once avoided a breaking change can now keep you on a release with worse 429 behavior. Upgrade in a test environment, run a small batch, and compare the logs before changing a production pin.
Fix 2: Remove custom sessions and caches
Older yfinance examples often pass a custom requests.Session, sometimes a requests_cache.CachedSession, to add caching or a custom user agent. That advice is now a trap. Current yfinance rejects a session that exposes a cache with YFDataException and tells you to stop setting the session and let yfinance handle it; the check is visible in yfinance's session handling. That source also shows the request path: yfinance switches to its other cookie strategy on an error, retries once, and raises YFRateLimitError if the response is still 429. A custom session replaces the session yfinance would otherwise build for you.
Remove the session= argument from Ticker and download calls:
import yfinance as yf
frame = yf.download("AAPL", period="5d", progress=False)
If you need a proxy, use the config object rather than constructing your own HTTP session. If you need disk caching, cache the returned DataFrames yourself; the yfinance caching documentation explains that the library's persistent cache stores timezones and cookies, not price history.
A caching layer is still valuable, but it belongs after the download, not inside the HTTP session. The next section shows where to put it.
Fix 3: Batch tickers and reuse cached bars
A loop over Ticker.history() costs at least one request per symbol. yf.download() with a list uses one shared session and can fetch symbols in parallel, which is the better primitive for a universe of tickers. Keep chunks moderate, cap the worker count, and pause between chunks.
If you want to check the baseline call pattern before adding batching, our guide to downloading historical data with yfinance walks through yf.download() and Ticker.history() with runnable examples.
A simple batch call looks like this:
import yfinance as yf
symbols = ["AAPL", "MSFT", "NVDA", "AMZN"]
frame = yf.download(
symbols,
period="1y",
interval="1d",
group_by="ticker",
threads=4,
progress=False,
auto_adjust=True,
)
Use threads=4 rather than leaving the default threads=True. In the yfinance source, threads=True becomes one worker per CPU core, so a 32-core runner can fire 32 requests at once. That burst is exactly what a shared cloud IP does not need. A small integer keeps the parallelism but makes it predictable.
Caching is the other half of batching. Unadjusted daily bars do not change after the session, though adjusted prices can be revised when a dividend or split occurs, which is why the cache key includes the fetch date. A rerun should not ask Yahoo for the same history again. Cache per symbol, include the date in the filename so a file from yesterday is not served as today's data, and refuse to write an empty frame:
from datetime import date
from pathlib import Path
import pandas as pd
CACHE = Path("yf-cache")
CACHE.mkdir(exist_ok=True)
def cache_file(symbol: str, period: str) -> Path:
stamp = date.today().isoformat()
return CACHE / f"{symbol}_{period}_{stamp}.pkl"
def load_bars(symbol: str, period: str = "1y") -> pd.DataFrame | None:
path = cache_file(symbol, period)
return pd.read_pickle(path) if path.exists() else None
def save_bars(symbol: str, frame: pd.DataFrame, period: str = "1y") -> None:
if frame.empty:
raise ValueError(f"{symbol}: refusing to cache an empty frame")
frame.to_pickle(cache_file(symbol, period))
Only fetch the symbols that do not have a cache file for the current period. The empty-frame check is important: a cache written during an outage would otherwise be read back as if it were real data on every later run.
Fix 4: Retry empty frames with bounded backoff
Once batching and caching are in place, retries become a smaller, more targeted tool. The retry condition is an empty frame or an empty ticker column, not except YFRateLimitError. Start with a long wait, add jitter so parallel jobs do not retry at the same instant, and stop after a fixed number of attempts.
import random
import time
import pandas as pd
import yfinance as yf
def download_with_backoff(symbols, attempts=6, base=30, cap=900):
for attempt in range(attempts):
frame = yf.download(
symbols,
period="5d",
interval="1d",
threads=False,
progress=False,
)
if frame is None:
frame = pd.DataFrame()
if not frame.empty:
return frame
if attempt == attempts - 1:
break
wait = min(cap, base * 2 ** attempt) * random.uniform(0.8, 1.2)
print(f"empty frame; sleeping {wait:.0f}s before retry {attempt + 1}")
time.sleep(wait)
return frame
Thirty seconds is a better starting point than one second. A tight retry loop keeps the block alive; yfinance's own source notes that once Yahoo rate-limits, more requests only extend the block. Five escalating waits with a 15-minute cap give a genuine volume limit time to clear without hiding a client-level rejection.
Do not use yf.config.network.retries as your 429 strategy. The yfinance config documentation describes that setting as automatic retry for transient network errors, with waits of 1, 2, and 4 seconds; an HTTP 429 response is not a transient network error. It is a successful round trip with a refusal, and it needs your own policy.
For a multi-ticker frame, not frame.empty is too coarse. One surviving ticker makes the whole frame non-empty. Use the per-ticker extraction shown earlier, retry only the missing symbols, and keep the rest of the data.
Put the fixes in one resumable loader
The pieces fit together in a loader that batches missing symbols, caches successful bars, retries empty results, and records what it could not fetch. The skipped list is the handoff to the next run: symbols that outlasted the retries have no cache file, so the next run picks them up automatically.
import json
import random
import time
from datetime import date
from pathlib import Path
import pandas as pd
import yfinance as yf
CACHE = Path("yf-cache")
CACHE.mkdir(exist_ok=True)
SKIPPED = Path("yf-skipped.json")
def cache_file(symbol: str, period: str) -> Path:
stamp = date.today().isoformat()
return CACHE / f"{symbol}_{period}_{stamp}.pkl"
def ticker_frame(frame: pd.DataFrame, symbol: str) -> pd.DataFrame:
if frame is None:
return pd.DataFrame()
if isinstance(frame.columns, pd.MultiIndex):
level = 0 if symbol in frame.columns.get_level_values(0) else 1
if symbol not in frame.columns.get_level_values(level):
return pd.DataFrame()
if level == 0:
frame = frame[symbol]
else:
frame = frame.xs(symbol, axis=1, level=1)
return frame.dropna(how="all")
def chunked(items: list[str], size: int):
for i in range(0, len(items), size):
yield items[i:i + size]
def update_cache(symbols: list[str], period: str = "1y", chunk: int = 50) -> list[str]:
missing = [s for s in symbols if not cache_file(s, period).exists()]
skipped: list[str] = []
for batch in chunked(missing, chunk):
pending = batch
for attempt in range(6):
if attempt:
wait = min(900, 30 * 2 ** (attempt - 1)) * random.uniform(0.8, 1.2)
time.sleep(wait)
frame = yf.download(
pending,
period=period,
interval="1d",
group_by="ticker",
threads=4,
progress=False,
auto_adjust=True,
)
pending = []
for symbol in batch:
bars = ticker_frame(frame, symbol)
if bars.empty:
pending.append(symbol)
else:
bars.to_pickle(cache_file(symbol, period))
if not pending:
break
batch = pending
skipped.extend(pending)
time.sleep(5)
SKIPPED.write_text(json.dumps(sorted(set(skipped)), indent=2))
return sorted(set(skipped))
Call update_cache(symbols) once per run. It returns the symbols that still need attention, writes them to yf-skipped.json, and leaves a cache file for every success. On the next run, the cache check skips the completed symbols and tries the rest. The six-attempt loop starts with a 30-second wait, doubles it, adds jitter, and caps each wait at 15 minutes, so a bad afternoon does not turn into an infinite request loop.
Two operational details are worth adding in a real job. Delete old cache files periodically so the directory does not grow forever, and log the skipped list with the run ID. If the same symbols appear in the skipped file for several runs, stop retrying them and investigate the symbols or the network before the next scheduled run.
When to stop retrying
There are two cases where more retries are the wrong move.
The first is a 429 on the very first request from a known-good symbol on a network that worked before. That pattern points to a client or IP-level rejection, not a volume limit that will clear in 15 minutes. Check the version and curl_cffi backend, remove custom sessions, and test from a different network. Shared cloud addresses used by Colab, CI runners, and serverless functions are often already throttled before your job sends anything.
The second is a scheduled production workload that keeps hitting the limit even after batching, caching, and long backoff. Yahoo's Developer API Terms state that the APIs may be subject to rate limits at Yahoo's sole discretion, and they prohibit selling, leasing, or deriving income from the APIs without permission. yfinance's own documentation describes the project as a research and educational tool and points users to Yahoo's terms for the data. That is a reasonable fit for notebooks and research; it is not a service-level agreement for a nightly product job.
When the job must not fail, move it to a source with a published quota and a support contract. If you only need filed fundamentals rather than prices, the SEC's developer resources document free JSON APIs on data.sec.gov and a fair-access guideline of no more than 10 requests per second. If you need prices and intraday history, use a market-data vendor with a stated request allowance. A proxy can move you off a burned shared IP, but it does not turn Yahoo's endpoints into a supported API or change the terms.
Diagnostic checklist
Work down this list when a run fails or returns empty frames:
- Run the same date range for a known-good symbol. If it also fails with 429, treat it as a client, network, or IP problem. If it succeeds, inspect the suspect symbol and date range.
- Print the yfinance and
curl_cffiversions and confirm_http.HAS_CURL_CFFIisTrue. - Search the code for
session=. Remove custom sessions, especially caching sessions. - Check whether the failure is an exception or an empty result.
yf.download()logs the error and returns an empty frame;Ticker.history()raises. - For a multi-ticker frame, check each ticker's columns. Do not rely on the whole frame being empty.
- Replace
Ticker.history()loops withyf.download()in chunks of about 50, usingthreads=4. - Add a date-stamped cache and refuse to write an empty frame.
- Use a 30-second base, jitter, a 15-minute cap, and six attempts. Do not retry in a tight loop.
- If it fails only on cloud or CI runners, move the job to a cleaner network or switch to a quota-backed source.
- If the same symbols survive several retry cycles, stop and investigate instead of extending the block.
Conclusion
The yfinance YFRateLimitError fix is a sequence, not a single flag. Confirm the failure with a known-good symbol, reproduce the silent empty DataFrame, then upgrade yfinance and curl_cffi, remove custom sessions and caching sessions, batch and cache your tickers, and retry only the empty results with long, bounded backoff.
The most common mistake is treating yf.download() like a function that raises. It does not. Check the returned frame and the per-ticker columns, and record skipped symbols so the next run can resume. When the same job fails from the first request or keeps failing after a proper backoff, stop retrying and move the workload to a source with a published quota.
Top comments (0)