What will we cover in this tutorial?
In this tutorial we will cover the following.
- How to use Pandas Datareader to read historical stock prices from Yahoo! Finance.
- Learn how to read weekly and monthly data.
- Also how to read multiple tickers at once.
Step 1: What is Pandas Datareader?
Pandas-Datareader is an up to date remote data access for pandas.
This leads to the next question. What is pandas?
Pandas is a data analysis and manipulation tool containing a great data structure for the purpose.
Shortly said, pandas can be thought of as a data structure in Python, which is similar to working with data in a spreadsheet.
Pandas-datareader reads data from various sources and puts the data into a pandas data structures.
Pandas-datareader has a call to return historic stock price data from Yahoo! Finance.
To use Pandas-datareader you need to import the library.
Step 2: Example reading data from Yahoo! Finance with Pandas-Datareader
Lets break the following example down.
Where we first import two libraries.
- pandas_datareaderThe Pandas Datareader. If you do not have it installed already in your Jupyter Notebook you can do that by entering this in a cell!pip install pandas_datareaderand execute it.
- datetimeThis is a default library and represents a date and time. We only use it for the date aspects.
The the following lines.
- ticker = AAPLThe ticker we want data from. You can use any ticker you want. In this course we have used the ticker forApple(AAPL).
- start = dt.datetime(2019, 1, 1)Is the starting day we want historic stock price data.
- end = dt.datetime(2020, 12, 31)The end day.
- data = pdr.get_data_yahoo(ticker, start, end)This is the magic that usesPandas Datareader(pdr) to get data from theYahoo! Finance API. It returns a DataFrame as we know it from previous lessons.
The output of the code is as follows.
Step 3: A few parameters to set
You can get multiple tickers at once by parsing a list of them.
You can get the weekly or monthly data by using the argument as follows.
Set interval=m to get monthly data instead of weekly with w.
Next steps?
Want to learn more?
This is part of the FREE online course on my page. No signup required and 2 hours of free video content with code and Jupyter Notebooks available on GitHub.
Follow the link and read more.
Python for Financial Analysis with Pandas