16

Just looking for a simple api return, where I can input a ticker symbol and receive the full company name:

ticker('MSFT') will return "Microsoft"

paulz
  • 382
  • 1
  • 3
  • 10

6 Answers6

15

import yfinance as yf

msft = yf.Ticker("MSFT")

company_name = msft.info['longName']

#Output = 'Microsoft Corporation'

So this way you would be able to get the full names of companies from stock symbols

  • 2
    I love yfinance and use it regularly. Unfortunately it seems that the info method is somewhat flaky, depending on the stock your working with. Some of the other suggestions above seem to be from the days when the Yahoo and Google APIs were still functioning. – dborger Feb 22 '20 at 01:57
  • Actually this answer does not work appropriately for all tickers. For example, the ticker OGEN (which is Oragenics, Inc) gives the following error: IndexError: list index out of range I guess it's just that yfinance is not up-to-date. Also, if you gibe a non-existent ticker, e.g. "--", it throws a ValueError: ValueError: No tables found When, ideally it I would expect something along the lines of None. – alejandro Jun 15 '20 at 23:38
  • 1
    The script returns me the error '--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In [6], line 5 1 import yfinance as yf 3 msft = yf.Ticker("MSFT") ----> 5 company_name = msft.info['longName'] KeyError: 'longName' – efueyo Dec 25 '22 at 19:15
14

You need to first find a website / API which allows you to lookup stock symbols and provide information. Then you can query that API for information.

I came up with a quick and dirty solution here:

import requests


def get_symbol(symbol):
    symbol_list = requests.get("http://chstocksearch.herokuapp.com/api/{}".format(symbol)).json()

    for x in symbol_list:
        if x['symbol'] == symbol:
            return x['company']


company = get_symbol("MSFT")

print(company)

This website only provides company name. I didn't put any error checks. And you need the requests module for it to work. Please install it using pip install requests.

Update: Here's the code sample using Yahoo! Finance API:

import requests


def get_symbol(symbol):
    url = "http://d.yimg.com/autoc.finance.yahoo.com/autoc?query={}&region=1&lang=en".format(symbol)

    result = requests.get(url).json()

    for x in result['ResultSet']['Result']:
        if x['symbol'] == symbol:
            return x['name']


company = get_symbol("MSFT")

print(company)
masnun
  • 11,635
  • 4
  • 39
  • 50
4

Using fuzzy match to get company symbol from company name or vice versa

from fuzzywuzzy import process
import requests

def getCompany(text):
    r = requests.get('https://api.iextrading.com/1.0/ref-data/symbols')
    stockList = r.json()
    return process.extractOne(text, stockList)[0]


getCompany('GOOG')
getCompany('Alphabet')
1

Here's another Yahoo API call. @masnun's call will return all results that contain the search param, for example trying AMD (Advanced Micro Devices): http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=amd&region=1&lang=en gives you AMD (Advanced Micro Devices, Inc.), AMDA (Amedica Corporation), DOX (Amdocs Limited), etc.

If you know the ticker, you can try either of these Yahoo APIs:z http://finance.yahoo.com/d/quotes.csv?s=amd&f=nb4t8 (well documented, this particular call asks for n=name; b4=book value; t8=1yr target price). https://query2.finance.yahoo.com/v7/finance/options/amd (not very well documented but new...see more info here about this API: https://stackoverflow.com/a/40243903/933972)

Forgot to include the Google API, which seems ok for stock quotes, but not reliable for full data on option chains: 'https://www.google.com/finance?q=nyse:amd&output=json'

Community
  • 1
  • 1
dmayo
  • 640
  • 6
  • 16
1

For anyone wondering how to get the stock price of a company using its name rather than its symbol

import yfinance as yf

def getStock(search_term):
    results = []
    query = requests.get(f'https://yfapi.net/v6/finance/autocomplete?region=IN&lang=en&query={search_term}', 
    headers={
        'accept': 'application/json',
        'X-API-KEY': 'API_KEY'
    })
    response = query.json()
    for i in response['ResultSet']['Result']:
        final = i['symbol']
        results.append(final)

    try:
        stock = yf.Ticker(results[0])
        price = stock.info["regularMarketPrice"]
        full_name = stock.info['longName']
        curreny = stock.info["currency"]
    except Exception as e:
        print('Something went wrong')

return f"The stock price of {full_name} is {price} {curreny}"

stock = input("Enter the company's name: ")
final = getStock(stock)
print(final)

Output:

Enter the company's name: Apple
The stock price of Apple Inc. is 172.39 USD
Rohith Nambiar
  • 2,957
  • 4
  • 17
  • 37
0

I use Quandl for prices, so when I had a similar issue I decided to check there. If you go to https://www.quandl.com/data/EOD-End-of-Day-US-Stock-Prices/documentation about a quarter of the way down under Available Tickers there is a link to download a csv file containing names and tickers. I then use the following code to create a dictionary with ticker as key and name a value.

def companyNames():
    cnames = pd.read_csv('ticker_list.csv')
    cnames_dict = pd.Series(cnames.Name.values, index=cnames.Ticker).to_dict()
    
    return cnames_dict
Ajeet Verma
  • 2,938
  • 3
  • 13
  • 24
dborger
  • 89
  • 2
  • 5