Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save duivesteyn/7b5f83d3807b840c6867f10631a7ada3 to your computer and use it in GitHub Desktop.
Save duivesteyn/7b5f83d3807b840c6867f10631a7ada3 to your computer and use it in GitHub Desktop.
Demonstrates Yahoo Finance Ticker Search API
#!/user/bin/env python3
# coding: utf-8
# bmd-exploring-the-yahoo-finance-stock-search-api
# bmd
# exploring the yahoo finance stock lookup API. I.e. something that will identify tickers from a search
# python code that takes an input stock ticker code (fragment), and returns the most likely result(s) for the search.
# Api exists at https://finance.yahoo.com/_finance_doubledown/api/resource/searchassist;searchTerm=WAF
# But is pretty undocumented. Seems to have been around for years (since 2019ish). Seems to give just the 10 most likely guesses
#
# 2021-07-21
#
# pre-reqs: PIL
#Imports
import sys
import requests
import pprint
import logging
logging.basicConfig(level=logging.DEBUG) #Sets up logging to stdio
#Functions
def main():
args = sys.argv[1:]
#Request search term.
tickerToSearch = input('What is your Search Term (Stock ticker/instrument?: (eg AAPL, or BHP.AX)... ')
listOfStocksThatMeetCriteria = searchStockByNameInYahoo(tickerToSearch)
pprint.pprint('\n\n')
pprint.pprint(listOfStocksThatMeetCriteria)
#Optionally Print Available items nicely!!
stocks = [item["name"] for item in listOfStocksThatMeetCriteria]
stocksSymbols = [item["symbol"] for item in listOfStocksThatMeetCriteria]
print(stocks)
print(stocksSymbols)
def searchStockByNameInYahoo(searchterm):
"""Function that Searches Yahoo for relevant stock, used in a Search for a stock. Returns a list of dictionaries with data.
returnedData = [{'exch': 'ASX',
'exchDisp': 'Australian',
'name': 'Woolworths Group Limited',
'symbol': 'WOW.AX',
'type': 'S',
'typeDisp': 'Equity'},
{'exch': 'VAN',
'exchDisp': 'CDNX',
'name': 'Wow Unlimited Media Inc.',
'symbol': 'WOW.V',
'type': 'S',
'typeDisp': 'Equity'}]
## And Its Easy to use List Comprehension to simply display the results
['Woolworths Group Limited', 'Wow Unlimited Media Inc.']
['WOW.AX', 'WOW.V']
"""
print('Looking up:', searchterm)
#Setup Request Nicely (as y! is picky)
site = "https://finance.yahoo.com/_finance_doubledown/api/resource/searchassist;searchTerm=" + searchterm
headers = {
'User-Agent' : 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/91.0.4472.80 Mobile/15E148 Safari/604.1',
'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language' : 'en-US,en;q=0.5',
'DNT' : '1', # Do Not Track Request Header
'Connection' : 'close'
}
resp = requests.get(site, headers = headers)
if not resp.ok:
raise AssertionError(resp.json())
#Get Data from JSON and return to main
data = resp.json()
if 'items' in data:
pprint.pprint(data['items'])
return data['items'] #Gather just the list of stocks!
else:
raise AssertionError(resp.json())
# Main body
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment