Try95th

search_for_ticker_symbol for so_q_75922337

Apr 3rd, 2023
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.88 KB | None | 0 0
  1. ## Company ticker symbol using company name ##########
  2. ## for https://stackoverflow.com/questions/75922337 ##
  3.  
  4. #!pip install requests_html # https://requests.readthedocs.io/projects/requests-html
  5. from requests_html import HTMLSession
  6. import pandas as pd
  7.  
  8.  
  9. #################################### FUNCTION TO APPLY ####################################
  10. def search_for_symbol(search_term:str, return_all=False):
  11.     api_endpt = f'https://query1.finance.yahoo.com/v1/finance/search'
  12.     api_url = f'{api_endpt}?q={search_term}&lang=en-US&region=US'
  13.     try: jData = (r:=HTMLSession().get(api_url)).json()
  14.     except Exception as e:
  15.         jData = {'error_message': f'{type(e)} {e}'}
  16.         print(f'<{r.status_code} {r.reason}> from {r.url}\n{e!r}')
  17.    
  18.     if return_all: return jData
  19.     if (jq:=jData.get('quotes')): return jq[0]['symbol'], jq[0]['shortname']
  20.     return None, None ## could return default values instead
  21. ###########################################################################################
  22.  
  23.  
  24.  
  25. ########################################## EXAMPLE ##########################################
  26. df = pd.DataFrame({'company': ['Microsoft', 'Apple', 'Amazon', 'Facebook']})
  27.  
  28. ## if company column doesn't have duplicates [like in this case]
  29. # df[['symbol','shortname']] = pd.DataFrame(df['company'].apply(search_for_symbol).to_list())
  30.  
  31. ## better for when company column has duplicates [bc calls api only once per company]
  32. ssDict = lambda c: dict(zip(['symbol','shortname'], search_for_symbol(c)))
  33. df = df.join(pd.DataFrame({cn: ssDict(cn) for cn in set(df['company'])}).T, on='company')
  34.  
  35. print(df.to_markdown(index=False, tablefmt='fancy_grid')) ## should print:
  36. '''
  37. >     ╒═══════════╤══════════╤═══════════════════════╕
  38. >     │ company   │ symbol   │ shortname             │
  39. >     ╞═══════════╪══════════╪═══════════════════════╡
  40. >     │ Microsoft │ MSFT     │ Microsoft Corporation │
  41. >     ├───────────┼──────────┼───────────────────────┤
  42. >     │ Apple     │ AAPL     │ Apple Inc.            │
  43. >     ├───────────┼──────────┼───────────────────────┤
  44. >     │ Amazon    │ AMZN     │ Amazon.com, Inc.      │
  45. >     ├───────────┼──────────┼───────────────────────┤
  46. >     │ Facebook  │ META     │ Meta Platforms, Inc.  │
  47. >     ╘═══════════╧══════════╧═══════════════════════╛
  48. '''
  49.  
Advertisement
Add Comment
Please, Sign In to add comment