Getting a list of stock symbols with Python

Lists of stock symbols can be found at either of these links:


You can download a list of symbols from the nasdaq.com site for the Nasdaq, NYSE, and AMEX exchanges.

The FTP directory at ftp.nasdaqtrader.com gets updated every night at 3:00AM (symbols can change). Here is a quick Python script to download the nasdaqlisted.txt and otherlisted.txt files from the ftp site:


#!/usr/bin/python

# typical use: python get_symbols.py > symbols.txt

import urllib

def get_data( url ):
    data = urllib.urlopen( url )
    lines = []
    for line in data:
        lines.append( line.rstrip().split('|') )
    return lines


url = 'ftp://ftp.nasdaqtrader.com/SymbolDirectory/'
files = ['nasdaqlisted.txt', 'otherlisted.txt']

for f in files:
    print get_data( url + f )


List Comprehensions in Python

# create a new list
>>> a = [1,2,3,4,5]
>>> a [1, 2, 3, 4, 5]

# sample list comprehension expression; equivalent to b = a
>>> b = [a[i] for i in range(len(a))]
>>> b [1, 2, 3, 4, 5]

# only even indices
>>> b = [a[i] for i in range(len(a)) if i % 2 == 0]
>>> b [1, 3, 5]

# only even indices and conditionally modifies the value of a[i] 
>>> b = [a[i]*2 if i > 1 else a[i] for i in range(len(a)) if i % 2 == 0]
>>> b [1, 6, 10]