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.
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.
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.
Here we complete our first exercise to start Algorithmic trading using Python. Let us know if you have any questions.
sir
on copying the pip install google finance, i got following message. “pip is not recognised as an internal or external command
Hi,
You need to correctly setup PYTHONPATH environment variable in your OS. Refer the below article:
https://tradingtuitions.com/algorithmic-trading-using-python-introduction-and-setup/
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
Hi Rahul,
We will cover all these in the upcoming posts.
sir is it possible to upload videos??
is there something available for yahoo for EOD atleast?
Hi Raghu,
For EOD, I would recommend NSE Bhavcopy instead of Yahoo.
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 .
when i am running a code its getting like no quote availabe. pls check
# -*- coding: utf-8 -*-
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[0]
while True:
print
print str(time.ctime())+ " – " + symbol+ " – " + fetchstockquotes(symbol)
time.sleep(5)
ths is the script..i am running in spider.
hu Dec 07 17:24:49 2017 – C:/Users/Chethu/Desktop/7.py – no quote available for: C:/Users/Chethu/Desktop/7.py
this s the output
please help to get live market values for any stocks
Liked it, Works. I was able to test for NYSE and Nasdaq stocks as well. Thanks.
Thanks for your kind words Shahsi!
m = re.search(‘data-last-price=\”(.+?)\”‘, content)
This is latest regex(10th Aug 2021) which will pickup corrcet price