Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## Company ticker symbol using company name ##########
- ## for https://stackoverflow.com/questions/75922337 ##
- #!pip install requests_html # https://requests.readthedocs.io/projects/requests-html
- from requests_html import HTMLSession
- import pandas as pd
- #################################### FUNCTION TO APPLY ####################################
- def search_for_symbol(search_term:str, return_all=False):
- api_endpt = f'https://query1.finance.yahoo.com/v1/finance/search'
- api_url = f'{api_endpt}?q={search_term}&lang=en-US®ion=US'
- try: jData = (r:=HTMLSession().get(api_url)).json()
- except Exception as e:
- jData = {'error_message': f'{type(e)} {e}'}
- print(f'<{r.status_code} {r.reason}> from {r.url}\n{e!r}')
- if return_all: return jData
- if (jq:=jData.get('quotes')): return jq[0]['symbol'], jq[0]['shortname']
- return None, None ## could return default values instead
- ###########################################################################################
- ########################################## EXAMPLE ##########################################
- df = pd.DataFrame({'company': ['Microsoft', 'Apple', 'Amazon', 'Facebook']})
- ## if company column doesn't have duplicates [like in this case]
- # df[['symbol','shortname']] = pd.DataFrame(df['company'].apply(search_for_symbol).to_list())
- ## better for when company column has duplicates [bc calls api only once per company]
- ssDict = lambda c: dict(zip(['symbol','shortname'], search_for_symbol(c)))
- df = df.join(pd.DataFrame({cn: ssDict(cn) for cn in set(df['company'])}).T, on='company')
- print(df.to_markdown(index=False, tablefmt='fancy_grid')) ## should print:
- '''
- > ╒═══════════╤══════════╤═══════════════════════╕
- > │ company │ symbol │ shortname │
- > ╞═══════════╪══════════╪═══════════════════════╡
- > │ Microsoft │ MSFT │ Microsoft Corporation │
- > ├───────────┼──────────┼───────────────────────┤
- > │ Apple │ AAPL │ Apple Inc. │
- > ├───────────┼──────────┼───────────────────────┤
- > │ Amazon │ AMZN │ Amazon.com, Inc. │
- > ├───────────┼──────────┼───────────────────────┤
- > │ Facebook │ META │ Meta Platforms, Inc. │
- > ╘═══════════╧══════════╧═══════════════════════╛
- '''
Advertisement
Add Comment
Please, Sign In to add comment