不是我牛是ChatGPT牛。。。

来源: 2024-01-08 12:18:40 [博客] [旧帖] [给我悄悄话] 本文已被阅读:

问: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. 1. Install yfinance if you haven't already:
  2. pip install yfinance
  3.  
  4. 2. Use the following Python code to get the company name and sector:
  5.  

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}")