Matplotlib 3.0 Cookbook
上QQ阅读APP看书,第一时间看更新

There's more...

Instead of reading the Google Stock Price data from a .csv or .xlsx file, there are standard APIs such as fix_yahoo_finance, pandas_datareader that can read data directly from open databases.

Standard APIs undergo frequent changes and at times the database websites are not responsive. You need to install these APIs on your machine, as they don't come with standard Python distributions.

Here, we will show an example of using fix_yahoo_finance:

  1. Import the required libraries:

import matplotlib.pyplot as plt
import pandas as pd
import fix_yahoo_finance as yf
  1. Download the apple daily closing price from October 1, 2017 to January 1, 2018:
data = yf.download('AAPL','2017-10-01','2018-01-01')

  1. Plot the closing price (Close) by date. Please note that date is the default x axis here, as yf.download creates data with date index. Hence, we don't need to provide x axis co-ordinates for the plot. Please note that here we are using plot() command of pandas, not Matplotlib:
data.Close.plot()
  1. Display the graph on the screen:
plt.show()

You should see a graph, like the one depicted here:

You can try using the pandas_datareader API. Please refer to the documentation at http://pandas-datareader.readthedocs.io/en/latest/ on pandas_datareader for more details.