Skip to content

Instantly share code, notes, and snippets.

@m-manu
Last active November 21, 2017 07:56
Show Gist options
  • Save m-manu/6411582 to your computer and use it in GitHub Desktop.
Save m-manu/6411582 to your computer and use it in GitHub Desktop.
Command-line utility to get stock price from Nasdaq and display it in INR (or any other currency). This script is created only for academic purpose. Please check terms and conditions Yahoo! Finance and Google Finance APIs before using this.
#!/usr/bin/python
'''
Command-line script to get stock price (in USD and local currency)
Prerequisite:
Python 2.7
Installation:
Copy this script to /usr/bin or /bin.
Usage:
$ stock ZNGA
This will get you stock price for company with stock symbol 'ZNGA'
$ stock ZNGA FB
Multi-call. This will get you stock prices for companies with stock symbols 'ZNGA' and 'FB' in one call
'''
LOCAL_CURRENCY = "INR"
import sys, urllib2
try:
import json
except ImportError:
import simplejson as json
from csv import reader as csvreader
from StringIO import StringIO
from multiprocessing import Process, Queue
GOOGLE_FINANCE_API_URL = "http://finance.google.com/finance/info?client=ig&q=%s"
YAHOO_FINANCE_CURRENCY_API_URL = "http://download.finance.yahoo.com/d/quotes.csv?s=USD%s=X&f=snl1d1t1ab" % LOCAL_CURRENCY
usdQ = Queue()
stocksQ = Queue()
def getUsdPrice():
'''Get exchange rate with USD from Yahoo Finance'''
uh_currency_ex = urllib2.urlopen(YAHOO_FINANCE_CURRENCY_API_URL)
currency_ex_csv = uh_currency_ex.read()
f = StringIO(currency_ex_csv)
reader = csvreader(f)
currency_details = reader.next()
askPrice = (float)(currency_details[6])
usdQ.put(askPrice)
def getStockQuotes(symbols):
'''Get stock price from Google Finance'''
uh = urllib2.urlopen(GOOGLE_FINANCE_API_URL % symbols)
output_str_raw = uh.read()
output_str = output_str_raw.replace("\n// ", "")
stocksObj = json.loads(output_str)
stocksDetails = []
for stock in stocksObj:
stocksDetails.append({'symbol':str(stock.get('t')), 'price':float(stock.get('l')), 'change':str(stock.get('c')), 'change_percent': float(stock.get('cp'))})
stocksQ.put(stocksDetails)
if __name__ == "__main__":
try:
cmdargs = sys.argv
if len(cmdargs)>1:
currconvChildProcess = Process(target=getUsdPrice)
currconvChildProcess.start()
cmdargs.pop(0)
symbols = ",".join(cmdargs)
stockpriceChildProcess = Process(target=getStockQuotes, args=(symbols,))
stockpriceChildProcess.start()
usdPrice = usdQ.get()
stocks = stocksQ.get()
for stock in stocks:
print "% 4s: % 7.2f %s (%+.2f%%) [%.2f in %s]" % (stock['symbol'], stock['price'], stock['change'], stock['change_percent'], usdPrice*stock['price'], LOCAL_CURRENCY)
stockpriceChildProcess.join()
currconvChildProcess.join()
else:
print >> sys.stderr, "Error: Not enough arguments. Pass stock symbol(s) as command line parameter(s)."
except (urllib2.HTTPError, urllib2.URLError) as e:
print >> sys.stderr, e
except ValueError as e:
print >> sys.stderr, "Value Error: (%s)" % str(e)
except:
print "Unexpected error: ", sys.exc_info()[0]
@anoop-v-mathew
Copy link

Very useful!

To use the query for Indian stocks on NSE, you need to precede the NSE stock code with NSE:. For eg., for Infosys, whose NSE code is INFY the query to use is :-

http://finance.google.com/finance/info?client=ig&q=NSE:INFY

For query on stocks on Bombay stock exchange, which has a numeric stock code, the prefix is BOM. For Infosys, the query to use is:-

http://finance.google.com/finance/info?client=ig&q=BOM:500209

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment