ranaroussi / yfinance

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

Unable to return earnings date #2141

Closed NayrusLove closed 1 day ago

NayrusLove commented 1 day ago

Describe bug

I'm looking for upcoming earnings date to see if a company has an upcoming within the next 45 days. I'm getting an error any which way I attempt to gather this data. I've tried using earnings and calendar but each one returns an error. Feel free to run this for any company that has upcoming earnings date on the calendar.

Simple code that reproduces your problem

(python ...) import yfinance as yf from datetime import datetime, timedelta import pandas as pd

def check_upcoming_earnings(ticker_symbol, days=45): """ Checks if the given stock ticker has an upcoming earnings date within the next 'days' days.

Parameters:
    ticker_symbol (str): The stock ticker symbol.
    days (int): Number of days to look ahead for upcoming earnings.

Returns:
    date or list of dates or None: 
        - The next upcoming earnings date if within the specified range.
        - A list of all upcoming earnings dates within the range.
        - None if no earnings dates are found within the range or data is unavailable.
"""
ticker = yf.Ticker(ticker_symbol)

try:
    # Fetch earnings dates using get_earnings_dates()
    earnings_dates = ticker.get_earnings_dates()
except AttributeError as e:
    print(f"⚠️ AttributeError: {e}")
    return None
except Exception as e:
    print(f"⚠️ An unexpected error occurred while fetching earnings dates: {e}")
    return None

# Debugging: Print the type and content of earnings_dates
# Uncomment the lines below if you want to see the output structure
# print(f"Type of earnings_dates: {type(earnings_dates)}")
# print(earnings_dates)

# Check if earnings_dates is a DataFrame and not empty
if isinstance(earnings_dates, pd.DataFrame) and not earnings_dates.empty:
    # Ensure the index is in datetime format
    if not isinstance(earnings_dates.index, pd.DatetimeIndex):
        earnings_dates.index = pd.to_datetime(earnings_dates.index)

    today = datetime.today().date()
    future_date = today + timedelta(days=days)

    # Filter earnings dates within the specified range
    upcoming_earnings = earnings_dates[(earnings_dates.index.date >= today) & (earnings_dates.index.date <= future_date)]

    if not upcoming_earnings.empty:
        # Extract all upcoming earnings dates within the range
        next_earnings_dates = upcoming_earnings.index.date.tolist()
        return next_earnings_dates
else:
    # Handle cases where earnings_dates is not a DataFrame or is empty
    return None

def main(): """ Main function to prompt user input and display upcoming earnings information. """ ticker_symbol = input("Enter the stock ticker symbol: ").upper().strip()

# Validate input
if not ticker_symbol.isalnum():
    print("❌ Invalid ticker symbol. Please enter a valid alphanumeric ticker.")
    return

try:
    upcoming_earnings = check_upcoming_earnings(ticker_symbol)

    if upcoming_earnings:
        if isinstance(upcoming_earnings, list):
            dates_formatted = ', '.join(date.strftime('%Y-%m-%d') for date in upcoming_earnings)
            print(f"\n📈 {ticker_symbol} has the following upcoming earnings date(s) within the next 45 days on: {dates_formatted}.")
        else:
            print(f"\n📈 {ticker_symbol} has an upcoming earnings date on {upcoming_earnings}.")
    else:
        print(f"\n❌ {ticker_symbol} does not have an upcoming earnings date within the next 45 days or the data is unavailable.")
except Exception as e:
    print(f"\n⚠️ An error occurred while processing {ticker_symbol}: {e}")

if name == "main": main() (python ...)

Debug log

Enter the stock ticker symbol: EXAI 2024-11-20 10:27:02,260 - main - DEBUG - User entered ticker symbol: EXAI 2024-11-20 10:27:02,260 - main - DEBUG - Initializing yfinance Ticker for symbol: EXAI 2024-11-20 10:27:02,260 - main - DEBUG - Fetching earnings dates using get_earnings_dates() 2024-11-20 10:27:02,260 - yfinance - DEBUG - Entering get_earnings_dates() 2024-11-20 10:27:02,260 - yfinance - DEBUG - Entering get() 2024-11-20 10:27:02,260 - yfinance - DEBUG - Entering _make_request() 2024-11-20 10:27:02,260 - yfinance - DEBUG - url=https://finance.yahoo.com/calendar/earnings?symbol=EXAI&offset=0&size=12 2024-11-20 10:27:02,260 - yfinance - DEBUG - params=None 2024-11-20 10:27:02,260 - yfinance - DEBUG - Entering _get_cookie_and_crumb() 2024-11-20 10:27:02,260 - yfinance - DEBUG - cookie_mode = 'basic' 2024-11-20 10:27:02,260 - yfinance - DEBUG - Entering _get_cookie_and_crumb_basic() 2024-11-20 10:27:02,264 - peewee - DEBUG - ('CREATE TABLE IF NOT EXISTS "_cookieschema" ("strategy" VARCHAR(255) NOT NULL PRIMARY KEY, "fetch_date" DATETIME NOT NULL, "cookie_bytes" BLOB NOT NULL) WITHOUT ROWID', []) 2024-11-20 10:27:02,264 - peewee - DEBUG - ('SELECT "t1"."strategy", "t1"."fetch_date", "t1"."cookie_bytes" FROM "_cookieschema" AS "t1" WHERE ("t1"."strategy" = ?) LIMIT ? OFFSET ?', ['basic', 1, 0]) 2024-11-20 10:27:02,265 - yfinance - DEBUG - loaded persistent cookie 2024-11-20 10:27:02,265 - yfinance - DEBUG - reusing cookie 2024-11-20 10:27:02,272 - urllib3.connectionpool - DEBUG - Starting new HTTPS connection (1): query1.finance.yahoo.com:443 2024-11-20 10:27:02,373 - urllib3.connectionpool - DEBUG - https://query1.finance.yahoo.com:443 "GET /v1/test/getcrumb HTTP/11" 200 11 2024-11-20 10:27:02,373 - yfinance - DEBUG - crumb = 'NB5HqDMLc1K' 2024-11-20 10:27:02,373 - yfinance - DEBUG - Exiting _get_cookie_and_crumb_basic() 2024-11-20 10:27:02,373 - yfinance - DEBUG - Exiting _get_cookie_and_crumb() 2024-11-20 10:27:02,374 - urllib3.connectionpool - DEBUG - Starting new HTTPS connection (1): finance.yahoo.com:443 2024-11-20 10:27:09,597 - urllib3.connectionpool - DEBUG - https://finance.yahoo.com:443 "GET /calendar/earnings?symbol=EXAI&offset=0&size=12&crumb=NB5HqDMLc1K HTTP/11" 200 1129240 2024-11-20 10:27:09,768 - yfinance - DEBUG - response code=200 2024-11-20 10:27:09,768 - yfinance - DEBUG - Exiting _make_request() 2024-11-20 10:27:09,769 - yfinance - DEBUG - Exiting get() 2024-11-20 10:27:09,826 - main - ERROR - An unexpected error occurred while fetching earnings dates: 'Earnings Date'

❌ EXAI does not have an upcoming earnings date within the next 45 days or the data is unavailable. 2024-11-20 10:27:09,827 - main - INFO - No upcoming earnings dates found for EXAI within the next 45 days. venvdaniel@macbookpro las-fund %

Bad data proof

No response

yfinance version

0.2.50

Python version

Python 3.13.0

Operating system

Mac OS 15.1

ValueRaider commented 1 day ago

Duplicate #1932

szapiro commented 1 day ago

Happens to me too. getting following error: yfinance 0.2.50 Debian 11 5.10.0-33-amd64 Python 3.9.2

KeyError: 'Earnings Date'

Traceback (most recent call last): File "/home/XX/.local/lib/python3.9/site-packages/pandas/core/indexes/base.py", line 3790, in get_loc return self._engine.get_loc(casted_key) File "index.pyx", line 152, in pandas._libs.index.IndexEngine.get_loc File "index.pyx", line 181, in pandas._libs.index.IndexEngine.get_loc File "pandas/_libs/hashtable_class_helper.pxi", line 7080, in pandas._libs.hashtable.PyObjectHashTable.get_item File "pandas/_libs/hashtable_class_helper.pxi", line 7088, in pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: 'Earnings Date'

lukas-uhl commented 17 hours ago

Indeed not working. Same issue here. Error message: KeyError: 'Earnings Date'

Traceback (most recent call last): File "C:\Users\me\Můj disk\personal stuff\programming - own code\python\options-trader v3\venv\lib\site-packages\pandas\core\indexes\base.py", line 3805, in get_loc return self._engine.get_loc(casted_key) File "index.pyx", line 167, in pandas._libs.index.IndexEngine.get_loc File "index.pyx", line 196, in pandas._libs.index.IndexEngine.get_loc File "pandas\_libs\hashtable_class_helper.pxi", line 7081, in pandas._libs.hashtable.PyObjectHashTable.get_item File "pandas\_libs\hashtable_class_helper.pxi", line 7089, in pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: 'Earnings Date'

The above exception was the direct cause of the following exception:

Traceback (most recent call last): File "C:\Users\me\Můj disk\personal stuff\programming - own code\python\options-trader v3\yfinance_downloader\yfinance_handler.py", line 56, in get_earnings("AMD") File "C:\Users\me\Můj disk\personal stuff\programming - own code\python\options-trader v3\yfinance_downloader\yfinance_handler.py", line 48, in get_earnings df = ticker.earnings_dates File "C:\Users\me\Můj disk\personal stuff\programming - own code\python\options-trader v3\venv\lib\site-packages\yfinance\ticker.py", line 296, in earnings_dates return self.get_earnings_dates() File "C:\Users\me\Můj disk\personal stuff\programming - own code\python\options-trader v3\venv\lib\site-packages\yfinance\utils.py", line 104, in wrapper result = func(*args, *kwargs) File "C:\Users\me\Můj disk\personal stuff\programming - own code\python\options-trader v3\venv\lib\site-packages\yfinance\base.py", line 634, in get_earnings_dates tzinfo = dates[cn].str.extract('([AP]M[a-zA-Z])$') File "C:\Users\me\Můj disk\personal stuff\programming - own code\python\options-trader v3\venv\lib\site-packages\pandas\core\frame.py", line 4102, in getitem indexer = self.columns.get_loc(key) File "C:\Users\me\Můj disk\personal stuff\programming - own code\python\options-trader v3\venv\lib\site-packages\pandas\core\indexes\base.py", line 3812, in get_loc raise KeyError(key) from err KeyError: 'Earnings Date'

ranger9692 commented 11 hours ago

This is still an issue. Why is this closed? I updated yfinance, still same earnings date errors listed herein. I updated all packages to be sure, because stranger combinations hav3e certainly occured to me. Same issue. Anyone see this actually working since update two days ago?

ValueRaider commented 11 hours ago

@ranger9692 https://github.com/ranaroussi/yfinance/issues/2141#issuecomment-2489364831