Search code examples
pythonc#ryahoo

Yahoo Option Data with R but has error? Better examples in Python or C#?


I am trying to run a R script from: http://www.math.tu-berlin.de/~mkeller/R-progs/yahoo_opt.R Description at: http://www.math.tu-berlin.de/~mkeller/index.php?target=rcode

I am new at R but I get a really strange error when I run the following as instructed:

opt <- yahoo.getAllOptions("IBM")

The error is:

trying URL 'http://finance.yahoo.com/q/op?s=IBM&m=2011-06' Content type 'text/html; charset=utf-8' length unknown opened URL downloaded 57 Kb

Read 2616 items Error in yahoo.getOption(ticker = ticker, maturity = mat[j], get.short.rate = FALSE) : Unexpected data format

Does anyone know how to correct this? I am new to R and this could a newbie question but I am stumped. Does anyone know of a better source example in C# or Python? I don't mind, I just want to get the Yahoo Options data. Thanks


Solution

  • Have you heard of the YQL Console and datatables.org? It provides access to a lot of Yahoo (and other) data tables using REST requests returning XML or JSON objects. There is a nice options table you can easily access using Python's urllib. Consider the following example:

    >>> import urllib2
    >>> import json
    >>> url='http://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20yahoo.finance.options%20WHERE%20symbol%3D\"goog\"%20AND%20expiration%3D\"2011-08\"&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback='
    >>> req = urllib2.Request(url)
    >>> response = urllib2.urlopen(req)
    >>> result = json.loads(response.read())
    

    result is an json object containing all options for GOOG with a 2011-08 expiration. If you look closely in the url, you'll see the symbol for Google and the expiration date. This can be easily modified programmatically.

    >>> result['query']['results']['optionsChain']['option'][0]
    {u'strikePrice': u'400', u'lastPrice': u'110.10', u'vol': u'1', u'type': u'C', u'symbol': u'GOOG110820C00400000', u'openInt': u'9', u'ask': u'90.5', u'changeDir': None, u'bid': u'87', u'change': u'0'}
    >>> result['query']['results']['optionsChain']['option'][10]
    {u'strikePrice': u'490', u'lastPrice': u'21.20', u'vol': u'350', u'type': u'C', u'symbol': u'GOOG110820C00490000', u'openInt': u'56', u'ask': u'21.3', u'changeDir': u'Down', u'bid': u'20.8', u'change': u'-6.9'}
    

    Note you can also return the results in XML.

    Google "yql consol", click on the first link. On the right side, click the link that says "Show Community Tables". Scroll down to Yahoo. Click on yahoo.finance.options. You should be able to figure out the rest :)