Search code examples
pythonfor-loopyahoo-financeyfinance

How to iterate over the class in python? (yfinance class)


I'm trying to get some data for multiple stocks, but simple for loop does not iterate over the class. For example:

    In[2]:  import yfinance as yf
            stock = yf.Ticker('AAPL')
            stock.info.get('sharesOutstanding')
    Out[2]: 4375479808

And when I'm trying something like:

t = ['AAPL', 'MSFT']
for str in t:
    stock = yf.Ticker(str)
    a = []
    a = stock.info.get('sharesOutstanding')

I get only MSFT shares outstanding. Ideally, the result must be a dataframe like:

     sharesOutstanding
AAPl 4375479808
MSFT 7606049792

Any ideas how to realise it? Actually I have list of about 6375 stocks, but if there would be a solve for two stocks, then code cample can be used for multiple stocks, I think.

PROBLEM SOLVING:

a = []
b = []
for str in t:
    try:
        stock = yf.Ticker(str)
        a.append(stock.info.get('sharesOutstanding'))
        b.append(stock.info.get('symbol'))
    except KeyError:
        continue
    except IndexError:
        continue
shares_ots = pd.DataFrame(a, b)

Solution

  • The problem most likely occurs because the a list is declared locally within the loop, meaning that the data it holds is overridden each iteration.

    To solve the issue, we can declare the list outside of the scope of the loop. This way, it can retain its information.

    t = ['AAPL', 'MSFT']
    a = []
    for str in t:
        stock = yf.Ticker(str)
        a.append(stock.info.get('sharesOutstanding'))
    

    Alternatively, you can use another built-in function in the API as shown in the docs.

    tickers = yf.Tickers('aapl msft')
    # ^ returns a named tuple of Ticker objects
    
    # access each ticker
    tickers.msft.info.get('sharesOutstanding'))
    tickers.aapl.info.get('sharesOutstanding'))
    

    EDIT

    If you prefer, you can simplify the loop with list comprehension as shown:

    t = ['AAPL', 'MSFT']
    a = [yf.Ticker(str).info.get('sharesOutstanding') for str in t]
    

    Because the Ticker(str).info object is a Python dictionary, we can pass in an additional argument to the get function to specify a default fallback value.

    a = [yf.Ticker(str).info.get('sharesOutstanding', 'NaN') for str in t]
    

    In this case, if the dictionary does not have the 'sharesOutstanding' key, it will default to None. This way, we can ensure that len(a) == len(t).

    To create a pandas data frame, try something like

    df = pd.DataFrame(a, t, columns=['sharesOutstanding'])