#!/usr/bin/python
"""
Really basic thing for fetching stock quotes from
Google's "secret" stock quote API.

Give it a symbol, it returns a dict.

"""
from __future__ import unicode_literals

__author__  = 'Michael Stella <googlequote@thismetalsky.org>'
__license__ = "Apache 2.0"
__version__ = "0.1"

import re, sys, urllib2
from xml.dom import minidom

def quote(symbol):
    """Gets a stock quote, given the ticker symbol (str or unicode).
    Returns a dict of interesting information.
    """

    QUOTE_URL = 'http://www.google.com/ig/api?stock={symbol}'
    url = QUOTE_URL.format(symbol=symbol)
    handler = urllib2.urlopen(url)
    content_type = handler.info().dict['content-type']

    charset = re.search('charset\=(.*)',content_type).group(1)
    if not charset:
        charset = 'utf-8'
    if charset.lower() != 'utf-8':
        xml_response = handler.read().decode(charset).encode('utf-8')
    else:
        xml_response = handler.read()

    dom = minidom.parseString(xml_response)
    handler.close()

    quote_data = {}
    quote_dom = dom.getElementsByTagName('finance')[0]

    interesting_tags = (
        'symbol', 'company', 'exchange', 'currency',
        'last','high','low','volume','avg_volume','market_cap','open',
        'y_close','change','perc_change',
        'chart_url','symbol_url',
    )

    for tag in interesting_tags:
        try:
            quote_data[tag] =  quote_dom.getElementsByTagName(tag)[0].getAttribute('data')
        except IndexError:
            pass

    return quote_data


if __name__ == '__main__':
    if len(sys.argv) > 1:
        print quote(sys.argv[1])
    else:
        print "googlequote.py [symbol]"

"""
Copyright 2011 Michael Stella

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""


