How to Download historical stock prices in Python ?
Last Updated :
05 Apr, 2021
Stock prices refer to the current price of the share of that stock. Stock prices are widely used in the field of Machine Learning for the demonstration of the regression problem. Stock prediction is an application of Machine learning where we predict the stocks of a particular firm by looking at its past data. Now to build something like this first step is to get our historical stock data.
We can get our historical stock data using API's provided as library support in Python. A few of the API's are mentioned below:
- Yahoo Finance
- Pandas DataReader
- Quandl
Approach:
Each of the methods uses a different python module, but they have a similar procedural structure which includes the following steps:
1. Import required libraries
- We are using datetime module to get the date of the starting and ending limit of the stock data required.
- We are using matplotlib module to display the data extracted in a graphical format.
2. Initialize the start and end date for getting the stock data during that time period.
3. Get the data using the dedicated functions provided in each of the modules.
4. Display the data using the matplotlib library. We use the plot() function to plot the data in a graphical format.
Method 1: Using Yahoo Finance
We can get stock using the yfinance.download() function provided in the yfinance module which is a module for Yahoo's Finance API. We can download the module using the following command.
pip install yfinance
We need to supply 3 required parameters in the yfinance.download() function which are
- Stock Symbol
- Start date
- End date
Below is the implementation.
Python3
# import modules
from datetime import datetime
import yfinance as yf
import matplotlib.pyplot as plt
# initialize parameters
start_date = datetime(2020, 1, 1)
end_date = datetime(2021, 1, 1)
# get the data
data = yf.download('SPY', start = start_date,
end = end_date)
# display
plt.figure(figsize = (20,10))
plt.title('Opening Prices from {} to {}'.format(start_date,
end_date))
plt.plot(data['Open'])
plt.show()
Output:

Method 2: Using Pandas DataReader
Another way of getting the historical stock data is to use the pandas_datareader library. It also uses Yahoo's Finance API to load in the data. We can download the module using the following command.
pip install pandas_datareader
It also requires the similar three fields to load in the data which are
- Stock Symbol
- Start date
- End date
Below is the implementation:
Python3
# import modules
from pandas_datareader import data as pdr
import matplotlib.pyplot as plt
# initializing Parameters
start = "2020-01-01"
end = "2021-01-01"
symbols = ["AAPL"]
# Getting the data
data = pdr.get_data_yahoo(symbols, start, end)
# Display
plt.figure(figsize = (20,10))
plt.title('Opening Prices from {} to {}'.format(start, end))
plt.plot(data['Open'])
plt.show()
Output:

Method 3: Using Quandl
Quandl has hundreds of free and paid data sources, across equities, fixed incomes, commodities, exchange rates, etc. In order to get the access, we need to create an account on Quandl and get an API Key to access the data for free. After that, we need to download the API support quandl library of python using the following command.
pip install quandl
We will use quandl.get() function to get the data. It takes four fields to load in the data
- Symbol
- start_date
- end_date
- Authentication token
Below is the implementation:
Python3
# import modules
import quandl
from datetime import datetime
import matplotlib.pyplot as plt
# initialize parameters
start = datetime(2015, 1, 1)
end = datetime(2020, 1, 1)
# get the data
df = quandl.get('NSE/OIL', start_date = start,
end_date = end,
authtoken = 'enter_your_api_key')
# display
plt.figure(figsize=(20,10))
plt.title('Opening Prices from {} to {}'.format(start, end))
plt.plot(df['Open'])
plt.show()
Output:
Similar Reads
Multithreaded download of yahoo stock history with Python - yfinance
Yfinance is a python package that enables us to fetch historical market data from Yahoo Finance API in a Pythonic way. It becomes so easy for all the Python developers to get data with the help of yfinance. We can easily download historical stock data from yfinance, but the problem is, it is very ti
3 min read
How to Download All Images from a Web Page in Python?
Prerequisite: Requests BeautifulSouposFile Handling Web scraping is a technique to fetch data from websites. While surfing on the web, many websites donât allow the user to save data for personal use. One way is to manually copy-paste the data, which both tedious and time-consuming. Web Scraping is
3 min read
How to Download Python Old Version and Install
Python is a popular programming language known for its simplicity and versatility. When we install Python in our systems we always install the latest version of it but there may be situations where we need to install an older version of Python due to compatibility reasons or to work on legacy projec
2 min read
Web Scraping for Stock Prices in Python
Web scraping is a data extraction method that collects data only from websites. It is often used for data mining and gathering valuable insights from large websites. Web scraping is also useful for personal use. Python includes a nice library called BeautifulSoup that enables web scraping. In this a
6 min read
Build a GUI Application to Get Live Stock Price using Python
The stock price is the highest amount someone is willing to pay for the stock. In this article, we are going to write code for getting live share prices for each company and bind it with GUI Application. Module Needed Yahoo_fin: This module is used to scrape historical stock price data, as well as t
3 min read
Python - Performing operations on the stock data
This article demonstrates basic operations that can be done using Python to analyze and construct algorithmic trading strategies on stock data. We run through some simple operations that can be performed using Python on stock data, and we begin by reading stock data from a CSV file. Python has emerg
4 min read
How to download Files with Scrapy ?
Scrapy is a fast high-level web crawling and web scraping framework used to crawl websites and extract structured data from their pages. It can be used for a wide range of purposes, from data mining to monitoring and automated testing. In this tutorial, we will be exploring how to download files usi
8 min read
How to add timestamp to CSV file in Python
Prerequisite: Datetime module In this example, we will learn How to add timestamp to CSV files in Python. We can easily add timestamp to CSV files with the help of datetime module of python. Let's the stepwise implementation for adding timestamp to CSV files in Python. Creating CSV and adding timest
5 min read
How to Install Packages in Python on Linux?
To install a package in python, we use pip. The pip is a python package manager. In this tutorial, we will be discussing how we can install packages in python on a Linux system. To install packages in python on Linux, we must have python and pip installed on our Linux machine. As python comes preins
2 min read
How to Install Ta-Lib for Python?
Ta-Lib (Technical Analysis Library) is a widely used open-source library that provides technical analysis of financial market data. It includes over 150 technical indicators such as moving averages, RSI, MACD, and Bollinger Bands. This guide covers the installation of Ta-Lib on different operating s
3 min read