Search code examples
pythonpandasyahoo-finance

Issues while extracting Industry/Sector from Yahoo finance package


I have to change my question subject to reflect my real issue.

If I try the below example with 3 stocks, the code is working fine. However, if I add more tickers, I am getting 'Key error'. Please help.

Code:

stocks = ['ADSK', 'DDD', 'DM', 'FARO', 'MTLS', 'SSYS', 'XONE', 'AAPL', 'NXTG', 'QCOM']
    
    import yfinance as yf
    import pandas as pd
    
    df = pd.DataFrame()
    for stock in stocks:
        info = yf.Ticker(stock).info
        industry = info['industry']
        beta = info['beta']
        sector = info['sector']
        df = df.append({'Stock':stock,'Industry':industry,'Beta':beta,'Sector':sector}, ignore_index=True)

Error is below:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-35-8ae147fa8723> in <module>
      7 for stock in stocks:
      8     info = yf.Ticker(stock).info
----> 9     industry = info['industry']
     10     beta = info['beta']
     11     sector = info['sector']

KeyError: 'industry'

Solution

  • NXTG stock doesn't have neither "industry", nor "beta" fields. Dictionary method get() could be used to avoid KeyError:

    stocks = ['ADSK', 'DDD', 'DM', 'FARO', 'MTLS', 'SSYS', 'XONE', 'AAPL', 'NXTG', 'QCOM']
        
    import yfinance as yf
    import pandas as pd
        
    df = pd.DataFrame()
    for stock in stocks:
      info = yf.Ticker(stock).info
      industry = info.get('industry')
      beta = info.get('beta')
      sector = info.get('sector')
      df = df.append({'Stock':stock,'Industry':industry,'Beta':beta,'Sector':sector}, ignore_index=True)
    
    df
    

    That will give following result:

    enter image description here