Search code examples
pythonpython-3.xlistyahoo-financeyfinance

Is it possible to automate the adding of tickers to sector lists rather than adding individual ones?


Is it possible to automate the adding of tickers to sector lists rather than adding individual ones by iterating through the database of available tickers listed in the USA? I'm not sure how i would access the database rather than a specific ticker, so that i can begin iterating through which i believe should be simpler. Also, if anyone has a list of commands that can be used within yfinance, that would be great. I have had mixed success with those found online.

import yfinance as yf

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

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'])

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

i have used this to get some basic data from a couple of companies at a time but i would like to be able to add a section of code which can go through the yahoo finance database of available tickers listed in the USA and add relevant companies to an sector-specific list - rather than adding them individually - such as "energy" or "basic materials".


Solution

  • Try to define the sectors and their corresponding industries in the sectors dictionary. The get_tickers_by_sector function takes a sector as input and retrieves all tickers listed in the USA that belong to that sector based on the sector and industry information from yfinance.

    You can extend the sectors dictionary with more sectors and their corresponding industries as needed.

    import yfinance as yf
    import pandas as pd
    
    sectors = {
        'energy': ['XOM', 'CVX', 'BP'],
        'basic_materials': ['DD', 'LIN', 'FCX'],
        'technology': ['AAPL', 'MSFT', 'GOOGL'],
        'healthcare': ['JNJ', 'PFE', 'UNH'],
        'finance': ['JPM', 'BAC', 'GS']
        # Add more sectors and their corresponding ticker symbols as needed
    }
    
    def get_historical_data_with_sector(sectors, start_date, end_date):
        data = pd.DataFrame()
        for sector, tickers in sectors.items():
            sector_data = yf.download(tickers, start=start_date, end=end_date)
            sector_data['Sector'] = sector
            data = pd.concat([data, sector_data])
        return data
    
    # Example usage
    start_date = '2022-01-01'
    end_date = '2022-12-31'
    
    historical_data = get_historical_data_with_sector(sectors, start_date, end_date)
    print(historical_data)
    

    Check the official documentation for more details: https://pypi.org/project/yfinance/