Downloading Stock Market Data via Yahoo using Python
"""
In my spare time, I'm an investor. I figure I should
should use my powers in math and computer science and
help build for myself a better future.
This program will download the past year's stock
history for a list of ticker symbols defined by the
'symbols' list variable. Each stock's data will be
downloaded to your computer into a CSV file, which
can easily be viewed with Microsoft Excel.
Tomorrow's post will be a program on how to read the
output files using the popular statistical computing
software R.
"""
import urllib
from datetime import date
symbols = [ "BAC", "YHOO", "RIMM", "MU", "MSFT", "GOOG", "PFE", "INTC", "C", "GE", "SAP", "YUM", "CLRT", "ORCL", "AMZN", "XTXI", "GS", "KO", "F", "PG", "EMR", "AAPL", "KFT", "NFLX", "CPNO", "BIG", "FTR"]
def download(url, outfile):
webFile = urllib.urlopen(url)
localFile = open(outfile, 'w')
localFile.write(webFile.read())
webFile.close()
localFile.close()
def get1YearPriceHistory(symbol):
today = date.today()
url = "http://ichart.finance.yahoo.com/table.csv?s=%s&a=%02d&b=%02d&c=%04d&d=%02d&e=%02d&f=%04d&g=d&ignore=.csv" % \
(symbol, today.month - 1, today.day, today.year - 1, today.month - 1, today.day, today.year)
outfile = symbol + ".csv"
download(url, outfile)
if __name__ == '__main__':
for s in symbols:
get1YearPriceHistory(s)