Searching for Google stock quote

If the stock quote of any company is of interest to you, this recipe can help you to find today's stock quote of that company.

Getting ready

We assume that you already know the symbol used by your favorite company to enlist itself on any stock exchange. If you don't know, get the symbol from the company website or just search in Google.

How to do it...

Here, we use Google Finance (http://finance.google.com/) to search for the stock quote of a given company. You can input the symbol via the command line, as shown in the next code.

Listing 6.4 describes how to search for Google stock quote, as shown:

#!/usr/bin/env python
# Python Network Programming Cookbook -- Chapter - 6
# This program is optimized for Python 2.7.
# It may run on any other version with/without modifications. 

import argparse
import urllib
import re
from datetime import datetime

SEARCH_URL = 'http://finance.google.com/finance?q='
 
def get_quote(symbol):
  content = urllib.urlopen(SEARCH_URL + symbol).read()
  m = re.search('id="ref_694653_l".*?>(.*?)<', content)
  if m:
    quote = m.group(1)
  else:
    quote = 'No quote available for: ' + symbol
  return quote

if __name__ == '__main__':
  parser = argparse.ArgumentParser(description='Stock quote 
search')
  parser.add_argument('--symbol', action="store", dest="symbol", 
required=True)
  given_args = parser.parse_args() 
  print "Searching stock quote for symbol '%s'" %given_args.symbol 
  print "Stock  quote for %s at %s: %s" %(given_args.symbol , 
datetime.today(),  get_quote(given_args.symbol))

If you run this script, you will see an output similar to the following. Here, the stock quote for Google is searched by inputting the symbol goog, as shown:

$ python 6_4_google_stock_quote.py --symbol=goog 
Searching stock quote for symbol 'goog' 
Stock quote for goog at 2013-08-20 18:50:29.483380: 868.86 

How it works...

This recipe uses the urlopen() function of urllib to get the stock data from the Google Finance website.

By using the regular expression library re, it locates the stock quote data in the first group of items. The search() function of re is powerful enough to search the content and filter the ID data of that particular company.

Using this recipe, we searched for the stock quote of Google, which was 868.86 on August 20, 2013.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.97.216