You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决yfinance出现的JSONDecode错误——代码仅能成功运行一次后即失效

Fixing yfinance JSONDecodeError That Only Runs Successfully Once

Hey, sorry to hear you're stuck with this frustrating yfinance issue—especially since it popped up after messing with Docker, even after you uninstalled it. Let's break down what might be going on and try some targeted fixes, building on the steps you've already attempted:

1. First, Check Cron vs. Your User Environment

A super common gotcha with cron jobs is that they run in a different environment than when you manually execute your script. This often causes weird inconsistencies like "works once manually, breaks in cron":

  • Verify the Python path cron uses matches yours. Add import sys; print(sys.executable) to your script, run it manually, then check the cron log to see if the paths align. If not, update your cron command to use the full path to your Python executable (e.g., /home/youruser/.venv/bin/python instead of just python).
  • Cron runs in a default working directory (usually /), which might mess with yfinance's caching or file access. Add this to the top of your script to switch to the script's directory:
    import os
    script_dir = os.path.dirname(os.path.abspath(__file__))
    os.chdir(script_dir)
    
  • Enable full logging for your cron job to get the complete error traceback, not just the JSONDecodeError. Modify your cron line to:
    * * * * * /full/path/to/python /full/path/to/your/script.py >> /var/log/yfinance_cron.log 2>&1
    

This will log both stdout and stderr, so you can see exactly where the decode is failing.

2. Nuke yfinance's Local Cache

yfinance caches data locally, and a corrupted cache is likely causing this "works once then breaks" behavior—reinstalling the package often doesn't clear this cache automatically:

  • Find and delete the yfinance cache directory. On most systems, this lives at ~/.cache/yfinance—run this command in your terminal:
    rm -rf ~/.cache/yfinance
    
  • Alternatively, force yfinance to ignore the cache in your script to test if this is the root cause:
    import yfinance as yf
    ticker = yf.Ticker("AAPL")
    data = ticker.history(period="1d", ignore_cache=True)
    

3. Try a Stable yfinance Version

Sometimes the latest yfinance version has bugs, or the version you rolled back to isn't compatible with your other dependencies. Let's test a known-stable release:

  • Downgrade to version 0.2.31 (many users report this version is reliable):
    pip uninstall -y yfinance && pip install yfinance==0.2.31 --no-cache-dir
    
  • If that doesn't work, try the latest development build (in case the team fixed this issue recently):
    pip install git+https://github.com/ranaroussi/yfinance.git --no-cache-dir
    

4. Add Robust Retries for Network Requests

JSONDecodeError often happens when Yahoo Finance returns an error page (like 429 Too Many Requests) instead of valid JSON. Your time.sleep(1) helps, but adding retries will make your script more resilient:

  • Add a simple retry loop to your data fetching code:
    import yfinance as yf
    import time
    import json
    
    def fetch_ticker_data(symbol, max_retries=3):
        for attempt in range(max_retries):
            try:
                ticker = yf.Ticker(symbol)
                return ticker.history(period="1d")
            except json.JSONDecodeError:
                print(f"Fetch failed, retrying in 2s (attempt {attempt+1}/{max_retries})")
                time.sleep(2)
        raise RuntimeError(f"Couldn't fetch data for {symbol} after {max_retries} retries")
    
  • Also, double-check if your IP is being rate-limited. Try manually visiting Yahoo Finance's stock page in a browser—if you see a CAPTCHA or "too many requests" message, you might need to wait or adjust your request frequency.

5. Fix System Dependency Issues

Docker installation can sometimes overwrite or update system libraries (like SSL/curl libraries) that Python's request tools rely on. Let's reset those critical dependencies:

  • Reinstall requests and urllib3 (the libraries yfinance uses under the hood) to ensure they're not corrupted:
    pip uninstall -y requests urllib3 && pip install requests urllib3 --no-cache-dir
    
  • Test if your Python can even reach Yahoo Finance's API properly. Run this quick diagnostic script:
    import requests
    response = requests.get("https://query1.finance.yahoo.com/v8/finance/chart/AAPL")
    print(f"Status code: {response.status_code}")
    print(f"First 500 chars of response: {response.text[:500]}")
    

If the status code is 429/503 or the response is HTML instead of JSON, that's a network/rate-limiting issue, not a yfinance bug.


内容的提问来源于stack exchange,提问作者Mayank

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 01:38:10