问:how to get company name and sector for a stock using yfinance
答:
To get the company name and sector for a stock using the yfinance
library in Python, you can follow these steps:
- 1. Install
yfinance
if you haven't already: - pip install yfinance
- 2. Use the following Python code to get the company name and sector:
-
import yfinance as yf def get_company_info(ticker_symbol): # Create a Ticker object for the given stock symbol ticker = yf.Ticker(ticker_symbol) try: # Get the info dictionary for the stock info = ticker.info # Extract company name and sector from the info dictionary company_name = info['longName'] sector = info['sector'] return company_name, sector except Exception as e: print(f"Error: Unable to retrieve information for {ticker_symbol}.") print(f"Error details: {e}") return None, None # Example: Get information for Apple Inc. (AAPL) ticker_symbol = 'AAPL' company_name, sector = get_company_info(ticker_symbol) if company_name and sector: print(f"Company Name: {company_name}") print(f"Sector: {sector}")