format. Apart from the visualization aspect, how to read out data from such APIs is also of
interest.
Real-time FX data
Our first example is based on a JSON API for, among others, FX rates. Some imports first:
In [ 51 ]: import time
import pandas as pd
import datetime as dt
import requests
The API we use is from OANDA, an FX online broker. This broker offers an API sandbox
that provides random/dummy data that resembles real exchange rates. Our example is
based on the EUR–USD exchange rate (cf. the API guide):
In [ 52 ]: url = ‘http://api-sandbox.oanda.com/v1/prices?instruments=%s’
# real-time FX (dummy!) data from JSON API
To connect to the API we use the requests library whose aim is to improve the interface
for “humans” when interacting with web resources:
In [ 53 ]: instrument = ‘EUR_USD’
api = requests.get(url % instrument)
With the open connection, data in JSON format is simply read by calling the method json
on the connection object:
In [ 54 ]: data = api.json()
data
Out[54]: {u’prices’: [{u’ask’: 1.25829,
u’bid’: 1.2582,
u’instrument’: u’EUR_USD’,
u’time’: u‘2014-09-29T06:14:34.749878Z’}]}
Unfortunately, the data is not yet completely in the format we would like it to have.
Therefore, we transform it a bit. The following code takes only the first element of the
list object stored under the key “prices.” The resulting object is a standard dict object:
In [ 55 ]: data = data[‘prices’][ 0 ]
data
Out[55]: {u’ask’: 1.25829,
u’bid’: 1.2582,
u’instrument’: u’EUR_USD’,
u’time’: u‘2014-09-29T06:14:34.749878Z’}
Since we collect such small data sets at a high frequency, we use a DataFrame object to
store all the data. The following code initializes an appropriate DataFrame object:
In [ 56 ]: ticks = pd.DataFrame({‘bid’: data[‘bid’],
‘ask’: data[‘ask’],
‘instrument’: data[‘instrument’],
‘time’: pd.Timestamp(data[‘time’])},
index=[pd.Timestamp(data[‘time’]),])
# initialization of ticks DataFrame
In [ 57 ]: ticks[[‘ask’, ‘bid’, ‘instrument’]]
Out[57]: ask bid instrument
2014-09-29 06:14:34.749878+00:00 1.25829 1.2582 EUR_USD
Implementing a real-time plot requires two things: real-time data collection and real-time
updates of the plot. With Bokeh, this is accomplished by using the Bokeh server, which
handles real-time updates of a plot given new data. It has to be started via the shell or
command-line interface as follows:
$ bokeh-server