Python for Finance: Analyze Big Financial Data

(Elle) #1

Web Plotting


Chapter 5 introduces matplotlib, the most popular plotting library for Python. However,


as powerful as it might be for 2D and 3D plotting, its strength lies in static plotting. In


fact, matplotlib is also able to generate interactive plots, e.g., with sliders for variables.


But it is safe to say that this is not one of its strengths.


[ 54 ]

This section starts with generating static plots, then proceeds to interactive plots to finally


arrive at real-time plotting.


Static Plots


First, a brief benchmark example using the pandas library based on a financial time series


from the Yahoo! Finance API, as used in the previous section:


In  [ 44 ]: import numpy as np
import pandas as pd
%matplotlib inline

As shown in Chapter 6, using pandas makes data retrieval from the Web in general quite


convenient. We do not even have to use additional libraries, such as urllib — almost


everything happens under the hood. The following retrieves historical stock price quotes


for Microsoft Inc. and stores the data in a DataFrame object:


In  [ 45 ]: url =   ‘http://ichart.yahoo.com/table.csv?s=MSFT&a=0&b=1&c=2009’
data = pd.read_csv(url, parse_dates=[‘Date’])

pandas accepts column names as parameter values for the x and y coordinates. The result


is shown in Figure 14-1:


In  [ 46 ]: data.plot(x=‘Date’, y=‘Close’)

Figure 14-1. Historical stock prices for Microsoft since January 2009 (matplotlib)

Graphics and plots like Figure 14-1 can of course also be used in a web context. For


example, it is straightforward to save plots generated with matplotlib as files in the PNG


(Portable Network Graphics) format and to include such files in a website. However,


recent web technologies typically also provide interactivity, like panning or zooming.


Bokeh is a library that explicitly aims at providing modern, interactive web-based plots to


Python. According to its website:


Bokeh is a Python interactive visualization library for large data sets that natively uses the latest web

technologies. Its goal is to provide elegant, concise construction of novel graphics in the style of Protovis/D3,
Free download pdf