Skip to content

Instantly share code, notes, and snippets.

@leftmove
Last active May 29, 2024 21:10
Show Gist options
  • Save leftmove/dd9d981c8c37983f61e423a45085e063 to your computer and use it in GitHub Desktop.
Save leftmove/dd9d981c8c37983f61e423a45085e063 to your computer and use it in GitHub Desktop.
Company name to ticker using Yahoo Finance API endpoint
def get_ticker(company_name):
yfinance = "https://query2.finance.yahoo.com/v1/finance/search"
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36'
params = {"q": company_name, "quotes_count": 1, "country": "United States"}
res = requests.get(url=yfinance, params=params, headers={'User-Agent': user_agent})
data = res.json()
company_code = data['quotes'][0]['symbol']
return company_code
@leftmove
Copy link
Author

leftmove commented Jan 16, 2023

Given a company's name, this function will return the ticker.

Most tutorials online are to get a company's name from its ticker symbol (for example, supplying MSFT returns "Microsoft"). This function does the opposite operation, where supplying "Microsoft" returns MSFT.


Sample
get_ticker('Texas Instruments')

  Data
Input Texas Instruments
Output TXN

As a side note, you can change the user agent as you wish. For information on what that means, see here.

This function is done by making a GET request to the Yahoo! Finance API.


Thanks to @0x4f53 for finding the original endpoint and writing the initial gist.

(My username was changed from "bruhbruhroblox" to "leftmove")

@gpetrone84
Copy link

gpetrone84 commented May 2, 2023

This does not longer work @bruhbruhroblox, do you have any hint on how to make this working again?

@MattDMo
Copy link

MattDMo commented May 31, 2023

@gpetrone84 works for me. get_ticker("Tesla") returns "TSLA". The trick is to make sure your company_name is generic enough. I tried "Tesla Corporation" and it didn't work.

@sjudent
Copy link

sjudent commented Jul 24, 2023

Thank you for this!
I'm currently doing CS50 pset9 Finance. The distribution code only gives the ability to search by Symbol.
I wanted a way to search company name and retrieve the symbol. I tried Alpha Vantage and IEX API but AV would return different symbols and IEX used to work but as of 22 July 2023, started returning random gibberish names.
Using your code, I was able to do what I wanted and this was way cleaner and simpler. Even better, no api key needed for yfinance so I don't need to keep creating new accounts like I did with IEX.

@smiley717
Copy link

@bruhbruhroblox Good catch! It's really helpful for me as well. I also tried to get ticker symbol from company name using OpenFIGI, FinHub, IEXCloud etc, but couldn't get correct symbols what I wanted to. it returns perfect ones. 👍

@Ajith-82
Copy link

@bruhbruhroblox Thank you very much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment