import random
import csv
import urllib2

class RandomStockTickers():

    def __init__(self, number_of_stocks):
        self.number_of_stocks = number_of_stocks

    #Fetches CSV from a specified URL and converts its contents to a list
    def get_list_csv_from_url(self, url):
        response = urllib2.urlopen(url)
        document = csv.reader(response)
        rows = list(document)
        return rows

    #Creates URLs used for NASDAQ's REST API, fetches CSVs, then combines them into one list
    def get_combined_stock_symbols_from_nasdaq_nyse_amex(self):
        tickers_table = []
        url_list = []
        exchange_names_strings_list = ["nasdaq","nyse","amex"]
        for name in exchange_names_strings_list:
            exchange_tickers_url = "http://www.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=" + \
            name + "&render=download"
            url_list.append(exchange_tickers_url)
        for url in url_list:
            tickers = self.get_list_csv_from_url(url)
            for i in range(1, len(tickers)):
                tickers_table.append(tickers[i])
        return tickers_table

    #Returns a specific number of stocks that are randomly picked from the combined list of stock tickers
    def get_random_stock_tickers(self):
        random_stock_tickers = []
        number_of_stocks = self.number_of_stocks
        combined_stock_symbols = self.get_combined_stock_symbols_from_nasdaq_nyse_amex()
        row_count = len(combined_stock_symbols)
        for i in range(0, number_of_stocks):
            random_stock_row = random.randrange(0, row_count - 1)
            random_stock_tickers.append(combined_stock_symbols[random_stock_row][0])
        return random_stock_tickers
