Making/download a csv file with python
Question: I want to make a CSV with the Closed values of stocks, by downloading them
from Yahoo Finance using python 2.7 on Windows. The file is call "Historical
Prices". I have the tickers in a list and i want to know if I can make a csv
file with the closed values in a row. For example:

    
    
    AAPL,109,87,110.06,
    GOOG,2123.546,213,56,
    

(and so on)

So far my script is this:

    
    
    import urllib2
    import csv
    
    nasdaqlisted = urllib2.urlopen("ftp://ftp.nasdaqtrader.com/SymbolDirectory/nasdaqlisted.txt")
    raw = nasdaqlisted.read().split("\r\n")
    del raw[0]
    del raw[-1]
    
    tickerslist = []
    for l in raw:
        linea = l.split("|")
        tickerslist.append(linea[0])
    del tickerslist[-1]
    
    def closed(tickerslist):
        url = urllib2.urlopen("http://real-chart.finance.yahoo.com/table.csv?s=" +tickerslist+ "&d=8&e=13&f=2014&g=d&a=11&b=12&c=1980&ignore=.csv")
        raw = url.read().split("\r\n")
        del raw[0]
        del raw[-1]
    
    closed_us = open("closed-us.csv","w")
    
    for i in tickerslist:
        cierres.write(closed(i))
    closed_us.close()
    

Thank you very much!

P.D.: I found a this question. It may help you [Download a .csv file with
Python](http://stackoverflow.com/questions/21500918/download-a-csv-file-with-
python) but I doesn't work saying that is because "request" can not be be
import (I guess is because I use python 2.7 instead of 3.3)


Answer: Everything you have looks good. For CSV file, generally, it's simple enough
just to write a normal text files an put commas where needed - no need for
anything fansy. In your example:

    
    
    def closed(tickerslist):
        returnLine = tickerslist
        url = urllib2.urlopen("http://real-chart.finance.yahoo.com/table.csv?s=" +tickerslist+ "&d=8&e=13&f=2014&g=d&a=11&b=12&c=1980&ignore=.csv")
        raw = url.read().split("\r\n")[1:-1]
        # if you wanted to grab the last number on each line...
        for line in raw:
            returnLine += ','+line[line.rfind(',')+1:])
        return returnLine+'\n'
    

If you're interested in only a small portion of a file, the 'read' method has
an optional parameter for bytes to read. So you don't have to download the
whole file to find something at the beginning. This parameter is also helpful
if you wanted to download a larger file in a separate thread and update the
main thread (usually a gui) about the progress.

Hope this helps.

