Fetch and plot historical financial data from Yahoo Finance

Fetch and plot historical financial data from Yahoo Finance

Yahoo Finance is a platform that provides financial news, stock quotes, press releases, financial reports as well as historical data for stocks. In this post we are going to download historical data from Yahoo Finance and plot the same using the python code. Yahoo used to provide the historical data via its API till 2017 but now the service is no longer available. But don’t be disheartened; we have a library yfinance in python that does the job for us. So let’s get started.

[media-credit name=’Image by Anand Kumar from Pixabay‘ align=”aligncenter” width=”1280″][/media-credit]

Let us first install the yfinance module using the following command:

pip install yfinance

Next let’s take a look at the code to plot the Time Series data based on Adjusted Closing Price for Maruti Suzuki

# import the required libraries
import yfinance as yf

stock_ticker = 'MARUTI.BO'
start_date = '2013-01-01'
end_date = '2020-03-25'

# fetch the data for the required duration
# the fetched data has Date column set as the DateTimeIndex by default
data = yf.download(stock_ticker, start=start_date, end=end_date)

# Fill in the missing data using forward fill and backward fill
data.fillna(method='ffill', inplace=True)
data.fillna(method='bfill', inplace=True)

# plot the historical chart based on Adjusted CLosing Price
data['Adj Close'].plot(figsize=(16,8), title='Adjusted Closing Prices');

So that’s it. Go ahead and run this piece of code in your favorite python editor and Voila you can see the chart plotted.
See you until next time. Happy Learning !

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top