pythonpython-3.xyahoo-financeyahoo-api

Assertionerror - Display only error message


I've the folowing code and want to print only the error (No data found, symbol may be delisted).

Is it possible write better code?

import yahoo_fin.stock_info as si
import sys
try:
    quoteinfo = si.get_data("badticker",start_date = "01/01/2022", end_date = "04/30/2022")
    print(quoteinfo)
except AssertionError as e:
    if (  "symbol may be delisted" in str(e)) :
        print ('Ticker is invalid')
    else:
        print(e)

Exception :

{'chart': {'result': None, 'error': {'code': 'Not Found', 'description': 'No data found, symbol may be delisted'}}}


Solution

  • Your code looks mostly fine. However:

    1. I'd check against the full string: 'No data found, symbol may be delisted' to be on the save side,
    2. the brackets in the if-statement are redundant,
    3. you got unused imports,
    4. your code could also use some formatting.
    import yahoo_fin.stock_info as si
    
    try:
        quoteinfo = si.get_data("badticker", start_date="01/01/2022", end_date="04/30/2022")
    except AssertionError as e:
        if "No data found, symbol may be delisted" in str(e):
            print("Ticker is invalid")
        else:
            print(e)