#!/usr/bin/python

# Dead. Yahoo has dismantled
# all the free quote services they
# had for years and years. So this doesn't work anymore.

# Edit the url to suit your quote needs.
# Output is a CSV file.

import requests
import sys
import datetime

u='http://download.finance.yahoo.com/d/quotes.csv?s=^GSPC+^IXIC+^VIX+AGG+BSV+DIA&f=sl1d1t1c1ohgv&e=.csv'

symdata=[]
navdata=[]
datedata=[]
now = datetime.datetime.now()
outfile = open('/home/wsanders/'+now.strftime("%Y-%m-%d.csv"), 'w')
dow = now.weekday()     #     Friday is 4
r = requests.get(u)
if r.status_code != 200:
    print "HTTP error:", r
t = r.text.decode()
for l in t.split("\n"):
    #print l
    l = l.replace('"','')
    try:
        (sym, nav, day, time, junk) = l.split(",", 4)
        m,d,y = (int(s) for s in day.split('/'))
        try:
            # date object
            navdate = datetime.datetime(y, m, d)
        except:
            sys.stderr.write('Badly formatted date in ' + l)
            sys.exit()
        if (now - navdate).days > 0 and dow in (1,2,3,4):
            print sym, "is not checked in yet"
        if (now - navdate).days > 3:
            print sym, "is stale"
        symdata.append(sym)
        navdata.append(nav)
        datedata.append(navdate.strftime('%x'))
    except:
        print "blank line"

outfile.write(",")
outfile.write( ','.join(symdata) )
outfile.write("\n,")
outfile.write( ','.join(navdata) )
# not really necessary as trailing zeros will be removed by LO
# outfile.write( ','.join(format(float(x),".2f") for x in navdata) )
outfile.write("\n,")
outfile.write( ','.join(datedata) )
outfile.write("\n")
outfile.close
