Search code examples
pythonpython-3.xfinanceyahoo-financeyfinance

How can i create a list full of all tickers of companies in a specific industry?


How would I be able to iterate through the yfinance database and append all companies within specific industries into specific lists?

y = int(input("number of tickers:"))

def info(x):
    comp = yf.Ticker(x)
    print(comp.history(period="1d").head())
    print(comp.info['forwardPE'])
    print(comp.info['trailingPE'])
    print(comp.info['beta'])


for a in range(y):
    info(x=input("Enter ticker: "))

This is what I have so far, which works, and I was hoping to add something to allow me to compare companies within the same industry. Also, is there a list of possible commands that I can use? I've had varying success with ones I have found so far


Solution

  • In your info() function, instead of printing the company's information, you need to append the ticker symbol to the corresponding industry list.

    import yfinance as yf
    
    y = int(input("Number of tickers: "))
    industry_lists = {}
    
    def info(x, industry):
        comp = yf.Ticker(x)
        print(comp.history(period="1d").head())
        print(comp.info['forwardPE'])
        print(comp.info['trailingPE'])
        print(comp.info['beta'])
      
        if industry in industry_lists:
            industry_lists[industry].append(x)
        else:
            industry_lists[industry] = [x]
    
    for a in range(y):
        ticker = input("Enter ticker: ")
        industry = input("Enter industry: ")
        info(x=ticker, industry=industry)
    
    for industry, tickers in industry_lists.items():
        print(f"Industry: {industry}")
        print("Tickers:", tickers)
        print()
    

    To compare companies within the same industry, you can access the industry lists in the industry_lists dictionary and perform any comparisonsneeded.