From 8e3173420e9a6c592dfabfdb9da526c942013b94 Mon Sep 17 00:00:00 2001 From: Harshika Matharia Date: Sat, 15 Nov 2025 20:59:15 +0530 Subject: [PATCH] Enhanced error handling with detailed exception messages in fetch_stocks.py --- Stock-Analysis/fetch_stocks.py | 42 +++++++++++++++++++++++++++------- 1 file changed, 34 insertions(+), 8 deletions(-) diff --git a/Stock-Analysis/fetch_stocks.py b/Stock-Analysis/fetch_stocks.py index 7063b62..a24cb76 100644 --- a/Stock-Analysis/fetch_stocks.py +++ b/Stock-Analysis/fetch_stocks.py @@ -6,20 +6,46 @@ class StockFetcher: @staticmethod def fetch_stock_data(stock): - """Fetch stock data from Yahoo Finance.""" + """Fetch stock data from Yahoo Finance with improved error handling.""" try: ticker = yf.Ticker(stock) info = ticker.info - if not info or 'recommendationMean' not in info: - raise ValueError("Recommendation data is missing") + + # Check if info returned anything + if not info: + raise ValueError("Empty response received from Yahoo Finance API") + + # Check if recommendation data exists + if 'recommendationMean' not in info: + raise KeyError("recommendationMean field missing in API response") + rate = info["recommendationMean"] return (rate, stock) + except ValueError as e: - logging.getLogger(__name__).error(f"Value error for stock {stock}: {e}") + logging.getLogger(__name__).error( + f"[ValueError] Unable to fetch data for '{stock}': {e}. " + f"Possible causes: Invalid stock symbol or empty API response." + ) + except KeyError as e: - logging.getLogger(__name__).error(f"Key error for stock {stock}: {e}", exc_info=True) + logging.getLogger(__name__).error( + f"[KeyError] Missing expected data for '{stock}': {e}. " + f"The API might have changed or the stock does not provide recommendation data.", + exc_info=True + ) + except URLError as e: - logging.getLogger(__name__).error(f"Network error while fetching data for {stock}: {e}") + logging.getLogger(__name__).error( + f"[URLError] Network issue while fetching '{stock}': {e}. " + f"Please check your internet connection or try again later." + ) + except Exception as e: - logging.getLogger(__name__).error(f"Unexpected error while fetching data for {stock}: {e}", exc_info=True) - return None \ No newline at end of file + logging.getLogger(__name__).error( + f"[Unexpected Error] Failed to fetch '{stock}': ({type(e).__name__}) {e}", + exc_info=True + ) + + return None +