|
| 1 | +from ftplib import FTP, all_errors |
| 2 | +from pandas import read_csv |
| 3 | +from pandas_datareader._utils import RemoteDataError |
| 4 | +from pandas.compat import StringIO |
| 5 | +import time |
| 6 | + |
| 7 | +_NASDAQ_TICKER_LOC = '/SymbolDirectory/nasdaqtraded.txt' |
| 8 | +_NASDAQ_FTP_SERVER = 'ftp.nasdaqtrader.com' |
| 9 | +_TICKER_DTYPE = [('Nasdaq Traded', bool), |
| 10 | + ('Symbol', str), |
| 11 | + ('Security Name', str), |
| 12 | + ('Listing Exchange', str), |
| 13 | + ('Market Category', str), |
| 14 | + ('ETF', bool), |
| 15 | + ('Round Lot Size', float), |
| 16 | + ('Test Issue', bool), |
| 17 | + ('Financial Status', str), |
| 18 | + ('CQS Symbol', str), |
| 19 | + ('NASDAQ Symbol', str), |
| 20 | + ('NextShares', bool)] |
| 21 | +_CATEGORICAL = ('Listing Exchange', 'Financial Status') |
| 22 | + |
| 23 | +_DELIMITER = '|' |
| 24 | +_ticker_cache = None |
| 25 | + |
| 26 | + |
| 27 | +def _bool_converter(item): |
| 28 | + return item == 'Y' |
| 29 | + |
| 30 | + |
| 31 | +def _download_nasdaq_symbols(timeout): |
| 32 | + """ |
| 33 | + @param timeout: the time to wait for the FTP connection |
| 34 | + """ |
| 35 | + try: |
| 36 | + ftp_session = FTP(_NASDAQ_FTP_SERVER, timeout=timeout) |
| 37 | + ftp_session.login() |
| 38 | + except all_errors as err: |
| 39 | + raise RemoteDataError('Error connecting to %r: $s' % |
| 40 | + (_NASDAQ_FTP_SERVER, err)) |
| 41 | + |
| 42 | + lines = [] |
| 43 | + try: |
| 44 | + ftp_session.retrlines('RETR ' +_NASDAQ_TICKER_LOC, lines.append) |
| 45 | + except all_errors as err: |
| 46 | + raise RemoteDataError('Error downloading from %r: $s' % |
| 47 | + (_NASDAQ_FTP_SERVER, err)) |
| 48 | + finally: |
| 49 | + ftp_session.close() |
| 50 | + |
| 51 | + # Sanity Checking |
| 52 | + if not lines[-1].startwith('File Creation Time:'): |
| 53 | + raise RemoteDataError('Missing expected footer. Found %r' % lines[-1]) |
| 54 | + |
| 55 | + # Convert Y/N to True/False. |
| 56 | + converter_map = dict((col, _bool_converter) for col, t in _TICKER_DTYPE |
| 57 | + if t is bool) |
| 58 | + |
| 59 | + data = read_csv(StringIO('\n'.join(lines[:-1])), '|', |
| 60 | + dtype=_TICKER_DTYPE, converters=converter_map, |
| 61 | + index_col=1) |
| 62 | + |
| 63 | + # Properly cast enumerations |
| 64 | + for cat in _CATEGORICAL: |
| 65 | + data[cat] = data[cat].astype('category') |
| 66 | + |
| 67 | + return data |
| 68 | + |
| 69 | + |
| 70 | +def get_nasdaq_symbols(retry_count=3, timeout=30, pause=None): |
| 71 | + """ |
| 72 | + Get the list of all available equity symbols from Nasdaq. |
| 73 | +
|
| 74 | + Returns |
| 75 | + ------- |
| 76 | + nasdaq_tickers : pandas.DataFrame |
| 77 | + DataFrame wiht company tickers, names, and other properties. |
| 78 | + """ |
| 79 | + if timeout < 0: |
| 80 | + raise ValueError('timeout must be >= 0, not %r' % (timeout,)) |
| 81 | + |
| 82 | + if pause is None: |
| 83 | + pause = timeout / 3 |
| 84 | + elif pause < 0: |
| 85 | + raise ValueError('pause must be >= 0, not %r' % (pause,)) |
| 86 | + |
| 87 | + global _ticker_cache |
| 88 | + if _ticker_cache is None: |
| 89 | + while retry_count > 0: |
| 90 | + try: |
| 91 | + _ticker_cache = _download_nasdaq_symbols(timeout=timeout) |
| 92 | + retry_count = -1 |
| 93 | + except Exception: |
| 94 | + # retry on any exception |
| 95 | + if retry_count == 0: |
| 96 | + raise |
| 97 | + else: |
| 98 | + retry_count -= 1 |
| 99 | + time.sleep(pause) |
| 100 | + |
| 101 | + return _ticker_cache |
0 commit comments