Last active
March 11, 2023 18:16
-
-
Save shner-elmo/47f5776e4a9ee7473f81ef8a09fb361e to your computer and use it in GitHub Desktop.
A simple function that uses TradingView's API to get all the stock symbols in the US stock market, and you can filter them by exchange.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import annotations | |
import requests | |
def get_all_symbols(exchanges: set[str]) -> list[str]: | |
""" | |
Get a list with all the symbols filtered by a given exchange. | |
Valid exchanges: {'AMEX', 'OTC', 'NYSE', 'NASDAQ'} | |
:param exchanges: a set which contains the exchanges you want to keep (all the rest will be ignored) | |
:return: list of symbols | |
""" | |
exchanges = {x.upper() for x in exchanges} | |
r = requests.get('https://scanner.tradingview.com/america/scan') | |
data = r.json()['data'] # [{'s': 'NYSE:HKD', 'd': []}, {'s': 'NASDAQ:ALTY', 'd': []}...] | |
symbols = [] | |
for dct in data: | |
exchange, symbol = dct['s'].split(':') | |
if exchange in exchanges: | |
symbols.append(symbol) | |
return symbols | |
# examples: | |
symbols = get_all_symbols(exchanges={'AMEX', 'OTC', 'NYSE', 'NASDAQ'}) | |
print(len(symbols), symbols[:10]) # out: 18528 ['EFHT', 'SWSDF', 'CHKR', 'MGUY', 'VHC', 'PWCDF', 'LUGDF', 'ABEQ', 'LL', 'HCBN'] | |
symbols = get_all_symbols(exchanges={'NYSE', 'NASDAQ'}) | |
print(len(symbols), symbols[:10]) # out: 7768 ['VNT', 'LXP/PC', 'USB/PR', 'NOVVU', 'RITM', 'PSTG', 'SMSI', 'MAQC', 'NX', 'TNC'] | |
symbols = get_all_symbols(exchanges={'AMEX', 'NYSE', 'NASDAQ'}) | |
print(len(symbols), symbols[:10]) # out: 10648 ['SDHY', 'CNK', 'WWW', 'HOLX', 'IBTD', 'JZRO', 'FUNC', 'SECO', 'PXSAP', 'PCT'] | |
symbols = get_all_symbols(exchanges={'NASDAQ'}) | |
print(len(symbols), symbols[:10]) # out: 4633 ['IGMS', 'HAIAU', 'VMGA', 'TRMK', 'LGIH', 'VCIT', 'PAA', 'INTU', 'MOBQ', 'RAYA'] | |
symbols = get_all_symbols(exchanges={'NYSE'}) | |
print(len(symbols), symbols[:10]) # out: 3135 ['HL', 'OTIS', 'BHR/PB', 'NGG', 'COHR', 'SOS', 'SKT', 'STET.U', 'NVST', 'EVRI'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment