C# Code, Tutorials and Full Visual Studio Projects

Google Stock API

Posted by on Dec 31, 2010 in API, Financial, Tutorials | 45 comments

Google Stock API

It’s not very well known and Google has no support or docs for it, but there is an elusive Google Stock API. Like most of Google’s API’s it’s REST based. (I wish all API’s were, as I hate SOAP)






The API will give you the following:

  • Stock Symbol
  • Company Name
  • Exchange
  • Exchange Timezone
  • Exchange UTC Offset
  • Exchange Closing
  • Divisor? (I assume this is the number of decimals)
  • Currency
  • Last
  • High
  • Low
  • Volume
  • AVG Volume
  • Market Cap
  • Open
  • Yesterdays Close
  • Change
  • Percent Change
  • Delay
  • Trade Timestamp
  • Trade Date (in UTC)
  • Trade Time (in UTC)
  • Current Date (in UTC)
  • Current Time (in UTC)
  • Link to Google Finance for this stock
  • Link to Google Finance for this stocks chart
  • Daylight Savings Flag


API Url Formatting

The API is very simple. It only has a single parameter that accepts a stock ticker.
http://www.google.com/ig/api?stock=MY_STOCK_TICKER_GOES_HERE

Here’s an example:
http://www.google.com/ig/api?stock=AAPL

It should return:

<?xml version="1.0"?>
<xml_api_reply version="1">
	<finance module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0" >
		<symbol data="AAPL"/>
		<pretty_symbol data="AAPL"/>
		<symbol_lookup_url data="/finance?client=ig&amp;q=AAPL"/>
		<company data="Apple Inc."/>
		<exchange data="Nasdaq"/>
		<exchange_timezone data="ET"/>
		<exchange_utc_offset data="+05:00"/>
		<exchange_closing data="960"/>
		<divisor data="2"/>
		<currency data="USD"/>
		<last data="321.90"/>
		<high data="323.48"/>
		<low data="321.33"/>
		<volume data="3753391"/>
		<avg_volume data="12682"/>
		<market_cap data="295281.14"/>
		<open data="323.00"/>
		<y_close data="323.66"/>
		<change data="-1.76"/>
		<perc_change data="-0.54"/>
		<delay data="0"/>
		<trade_timestamp data="54 seconds ago"/>
		<trade_date_utc data="20101231"/>
		<trade_time_utc data="184724"/>
		<current_date_utc data="20101231"/>
		<current_time_utc data="184818"/>
		<symbol_url data="/finance?client=ig&amp;q=AAPL"/>
		<chart_url data="/finance/chart?q=NASDAQ:AAPL&amp;tlf=12"/>
		<disclaimer_url data="/help/stock_disclaimer.html"/>
		<ecn_url data=""/>
		<isld_last data="323.00"/>
		<isld_trade_date_utc data="20101231"/>
		<isld_trade_time_utc data="143001"/>
		<brut_last data=""/>
		<brut_trade_date_utc data=""/>
		<brut_trade_time_utc data=""/>
		<daylight_savings data="false"/>
	</finance>
</xml_api_reply>

As you can see it’s nice simple XML, very well formated, so it’s makes getting the data out a snap.


Getting Multiple Stock Symbols

You can get multiple stock symbols at once by repeating the stock parameter in the url. (thanks to Patrick Fisher (see comments))
Here is an example of the response Google finance returns:

<?xml version="1.0"?>
<xml_api_reply version="1">
	<finance module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0" >
		<symbol data="AAPL"/>
		<pretty_symbol data="AAPL"/>
		<symbol_lookup_url data="/finance?client=ig&amp;q=AAPL"/>
		<company data="Apple Inc."/>
		<exchange data="Nasdaq"/>
		<exchange_timezone data="ET"/>
		<exchange_utc_offset data="+05:00"/>
		<exchange_closing data="960"/>
		<divisor data="2"/>
		<currency data="USD"/>
		<last data="572.29"/>
		<high data="573.99"/>
		<low data="560.85"/>
		<volume data="9565857"/>
		<avg_volume data="25140"/>
		<market_cap data="535126.61"/>
		<open data="563.70"/>
		<y_close data="568.18"/>
		<change data="+4.11"/>
		<perc_change data="0.72"/>
		<delay data="0"/>
		<trade_timestamp data="40 seconds ago"/>
		<trade_date_utc data="20120509"/>
		<trade_time_utc data="161528"/>
		<current_date_utc data="20120509"/>
		<current_time_utc data="161608"/>
		<symbol_url data="/finance?client=ig&amp;q=AAPL"/>
		<chart_url data="/finance/chart?q=NASDAQ:AAPL&amp;tlf=12"/>
		<disclaimer_url data="/help/stock_disclaimer.html"/>
		<ecn_url data=""/>
		<isld_last data=""/>
		<isld_trade_date_utc data=""/>
		<isld_trade_time_utc data=""/>
		<brut_last data=""/>
		<brut_trade_date_utc data=""/>
		<brut_trade_time_utc data=""/>
		<daylight_savings data="true"/>
	</finance>
	<finance module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0" >
		<symbol data="GOOG"/>
		<pretty_symbol data="GOOG"/>
		<symbol_lookup_url data="/finance?client=ig&amp;q=GOOG"/>
		<company data="Google Inc"/>
		<exchange data="Nasdaq"/>
		<exchange_timezone data="ET"/>
		<exchange_utc_offset data="+05:00"/>
		<exchange_closing data="960"/>
		<divisor data="2"/>
		<currency data="USD"/>
		<last data="611.91"/>
		<high data="614.09"/>
		<low data="601.81"/>
		<volume data="1271157"/>
		<avg_volume data="2668"/>
		<market_cap data="199486.59"/>
		<open data="606.82"/>
		<y_close data="612.79"/>
		<change data="-0.88"/>
		<perc_change data="-0.14"/>
		<delay data="0"/>
		<trade_timestamp data="1 minute ago"/>
		<trade_date_utc data="20120509"/>
		<trade_time_utc data="161455"/>
		<current_date_utc data="20120509"/>
		<current_time_utc data="161608"/>
		<symbol_url data="/finance?client=ig&amp;q=GOOG"/>
		<chart_url data="/finance/chart?q=NASDAQ:GOOG&amp;tlf=12"/>
		<disclaimer_url data="/help/stock_disclaimer.html"/>
		<ecn_url data=""/>
		<isld_last data=""/>
		<isld_trade_date_utc data=""/>
		<isld_trade_time_utc data=""/>
		<brut_last data=""/>
		<brut_trade_date_utc data=""/>
		<brut_trade_time_utc data=""/>
		<daylight_savings data="true"/>
	</finance>
</xml_api_reply>

http://www.google.com/ig/api?stock=MY_FIRST_SYMBOL&stock=MY_SECOND_SYMBOL
Example: http://www.google.com/ig/api?stock=AAPL&stock=GOOG


ASP.NET Example

Here is a quick example of using the Google Stock API with your ASP.NET C# apps. This example has only a single page and a quick form. You enter the stock symbol into the box and click the button and it will return the details via the Google Stock API.

Default.aspx ASP.NET Code

<%@ Page Title="Home Page" Language="C#"  AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="GoogleStockApi.Default" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="getQuote" runat="server">
        <h1>Stock Quote Service</h1>

        <asp:Label Text="Enter a symbol to lookup:" />
        <asp:TextBox id="symbol" runat="server" />
        <asp:Button Text="Get Quote" runat="server" />

        <div>Company: <%=Company %></div>
        <div>Company: <%=Exchange %></div>        
        <div>High: <%=High %></div>
        <div>Low: <%=Low %></div>
        <div>Last: <%=Last %></div>
    </form>
</body>
</html>

Default.aspx.cs C# Code

using System;
using System.Web.UI;
using System.Xml.Linq;

namespace GoogleStockApi
{
    public partial class Default : Page
    {
        public string Company { get; set; }
        public string Exchange { get; set; }
        public double Last { get; set; }
        public double High { get; set; }
        public double Low { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Form["symbol"] != null)
            {
                string symbol = Request.Form["symbol"];
                FetchQuote(symbol);
            }
        }

        private void FetchQuote(string symbol)
        {
            string url = "http://www.google.com/ig/api?stock=" + Server.UrlEncode(symbol);
            XDocument doc = XDocument.Load(url);
            Company = GetData(doc, "company");
            Exchange = GetData(doc, "exchange");
            Last = Convert.ToDouble(GetData(doc, "last"));
            High = Convert.ToDouble(GetData(doc, "high"));
            Low = Convert.ToDouble(GetData(doc, "low"));
        }

        private string GetData(XDocument doc, string name)
        {
            return doc.Root.Element("finance").Element(name).Attribute("data").Value;
        }
    }
}


45 Comments

Join the conversation and post a comment.

  1. Dean

    Thanks for this, very helpful. I was looking at easy ways to use Google’s Finance API!

  2. Shantaram

    Very helpful info. thanks a lot

  3. Dimitry

    Thanks, simple, and useful!

  4. Patrick Fisher

    You can get multiple records at a time like so:

    http://www.google.com/ig/api?stock=AAPL&stock=GOOG

  5. Anmol Kumar

    Hi,

    I was looking for this only. But How can I get stock list of an exchange?

    In Query string how can I pass exchange name?

    Please suggest.

    Regards,
    Anmol Kumar
    kr.anmol@gmail.com

  6. Suchigeorge

    Hi,

    Could you guide , how i can retrieve the AAPL stock details using google in PHP.

    Thank you

  7. Krishnapratap Vedula

    Hello Kelias,

    1. I want to retrieve NSE 50 stocks data from Google Finance in my ASP.NET Web Service & use it in Silverlight 4 Ticker made by me. Till now am using Yahoo Finance data but it is delayed & many times retrieves data as zero which is not possible.

    2. I want to retrieve World Indices from Google Finance.

    3. How can I retrieve Nifty 50 & World Indices data as Web Service in ASP.NET 4 & Silverlight 4?

    Kindly, help me with it. I tried to retrieve stock details with this URL http://www.google.com/ig/api?stock=NSE:ACC but nor showing any data in XML while this URL http://www.google.com/finance?q=NSE%3AACC%2C+NSE%3ABHEL shows data on the page but don’t know how to retrieve it in ASP.NET 4 & Silverlight 4 web app. Thanks.

    Best Regards,
    Krishnapratap Vedula

  8. Nathan

    Thanks so much for this, very helpful for some jquery I was working on!

  9. E||C0DE

    does this give you real time data?

  10. kelias

    That depends on the equity your looking for and where the Google got the data. Take a look at Google Finance Market Data Disclaimer for more info.

  11. mambajoe

    hi. good info.
    You can get the same kind of xml from yahoo but with much more information.
    try this:
    http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20%28%22bdt.l%22%29&diagnostics=false&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys.

    they pulled the info out of the yahoo api (you can not find it documented anymore)
    was just lucky to get it a couple of weeks before.

  12. mambajoe

    you can change the bdt.l (it’s a symbol that will work with google finance but not with yahoo finance) to any other you may like.
    aapl, msft,…. what ever

  13. Peter

    How to use jsp and servlet to rewrite this program?

  14. Harsh

    Hi, first of all thanks for such a wonderful article here. It is so simple to understand. Can you also guide us to get stock exchange value? for example. BSE value, NSE value etc. Till now, every thing is for stock value, not stock exchange value.

    thanks in advance,
    Harsh

  15. admin

    If I understand correctly your looking to get the price of the index such as the Dow Jones Industrial Average? If so you just need to pass the correct ticker in like so: http://www.google.com/ig/api?stock=DJI

  16. Adnan latif

    This info very helpful can anybody please tell me that how to get current stock price in this xml we get low,high and last i want to get current stock price for a ticker.
    thanks

  17. Curt

    Does anybody know how to get data from Google Fiance API for stock market indexes such as Dow Jones, S&P 500, London’s FTSE, Paris CAC, Frankfurt DAX, etc?

  18. Ben

    Anyone know if there are any special tags we can use in the URL to specify the data that is received??

  19. kamlendra kumar

    I was just looking for this onr and will congrats you for such a wonderful article.

    though this retrieves not only american stocks quote it retrieves world wide stock quote perhaps, there comes problem to retrieve some of those stocks which symbols are same in NYSE and other country’s stock symbol such as ACC, HCC, INFY, ITC of NSE of india. I”ve tried it to retrieve using nse:acc this also not works.

    there is a kind request do you have any solution of this problem? if yes please suggest us.

    thanks for such wonderful article…

  20. udipth

    Can I use google API to feed data in commercial application. They say you need to take written permission. How do I do that

  21. Sagar Patel

    Thanks so much.
    It was very helpful.
    can u tell me how can i get historic data. I want to use it for making graphs in my application.
    thanks….

  22. admin

    I have an article that shows how to get historical stock data from Yahoo and it includes a class to parse the results: http://www.jarloo.com/get-historical-stock-data/ Hope this helps.

  23. Erik

    @SUCHIGEORGE
    For PHP I use xpath (if you’re using v5+). Here an example code.


    ?
    $xml = simplexml_load_file('http://www.google.com/ig/api?stock=AAPL');
    $finance = $xml->xpath("/xml_api_reply/finance");
    ?
    ?= $finance[0]->temp_f['data'];?
    ?= $finance[0]->condition['data'];?

  24. Erik

    @SUCHIGEORGE
    Sorry, forgot to change the code that I use with google’s weather api.


    ?
    $xml = simplexml_load_file('http://www.google.com/ig/api?stock=AAPL');
    $finance = $xml->xpath("/xml_api_reply/finance");
    ?
    ?= $finance[0]->symbol['data'];?
    ?= $finance[0]->last['data'];?

    FYI: The question marks are either preceded or followed by a

  25. Sagar Patel

    Thanx guys, I tried this But
    I have a problem that in my case there is same name for multiple roots in xml file and i want price from each stock.
    U can check here
    i don’t how to differentiate between two Finance roots.
    please help to sort this out.
    Thanks so much….

  26. admin

    You just need to loop through the two roots. There will be a collection of “finance” Elements. Here is a quick LINQ example of iterating them and return the results.

    XDocument doc = XDocument.Load("http://www.google.com/ig/api?stock=goog&stock=aapl");
    var data = from e in doc.Root.Elements("finance")
        select new
    		{
    			Symbol = e.Element("symbol").Attribute("data").Value,
    			Last = Convert.ToDecimal(e.Element("last").Attribute("data").Value),
    			High = Convert.ToDecimal(e.Element("high").Attribute("data").Value),
    			Low = Convert.ToDecimal(e.Element("low").Attribute("data").Value),
    			Open = Convert.ToDecimal(e.Element("open").Attribute("data").Value)
    		};
    
    foreach (var price in data)
    {
        Console.WriteLine(string.Format("{0}={1}",price.Symbol,price.Last));
    }
    

  27. Sagar Patel

    Thanks So much.. It worked..
    Can u please tell me how can i get real time data because this data refreshes after 3-4 minutes and 8-10 minutes in some company’s cases..
    I think Google refreshes maximum every minute though it’s Late. Then why it is not reflecting in their APIs….
    Thanks for your guidance….

  28. Shreyansh

    Can this URLs be used commercially for free ?

  29. admin

    I wouldn’t suggest using it commercially. This is an UNOFFICIAL API, so there is no guarantee it will even be around tomorrow.

  30. Wayne D

    There is also a way of downloading historical data from Google using another undocumented approach. I found this link useful (http://www.codeproject.com/Articles/221952/Simple-Csharp-DLL-to-download-data-from-Google-Fin) This does have the advantage of allowing you to download data from many different exchanges (which you can’t do with Yahoo and some methods using Google). However, there is a problem with the approach… Unlike Yahoo, Google doesn’t include the Adjusted price. This can make for some very crazy numbers when there’s a stock split.

    My gutt is telling me that the best approach for getting all the information one may want will involve a combination of approaches.

  31. Mark

    How to calculate 2 years avearge return on a stock

  32. JASON

    This api is not updated in real time. if you watch it closely it updates every 2 minutes. If you catch it at the exact moment of the update, then it’s real time, otherwise it can be delayed up to 120 seconds.

    Still very useful for data mining.

  33. David

    For those looking to get Index info like The Dow, simply use a period in front of the symbol… i.e. .dji
    Works great EXCEPT, fo some reason, this data is 15 minutes delayed. Unlike the stock date which is much more real time…

  34. Radek

    Dla listy okolo 2500 symboli serwis smigal ok. Po takiej porcji chcialem zapuscic proces na nowo ale dostaje The remote server returned an error: (503) Server Unavailable. :) Od czasu do czasu pojawia sie Captcha na stronce przed wyswietleniem xml-a (jesli wiecie o co mi chodzi) :) Jakies pomysly na obejscie error code: 503?

  35. admin

    I don’t get a 503 error when I try it. Perhaps Google had some maintenance or something when you ran? If I try http://www.google.com/ig/api?stock=AAPL it works fine.

  36. Munkhjin

    This is good example but has one defect; Example , I want get IBM of London but respond IBM of Newyork. It is not enough only stock symbol, needs market name. How to get IBM of London. Help me.

  37. Joe C

    Hi All, thanks for this great thread. I am a Business Systems Analyst so not very familiar with XML but trying to use this code in a SharePoint 2010 XML viewer web part. Is that possible? I don’t see any absolute path to the source data within the XML that would tell it to go to Google. and I am struggling with the corresponding .xslt

    Any thoughts on how I could achieve this?

    Thanks

  38. admin

    Sorry but I haven’t worked with SharePoint in years.

  39. Carl

    So… *IS* the Google Stock API the same thing (or subsection) as the Google Finance API? ie – is the Stock API going to disappear in October (2012) along with all the Finance API?

  40. Karthick

    How to get the API for NSE: LT

  41. shahid iqbal

    Will this stock api of google will also be Deprecated as the google finance api…
    Any body having an idea about this pls answer…
    thanks in advance

  42. Abdelrahaman Aly

    Hey can i have historic data with the service???

  43. Ravan

    i tried to consume this web service via ADF mobile. Using http://www.google.com/ig/api?stock=AAPL gives a response as unable to connect to http://www.google.com at port: xx : java.net.connectException:Connection Timed Out..

    may be my question is not very related to you, but it would be great if you could help me on this.

  44. Arpit Makhiyaviya

    please anyone teli me how to get the symbols of shares ?

  45. Bart

    The issue with getting data from Yahoo or Google is that any web service they provide is for “personal use only”. Therefore, publishing on a commercial site or app could be considered a violation of their terms of service. It’s fine for a blog or something but once you get a little more usage, it just isn’t enough.
    Anyway, I’ve been using FinancialContent’s XML API for my iOS application and it works great. The sales rep Stephen there enlightened me on the intellectual property issues.
    Xignite is another good provider that I’ve used.

Trackbacks/Pingbacks

  1. How to parse Google Finance in PHP « Simon Irmančnik - [...] on. In contrast of the stock API, the result isn’t formatted in a pretty XML sequence, it rather uses ...
  2. 由SSIS取得WebService資訊並更新至DB | 不認真寫部落格 - [...] 2. Kelly Elias – Google Stock API [...]
  3. 由google stock API製作自己的股票報價單 | TDN Blog - [...] Jarloo [...]

Leave a Comment

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>