Python – Use threading to get all EOD quote prices from all NASDAQ symbols.

The script below goes to yahoo finance and takes the current price of all stocks from NASDAQ. There is really no real life application of this script. It was created to learn threading. The script obtains the prices for thousands of stocks with in a couple of seconds at most. The output at some sections is off due to the speed the results are being printed. In order for this to work you will have to download all the symbols for the NASDAQ exchange and save that info in a text file located in the same location the script is running from.

#!/usr/bin/python
import urllib
import re
import threading
from datetime import datetime

print "------------------------------------------"
print "Today's date: ", str(datetime.now())[0:10]
print "------------------------------------------"
print ""
print "Symbol    Price      Time"

def stock_prices_reader(smbl):
    url = "http://finance.yahoo.com/q?s=" + smbl + "&ql=0"
    #print url
    html_link = urllib.urlopen(url)
    html_read = html_link.read()
    regex = '(.+?)'
    pattern = re.compile(regex)
    price = re.findall(pattern, html_read)
    print (str(smbl).center(5)), (''.join(price).center(14)), str(datetime.now())[11:25]
    print (" ----".ljust(1)), ("-----".center(14)),("--------".rjust(5))

symbolsfile = open("symbols.txt")
symbolist = symbolsfile.read()
newsymbolist = symbolist.split(("\n"))

threadlist = []
for loop1 in newsymbolist:
    thrd = threading.Thread(target=stock_prices_reader, args=(loop1,))
    thrd.start()
    threadlist.append(thrd)

for loop2 in threadlist:
    loop2.join()

Share Button