ranaroussi / yfinance

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

python nvidia_stock_tool.py #2057

Closed Kessi69 closed 3 weeks ago

Kessi69 commented 1 month ago

Describe bug

C:\Users\basse>python nvidia_stock_tool.py Current Stock Information for NVDA: Company Name: NVIDIA Corporation Traceback (most recent call last): File "C:\Users\basse\nvidia_stock_tool.py", line 34, in display_stock_data(hist, info) File "C:\Users\basse\nvidia_stock_tool.py", line 20, in display_stock_data print(f"Current Price: ${info['regularMarketPrice']:.2f}")


KeyError: 'regularMarketPrice'

### Simple code that reproduces your problem

Python 

### Debug log

import yfinance as yf
import logging

# Configure logging
logging.basicConfig(filename='nvidia_stock_tool.log', level=logging.DEBUG, 
                    format='%(asctime)s - %(levelname)s - %(message)s')

def get_stock_data(ticker):
    logging.debug(f"Fetching stock data for ticker: {ticker}")
    try:
        # Create a Ticker object
        stock = yf.Ticker(ticker)

        # Fetch historical market data for the last 5 days
        hist = stock.history(period='5d')  # You can adjust the period as needed

        # Fetch current stock info
        info = stock.info
        logging.debug(f"Fetched stock info: {info}")

        return hist, info
    except Exception as e:
        logging.error(f"Error fetching stock data: {e}")
        raise

def display_stock_data(hist, info):
    logging.debug("Displaying stock data")

    # Print the entire info dictionary to inspect available keys
    logging.debug("Full info dictionary:")
    for key, value in info.items():
        logging.debug(f"{key}: {value}")

    # Safely retrieve information with defaults if key is missing
    def get_info(key):
        return info.get(key, 'Data not available')

    # Print current stock information
    print(f"Current Stock Information for {get_info('symbol')}:")
    print(f"Company Name: {get_info('longName')}")
    print(f"Current Price: ${get_info('regularMarketPrice')}")
    print(f"Market Cap: ${get_info('marketCap')}")
    print(f"PE Ratio: {get_info('trailingPE')}")
    print(f"52 Week High: ${get_info('fiftyTwoWeekHigh')}")
    print(f"52 Week Low: ${get_info('fiftyTwoWeekLow')}")
    print(f"Dividend Yield: {get_info('dividendYield')}")

    # Print historical data
    print("\nHistorical Data (Last 5 Days):")
    print(hist)

if __name__ == "__main__":
    ticker = 'NVDA'
    try:
        hist, info = get_stock_data(ticker)
        display_stock_data(hist, info)
    except Exception as e:
        logging.error(f"Unhandled exception: {e}")

### Bad data proof

_No response_

### `yfinance` version

Location: C:\Users\basse\AppData\Roaming\Python\Python312\site-packages Requires: beautifulsoup4, frozendict, html5lib, lxml, multitasking, numpy, pandas, peewee, platformdirs, pytz, requests Required-by:

### Python version

Python 3.12.6

### Operating system

windows 11
SaumyaC11 commented 3 weeks ago

Hey

I suggest giving it another try. I ran your code, and it is working perfectly fine. This happens sometimes when there is a problem with Yahoo Finance. I would suggest making your code robust by handling conditions when it gives a KeyError.