12. Fetching Financial Data from the Web#

Getting ready#

For this recipe, we will use the Python libraries yfinance and pandas_datareader.

If you use pip to manage your Python packages, you can install these libraries using the following commands

pip install yfinance

pip install pandas_datareader

How to do it#

Using yfinance#

  1. Import yfinance module as yf

import yfinance as yf
  1. Download the historical data for the TESLA stock price by using the method download and passing the ticker TSLA

data = yf.download('TSLA', multi_level_index=False)
YF.download() has changed argument auto_adjust default to True
[*********************100%***********************]  1 of 1 completed

  1. Check the type of the returned value.

type(data)
pandas.core.frame.DataFrame
  1. Inspect the pandas DataFrame by calling head, and describe

data.head()
Close High Low Open Volume
Date
2010-06-29 1.592667 1.666667 1.169333 1.266667 281494500
2010-06-30 1.588667 2.028000 1.553333 1.719333 257806500
2010-07-01 1.464000 1.728000 1.351333 1.666667 123282000
2010-07-02 1.280000 1.540000 1.247333 1.533333 77097000
2010-07-06 1.074000 1.333333 1.055333 1.333333 103003500
data.describe()
Close High Low Open Volume
count 3682.000000 3682.000000 3682.000000 3682.000000 3.682000e+03
mean 84.042719 85.916742 82.091640 84.068473 9.651920e+07
std 110.747440 113.321844 108.110895 110.838840 7.744906e+07
min 1.053333 1.108667 0.998667 1.076000 1.777500e+06
25% 12.193166 12.439501 11.978500 12.233500 4.923488e+07
50% 18.229000 18.461000 17.867667 18.172667 8.195580e+07
75% 181.355003 185.197498 177.367504 182.075005 1.216603e+08
max 479.859985 488.540009 457.510010 475.899994 9.140820e+08
  1. Import the plotly.express module as px

import plotly.express as px
  1. Plot the Close price using px.line. Note that we are giving the index of the DataFrame as values for the x-axis.

fig = px.line(data, x=data.index, y ='Close', title='TESLA Data from Yahoo Finance')
fig.show()

Using pandas_datareader#

  1. Import the pandas_datareader module as pdr

import pandas_datareader as pdr
  1. Read the data

data = pdr.get_data_fred('GS30')
  1. Inspect the data

data.head()
GS30
DATE
2020-03-01 1.46
2020-04-01 1.27
2020-05-01 1.38
2020-06-01 1.49
2020-07-01 1.31
  1. Create a line plot

fig = px.line(data, x=data.index, y='GS30', title='GS30')
fig.show()