Skip to content

Instantly share code, notes, and snippets.

@jnrbsn
Last active November 8, 2020 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnrbsn/d50854de003f5123e1e15fd40e7183b2 to your computer and use it in GitHub Desktop.
Save jnrbsn/d50854de003f5123e1e15fd40e7183b2 to your computer and use it in GitHub Desktop.
Get latest price of stocks, ETFs, mutual funds, etc.
import json
from concurrent.futures import ThreadPoolExecutor, as_completed
from urllib.parse import urlencode
from urllib.request import Request, urlopen
def get_latest_price_single(ticker):
url = f'https://query1.finance.yahoo.com/v8/finance/chart/{ticker}'
params = {
'region': 'US',
'lang': 'en-US',
'includePrePost': 'false',
'events': '',
'interval': '1d',
'range': '1d',
}
url += '?' + urlencode(params)
headers = {
'Referer': f'https://finance.yahoo.com/quote/{ticker}',
'User-Agent': (
'Mozilla/5.0 (Linux x86_64; rv:82.0) Gecko/20100101 Firefox/82.0'),
'X-Requested-With': 'XMLHttpRequest',
}
request = Request(url, headers=headers)
with urlopen(request) as response:
data = json.loads(response.read())
quote = data['chart']['result'][0]['indicators']['quote'][0]
return quote['close'][-1]
def get_latest_price_batch(*tickers):
with ThreadPoolExecutor(max_workers=len(tickers)) as executor:
future_to_ticker = {
executor.submit(get_latest_price_single, ticker): ticker
for ticker in tickers
}
prices = {}
for future in as_completed(future_to_ticker):
ticker = future_to_ticker[future]
price = future.result()
prices[ticker] = price
return prices
if __name__ == '__main__':
import time
tickers = [
'AAPL', 'MSFT', 'AMZN', 'GOOG', 'GOOGL', 'FB', 'BRK-B', 'BRK-A',
'V', 'TSLA', 'WMT', 'JNJ', 'PG', 'NVDA', 'UNH', 'JPM', 'MA',
'HD', 'VZ', 'PYPL',
]
t1 = time.time()
prices = get_latest_price_batch(*tickers)
t2 = time.time()
print(json.dumps(prices, indent=2))
print(f'Fetched {len(tickers)} prices in {t2 - t1:.3f} seconds')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment