Python for Finance: Analyze Big Financial Data

(Elle) #1

Chapter 6 provides an example based on the data source and API that we use in what


follows. It is the stock price API for intraday real-time data provided by Netfonds, a


Norwegian online broker. The API and web service, respectively, have the following basic


URL format:


In  [ 69 ]: url1    =   ‘http://hopey.netfonds.no/posdump.php?’
url2 = ‘date=%s%s%s&paper=%s.O&csv_format=csv’
url = url1 + url2

This URL is to be customized by providing date information and the symbol one is


interested in:


In  [ 70 ]: today   =   dt.datetime.now()
y = ‘%d’ % today.year
# current year
m = ‘%02d’ % today.month
# current month, add leading zero if needed
d = ‘%02d’ % (today.day)
# current day, add leading zero if needed
sym = ‘AAPL’
# Apple Inc. stocks
In [ 71 ]: y, m, d, sym
Out[71]: (‘2014’, ‘09’, ‘29’, ‘AAPL’)
In [ 72 ]: urlreq = url % (y, m, d, sym)
urlreq
Out[72]: ‘http://hopey.netfonds.no/posdump.php?date=20140929&paper=AAPL.O&csv_fo
rmat=csv’

Equipped with the right URL string, retrieving data is only one line of code away:


In  [ 73 ]: data    =   pd.read_csv(urlreq, parse_dates=[‘time’])
# initialize DataFrame object

The details of what follows are known from the previous example. First, the initial plot:


In  [ 74 ]: bp.line(data[‘time’],   data[‘bid’],
x_axis_type=‘datetime’, legend=sym)
# intial plot
Out[74]: <bokeh.objects.Plot at 0x7f92bedc8dd0>

Second, selection of the rendering object:


In  [ 75 ]: renderer    =   [r for r in bp.curplot().renderers
if isinstance(r, Glyph)][ 0 ]
ds = renderer.data_source

Third, the while loop updating the financial data and the plot per loop:


In  [ 76 ]: start   =   time.time()
while (time.time() - start) < 60 :
data = pd.read_csv(urlreq, parse_dates=[‘time’])
data = data[data[‘time’] > dt.datetime(int(y), int(m), int(d),
10 , 0 , 0 )]
# only data from trading start at 10am
ds.data[‘x’] = data[‘time’]
ds.data[‘y’] = data[‘bid’]
ds._dirty = True
bp.cursession().store_objects(ds)
time.sleep(0.5)

Figure 14-6 shows the resulting output — again, unfortunately, only a static snapshot of a


real-time plot.

Free download pdf