Python Script to fetch Live Stock Quotes from Google Finance

I hope you have already installed Python in your system and tested the execution of simple statements. If not, please go through the first part of this tutorial series right here. Now, let’s write a python script to fetch live stock quotes from Google finance. We would explore two different methods to fetch live stock quotes. First one uses googlefinance api, and the next uses web scraping.

Prerequisites

You would need to install googlefinance module to execute this script.

Open command prompt and copy past the below command to install GoogleFinance module

pip install googlefinance

The installation wouldn’t take more than 30 seconds depending on your internet speed.

GoogleFinanceAPI

Python Script to fetch Live Stock Quotes

Below is the simple python script to fetch live stock quotes.

from googlefinance import getQuotes
import time
import json
import os
import sys

def fetchstockquotes(symbol):
    while True:
        os.system('cls' if os.name=='nt' else 'clear')
        print json.dumps(getQuotes(symbol), indent=2)
        time.sleep(5)

symbol=sys.argv[1]
fetchstockquotes(symbol)

Copy this script, paste it in notepad and save as “FetchStockQuotes.py” in your working directory. Now open command prompt again, and goto your working directory path. Use below command to open Jupyter notebook:

jupyter notebook

Once the notebook is open in your web browser, goto New–>Python2, it will open up the editor where you can execute python statements and scripts. Type the below command to execute your script.

run FetchStockQuotes.py NSE:NIFTY

Here, NSE:NIFTY refers to the stock name you want to fetch data for. You can replace it with any other symbol using “EXCHANGE_NAME : SYMBOL_NAME” format.

You would see live stock quotes refreshing every 5 seconds once the script is executed.

Python Script to fetch Live Stock Quotes

Now, let’s understand the code logic and see how it works

The first few import statement are the necessary built-in modules to execute this script. You can see that we have also imported the googlefinance module installed in the first step.

Next, there is a function definition which takes a single argument “symbol”. The symbol name is passed as a command line argument during script execution. There is a infinite While loop in the function which uses getQuotes function to print the stock data. There is a time delay of 5 seconds between each loop.

See below another script to do the same:

import urllib
import re
import time
import sys

def fetchstockquotes(symbol):
    base_url = 'http://finance.google.com/finance?q='
    content = urllib.urlopen(base_url + symbol).read()
    m = re.search('id="ref_(.*?)">(.*?)<', content)
    if m:
        quote = m.group(2)
    else:
        quote = 'no quote available for: ' + symbol
    return quote

symbol=sys.argv[1]
while True:
    print
    print str(time.ctime())+ " - " + symbol+ " - " + fetchstockquotes(symbol)
    time.sleep(5)


This script uses web scraping to fetch the real-time stock price from Google finance website. Its output is the live closing price with time.

Python Stock Quotes

Here we complete our first exercise to start Algorithmic trading using Python. Let us know if you have any questions.

8 Comments

  1. sir
    on copying the pip install google finance, i got following message. “pip is not recognised as an internal or external command

  2. hi sir i am new to algo trading can you share how to handle time series data using Python packages like NumPy & Pandas. Backtesting strategies using Pythonan how extract data from Google/Yahoo, backtest strategies, analyse results, plot equity curves

  3. Hi Sir ,
    One Sincere request . I am trying to code OHLC(30min ) strategy for 3-4 stocks . I am aware that we can save the symbols in a list . Could you please create a tutorial or refer me where i can get thi strategy . I want to place order when 30 min High low is breached .

    Please sir help me in this .

Leave a Reply

Your email address will not be published. Required fields are marked *