Jarloo

Menu

Google Stock Options API

There is a little known way to get option chain information from Google, this will show how it’s done as well as demonstrate how to use it using C#. (Easy enough in any language since it’s REST based, so if your not a C# developer don’t let this stop you.)

 

THIS IS NOT AN OFFICIAL API. GOOGLE DOES NOT SUPPORT THIS FOR ANYTHING BUT THEIR OWN INTERNAL USES AND CAN CHANGE AT ANY TIME. USE THIS AT YOUR OWN RISK.

 

Accessing the REST based Google Stock Options API

Google lists stock options on there finance site. An example of this is this one for AAPL’s option chain.

With a very small modification to this you can get the data in a JSON like format. (it’s not exactly JSON, I will cover this below)

Download AAPL’s Option chain using the API

The difference between the site and the API is the addition of a simple query string “output=json”.

So the URL becomes: “http://www.google.com/finance/option_chain?q=AAPL&output=json”

 

Understanding the Google Option API

Calling “http://www.google.com/finance/option_chain?q=AAPL&output=json” will give you back several pieces of data:

  • The next expiry date
  • A list of all the available expiry dates for the symbol
  • A list of all the puts
  • A list of all the calls
  • The price of the underlying stock (not the option price.)

Here is a snippet of the return data:

{
	expiry: {
		y: 2015,
		m: 5,
		d: 8
	},
	expirations: [{
		y: 2015,
		m: 5,
		d: 8
	},
	{
		y: 2015,
		m: 6,
		d: 5
	},
	{
		y: 2017,
		m: 1,
		d: 20
	}],
	puts: [{
		cid: "43623726334021",
		s: "AAPL150508P00085000",
		e: "OPRA",
		p: "-",
		c: "-",
		b: "-",
		a: "-",
		oi: "-",
		vol: "-",
		strike: "85.00",
		expiry: "May 8, 2015"
	},
	{
		cid: "155079769787173",
		s: "AAPL150508P00090000",
		e: "OPRA",
		p: "-",
		c: "-",
		b: "-",
		a: "-",
		oi: "-",
		vol: "-",
		strike: "90.00",
		expiry: "May 8, 2015"
	},
        ...

 

There is obviously way more expiry dates on AAPL options and more calls plus I didn’t show the calls, but I think this should give you an idea of the general structure.

This only works for the latest expiry. All the options returned will be for that expiry only. You can select a different expiry easily enough though:

http://www.google.com/finance/option_chain?q=AAPL&expd=4&expm=4&expy=2014&output=json

You will notice the addition of three new query strings, these denote the year, month and day of the expiry. I find it best to call the previous URL to get the list of valid expiry dates, then use this one to get all the strikes for a specific expiry date.

 

But the results are not valid JSON?

Unfortunately they are not. If you look at the sample pasted above you will notice both the name and value should be enclosed in quotes but are not. In fact NONE of the names are in quotes and only some of the values are.

To fix this I run it through a regular expression to surround the names and values in quotes prior to trying to make an object out of the JSON.

This is where it differs from one language to the next but for C# I do the following:


data = Regex.Replace(data, @"(\w+:)(\d+\.?\d*)", "$1\"$2\"");
data = Regex.Replace(data, @"(\w+):", "\"$1\":");

 

Using this option chain API in your programs

Download the Source on GitHub

This assumes you are using .NET 4.5 or greater. It will work with other versions but you may need to remove the “async/await” logic perhaps the Thread.Run as well.

In C# it’s simple to consume this API and get functioning objects from it.

First lets start with the definition files needed to transform that almost-JSON into .NET objects:

namespace GoogleOptionsApi
{
    public class Expiry
    {
        public string y { get; set; }
        public string m { get; set; }
        public string d { get; set; }
    }
}

namespace GoogleOptionsApi
{
    public class Expiration
    {
        public string y { get; set; }
        public string m { get; set; }
        public string d { get; set; }
    }
}

namespace GoogleOptionsApi
{
    public class Option
    {
        public string cid { get; set; }
        public string s { get; set; }
        public string e { get; set; }
        public string p { get; set; }
        public string c { get; set; }
        public string b { get; set; }
        public string a { get; set; }
        public string oi { get; set; }
        public string vol { get; set; }
        public string strike { get; set; }
        public string expiry { get; set; }
        public string name { get; set; }
        public string cs { get; set; }
        public string cp { get; set; }
    }
}

namespace GoogleOptionsApi
{
    public class OptionData
    {
        public Expiry expiry { get; set; }
        public Expiration[] expirations { get; set; }
        public Option[] puts { get; set; }
        public Option[] calls { get; set; }
        public string underlying_id { get; set; }
        public string underlying_price { get; set; }
    }
}

Pro Tip: If your wondering if I typed all that in the answer is no. Visual Studio has a great little known function. Copy the JSON from that google api call and then in Visual Studio goto Edit->Paste Special->Paste JSON as Classes. And it does the work for you! (I did tweak it a bit, but let VS do boring mapping for you.)

So once we have the basic structure of how to store these calls as described above we need to get the data and fix those JSON issues.

using System.Net;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace GoogleOptionsApi
{
    public static class GoogleOptions
    {
        public static async Task<OptionData> GetOptionChains(string symbol, int? year=null,int? month=null,int? day=null)
        {
            var data = await Task.Run(() =>
            {
                using (var web = new WebClient())
                {
                    string url;

                    if (year != null && month != null & day != null)
                    {
                        url = string.Format("http://www.google.com/finance/option_chain?q={0}&expd={1}&expm={2}&expy={3}&output=json",
                            symbol,day.Value,month.Value,year.Value);
                    }
                    else
                    {
                        url = string.Format("http://www.google.com/finance/option_chain?q={0}&output=json", symbol);
                    }

                    return
                        web.DownloadString(url);
                }
            });

            //Clean up badly formatted JSON to embrace with quotes
            data = Regex.Replace(data, @"(\w+:)(\d+\.?\d*)", "$1\"$2\"");
            data = Regex.Replace(data, @"(\w+):", "\"$1\":");

            //Make object
            var optionData = data.FromJson<OptionData>();
            return optionData;
        }
    }
}

In this we create a WebClient to fetch the data. I do this on a seperate thread, not necessary in all cases but if your going to hook this to a UI this will prevent your UI from being locked while this is getting the data.

Then it calls one of the two URL’s shown earlier, all depending if the expiry day, month and year have been passed in.

The JSON is cleaned up, then it converts it to an object.

That call to .FromJson<…>() is an extension function I wrote that I’m using. It’s using the JSON parsing from System.Runtime.Serialization assembly.

I use this all over the place in most of my projects, and also later will use a .To<>() extension function, so I’ll list it here as well. Keep in mind you can use any JSON parser, such as JSON.NET, this is just my preference.

using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace GoogleOptionsApi
{
    public static class ConversionExtensions
    {
        /// <summary>
        ///     Serializes an object to JSON
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJson<T>(this T obj)
        {
            using (var stream = new MemoryStream())
            {
                var jsSerializer = new DataContractJsonSerializer(typeof (T));
                jsSerializer.WriteObject(stream, obj);
                return Encoding.UTF8.GetString(stream.ToArray());
            }
        }

        /// <summary>
        ///     Deseralizes an object from JSON
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="input"></param>
        /// <returns></returns>
        public static T FromJson<T>(this string input)
        {
            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(input)))
            {
                var jsSerializer = new DataContractJsonSerializer(typeof (T));
                var obj = (T) jsSerializer.ReadObject(stream);
                return obj;
            }
        }

        /// <summary>
        ///     Converts an object to the type specified.
        ///     If the object is a string and null or blank it will return null
        ///     If the object is = DBNull it will return the default type for that object.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="text"></param>
        /// <returns></returns>
        public static T To<T>(this object text)
        {
            if (text == null) return default(T);
            if (text.Equals(DBNull.Value)) return default(T);
            if (text is string) if (string.IsNullOrWhiteSpace(text as string)) return default(T);

            var type = typeof (T);

            var underlyingType = Nullable.GetUnderlyingType(type) ?? type;
            return (T) Convert.ChangeType(text, underlyingType);
        }
    }
}

Adding a UI on the Option Chain Data

So that covers getting the data. If you want to make an option chain table with calls on one side, strikes in the middle and put’s on the other it’s easy enough to do using WPF and the Google Option API Code I have posted on GitHub includes just such an example.

google-option-chains

Yeah I know it’s cringe worthy, but I wanted to display the concept without making the code more difficult by adding more functionality or style then necessary.

To get this layout I created a new class called an OptionPair. It’s only used by the UI to display those rows. Each row is an OptionPair object, that is a put, call, and strike.

using System;

namespace GoogleOptionsApi
{
    public class OptionPair
    {
        public decimal Strike { get; set; }
        public DateTime Expiry { get; set; }
        public Option Call { get; set; }
        public Option Put { get; set; }
    }
}

I didn’t use MVVM for this, again I wanted to keep it simple, so it’s just a single WPF window with some code behind. Here is the full code listing for the window:

using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace GoogleOptionsApi
{
    public partial class MainWindow : Window
    {
        public ObservableCollection<OptionPair> OptionPairs { get; set; }
        public ObservableCollection<Expiration> Expirations { get; set; }
        public Expiration SelectedExpiration { get; set; }
        public string Symbol { get; set; }

        public MainWindow()
        {
            InitializeComponent();

            DataContext = this;

            OptionPairs = new ObservableCollection<OptionPair>();
            Expirations = new ObservableCollection<Expiration>();
        }

        public async void GetInitialData()
        {
            if (Symbol == null) return;

            var od = await GoogleOptions.GetOptionChains(Symbol.ToUpper());

            foreach (var e in od.expirations)
            {
                Expirations.Add(e);
            }

            ShowOptionPairs(od);
        }

        public async void FetchData()
        {
            if (SelectedExpiration == null) return;
            if (Symbol == null) return;

            var od = await GoogleOptions.GetOptionChains(Symbol.ToUpper(), SelectedExpiration.y.To<int>(),
                SelectedExpiration.m.To<int>(), SelectedExpiration.d.To<int>());
            ShowOptionPairs(od);
        }

        public void ShowOptionPairs(OptionData od)
        {
            OptionPairs.Clear();

            var map = od.calls.Select(o => new OptionPair
            {
                Strike = o.strike.To<decimal>(),
                Expiry = o.expiry.To<DateTime>(),
                Call = o
            }).ToDictionary(p => p.Strike);

            foreach (var p in od.puts)
            {
                var strike = p.strike.To<decimal>();

                if (map.ContainsKey(strike))
                {
                    map[strike].Put = p;
                }
                else
                {
                    var x = new OptionPair
                    {
                        Strike = p.strike.To<decimal>(),
                        Expiry = p.expiry.To<DateTime>(),
                        Put = p
                    };
                    map.Add(x.Strike, x);
                }
            }

            var optionPairs = map.Select(pair => pair.Value).ToList();

            foreach (var pair in optionPairs)
            {
                OptionPairs.Add(pair);
            }
        }

        private void Expiry_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            FetchData();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (Symbol == null) return;

            GetInitialData();
        }
    }
}

Most of it should be fairly easy to grasp. When a user enters a stock ticker and clicks a button it gets the initial data which is for the latest expiry for that option.  The expiry dates that are returned are then put into a collection to be displayed in a dropdown box so the user can pick a different one. The OptionPair objects are created and displayed in the grid. If the user selects a new expiry date, then the FetchData() method is called which gets new data and populates the grid.

Here is the XAML

<Window x:Class="GoogleOptionsApi.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:googleOptionsApi="clr-namespace:GoogleOptionsApi"
        Title="MainWindow" Height="511" Width="785">

    <Window.Resources>
        <googleOptionsApi:ExpirationConverter x:Key="ExpirationConverter" />
    </Window.Resources>
    <Grid>
        <DataGrid Margin="0,100,0,0" ItemsSource="{Binding OptionPairs}" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Price" Binding="{Binding Call.p}" />
                <DataGridTextColumn Header="Bid" Binding="{Binding Call.b}" />
                <DataGridTextColumn Header="Ask" Binding="{Binding Call.a}" />
                <DataGridTextColumn Header="Volume" Binding="{Binding Call.vol}" />
                <DataGridTextColumn Header="Open Int" Binding="{Binding Call.oi}" />
                <DataGridTextColumn Header="Strike" Binding="{Binding Strike}" />
                <DataGridTextColumn Header="Price" Binding="{Binding Put.p}" />
                <DataGridTextColumn Header="Bid" Binding="{Binding Put.b}" />
                <DataGridTextColumn Header="Ask" Binding="{Binding Put.a}" />
                <DataGridTextColumn Header="Volume" Binding="{Binding Put.vol}" />
                <DataGridTextColumn Header="Open Int" Binding="{Binding Put.oi}" />
            </DataGrid.Columns>
        </DataGrid>
        <ComboBox HorizontalAlignment="Left" Height="23" Margin="329,31,0,0" VerticalAlignment="Top" Width="175"
                  ItemsSource="{Binding Expirations}" SelectionChanged="Expiry_OnSelectionChanged"
                  SelectedItem="{Binding SelectedExpiration}">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Path=.,Converter={StaticResource ExpirationConverter}}" />
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
        <TextBlock HorizontalAlignment="Left" Margin="329,10,0,0" TextWrapping="Wrap" Text="Expiry"
                   VerticalAlignment="Top" />
        <TextBlock HorizontalAlignment="Left" Margin="333,79,0,0" TextWrapping="Wrap" VerticalAlignment="Top">
            <Run Text="PUTS" /><LineBreak /><Run />
        </TextBlock>
        <TextBlock HorizontalAlignment="Left" Margin="27,79,0,0" TextWrapping="Wrap" Text="CALLS"
                   VerticalAlignment="Top" />
        <TextBlock HorizontalAlignment="Left" Margin="27,10,0,0" TextWrapping="Wrap" Text="Symbol"
                   VerticalAlignment="Top" />
        <TextBox HorizontalAlignment="Left" Height="24" Margin="27,31,0,0" TextWrapping="Wrap" VerticalAlignment="Top"
                 Width="107" Text="{Binding Symbol, Mode=TwoWay}" />
        <Button Content="Get Option Chains" HorizontalAlignment="Left" Height="35" Margin="173,31,0,0"
                VerticalAlignment="Top" Width="115" Click="Button_Click" />

    </Grid>
</Window>

No surprises here just binding the objects. The only thing of note is the ExpirationConverter which takes the year, month, day format Google returns and changes it to something better for display:

using System;
using System.Globalization;
using System.Windows.Data;

namespace GoogleOptionsApi
{
    public class ExpirationConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null) return null;

            var e = (Expiration) value;
            var date = new DateTime(e.y.To<int>(), e.m.To<int>(), e.d.To<int>());
            return date.ToString("MMM dd, yyyy");
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

Hope you enjoyed this look at this useful and interesting option chain API from Google. Keep in mind this is unsupported by Google so I wouldn’t suggest using it in a production level application, but it is interesting to play with.

If your looking to expand on this to add greeks like delta, gamma, vega etc.. I have another article you might want to take a look at: Vanilla Option Math

 

Categories:   Code, Finance

Comments

  • Posted: December 5, 2015 06:14

    gerry

    Kelly thanks for the post. Do you do contract work? I need help to automate an option pricing excel file I have.
  • Posted: December 10, 2015 12:02

    Randy Guidry

    Hi. I'm having trouble using the call “http://www.google.com/finance/option_chain?q=AAPL&output=json” with javascript. Can you send me a small javascript code snippet to make the call and display part of the result, say just the first item, "expiry"? Thanks in advance, Randy
    • Posted: December 16, 2015 21:09

      Kelly Elias

      Sorry I don't have any Javascript to give you, I mainly do C#. My Javascript is poor as it's been a long time since I've really done much in it.
    • Posted: August 26, 2016 23:40

      Kenny Votava

      Randy ... Still need help on this? I can give you some pointers.
      • Posted: October 19, 2016 13:38

        Randy Guidry

        Kenny, Yes I could still use some help. I gave up on it a few months ago because I was getting an "same-origin policy" error when trying to call the Google API. Do you know how to get around this?
  • Posted: March 28, 2016 10:51

    XP

    What about getting data for multiple companies at once? This seems to have very limited utility if you must spam their server with 1 request per company! Don't you end up getting your IP blocked?
  • Posted: July 15, 2016 10:37

    Tony

    Hi: I am using your program Options Chain data with GUI, compiles fine, but when I see the values are complete wrong; In Google Options chain site, for example today July-15-2016, I query the Options chain for AAPL and I select expiration date Aug-26-2016 and I see on the strike price $100 for a PUT the last Price = 3.70, and in your program I get Last Price = 1.20. Why the values of PUTs are wrong? Thanks Tony.