from datetime import datetime
import requests
import csv
import os
import sys
import time


os.chdir(sys.argv[1])
ticker_f = open(sys.argv[2], "rb")
ticker_reader = csv.reader(ticker_f)
tickers = [r[0] for r in ticker_reader][1:]
ticker_f.close()
tln = len(tickers)


t_1 = datetime.now()
for i, t in enumerate(tickers):
    resp = requests.get("https://www.quandl.com/api/v1/datasets/%s.csv?auth_token=%s" % (t, sys.argv[3]))
    output_f = open("%s.csv" % t.split("/")[1], "wb")
    output_f.write(resp.text)
    output_f.close()
    print i * 100. / tln, datetime.now() - t_1
    time.sleep(1)
