#!/usr/bin/python
# Copywrite (c) 2004 Randy Gamage
# Program to fetch stock prices daily, and store them for later trending
# References the following files:
# NOTE: Need to create a directory called 'stockdata' to hold all the data output files
# READS: stocklist.txt : list of stock ticker symbols to fetch
# Example file: stocklist.txt
# EMHSX
# MCBAX
# MBBAX
# MBFGX
# MBSPX
# PQNBX
# PTLBX
# 
# WRITES: ./stockdata/YYYYMMDD.txt : list of paired values (ticker symbol, price) for a given day
# Example file: 20042405.txt
# EMHSX,10.85
# MCBAX,28.91
# MBBAX,29.54
# MBFGX,14.46
# MBSPX,22.85
# PQNBX,21.55
# PTLBX,10.17
# 
import httplib, urllib
from string import *
import time
import os

def Today():
    # Returns today's date, in the form YYYYMMDD  
    lt = time.localtime()
    return '%02d%02d%02d' % (lt[0],lt[1],lt[2])

#os.chdir(os.environ['userprofile'] + '\\My Documents\\python source')

fIN = open('stocklist2.txt','rb')
stocklist = fIN.readlines()
fIN.close
fOUT = open('./stockdata/' + Today()+'.txt','w')
conn = httplib.HTTPConnection("quote.yahoo.com")
for tickersymbol in stocklist:
    # strip any extra parameters after each tickersymbol
    if ',' in tickersymbol:
        tickersymbol = strip(tickersymbol[:string.find(tickersymbol,',')])
    else:
        tickersymbol = strip(tickersymbol)
    params = urllib.urlencode({'s': tickersymbol, 'f': 'sl1', 'e': '.csv'})
    headers = {"Content-type": "application/x-www-form-urlencoded",
           "Accept": "text/plain"}
    conn.request("POST", "/d/quotes.csv", params, headers)
    response = conn.getresponse()
    data = response.read()
    quote1 = strip(data[find(data,',')+1:])
    #print tickersymbol + ',' + quote1
    fOUT.write(tickersymbol + ',' + quote1 + '\n')
conn.close()
fOUT.close