Importing Financial Data form the Web

1 minute read

Using pandas_datareader to import financial data from the web to a dataframe

It is convinient to use pandas_datareader to import fiancial data directly into a dataframe. The process is very straight-forward, there is minimal code required and the data is available from different sources such as Google Finance, Yahoo!, the Federal Reserve, the World Bank, etc.

import pandas as pd
import numpy as np
import pandas_datareader as pdr 
from datetime import datetime
#import datetime
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('whitegrid')
%matplotlib inline
#Set times, -1 = yearg ago from now
end = datetime.now()
print (end)

start = datetime(end.year -1, end.month, end.day)
print (start)
2018-10-23 21:29:25.592488
2017-10-23 00:00:00
stock_data = pdr.DataReader('AAPL', 'yahoo', start, end)
stock_data.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 253 entries, 2017-10-23 to 2018-10-23
Data columns (total 6 columns):
Open         253 non-null float64
High         253 non-null float64
Low          253 non-null float64
Close        253 non-null float64
Adj Close    253 non-null float64
Volume       253 non-null int64
dtypes: float64(5), int64(1)
memory usage: 13.8 KB
stock_data.head()
Open High Low Close Adj Close Volume
Date
2017-10-23 156.889999 157.690002 155.500000 156.169998 153.843857 21984300
2017-10-24 156.289993 157.419998 156.199997 157.100006 154.760010 17757200
2017-10-25 156.910004 157.550003 155.270004 156.410004 154.080307 21207100
2017-10-26 157.229996 157.830002 156.779999 157.410004 155.065399 17000500
2017-10-27 159.289993 163.600006 158.699997 163.050003 160.621384 44454200
stock_data.tail()
Open High Low Close Adj Close Volume
Date
2018-10-17 222.300003 222.639999 219.339996 221.190002 221.190002 22885400
2018-10-18 217.860001 219.740005 213.000000 216.020004 216.020004 32581300
2018-10-19 218.059998 221.259995 217.429993 219.309998 219.309998 33078700
2018-10-22 219.789993 223.360001 218.940002 220.649994 220.649994 28792100
2018-10-23 215.830002 223.250000 214.699997 222.729996 222.729996 38616200
#View historical trend of the closing price Adj Close column
stock_data['Adj Close'].plot(legend=True, figsize=(10,4))
<matplotlib.axes._subplots.AxesSubplot at 0x11f3f0160>

alt