DEV Community

Cover image for Getting Historical Stock Data Using Python
Charles White
Charles White

Posted on

Getting Historical Stock Data Using Python

There's an easy way to get stock data using pandas_datareader from yahoo finance which uses basics of pandas dataframe and also doing a moving average. It actually only takes a few lines of code and can help you in your data pipeline. This is just the quick snippet to get you going, if you want to see the full article you can scroll to the bottom.

Extracting data from yahoo with Pandas

We will be using Yahoo Finance for obtaining stock data. Firstly we will import pandas_datareader.data then send a request to yahoo finance with ticker , start and end date. The “pandas_datareader” module is a useful module that abstracts extracting web data very easily. You don’t have to bother with “requests” or “urllib” and parse the HTML data, this is all done for you! From the module in response we will get a dataframe containing our data in rows and columns . The columns are basically High , Low , Open , Close , Volume and Adj Close.

import pandas_datareader.data as web
import datetime as dt

ticker = "AAPL" # This is Apple's ticker
start = dt.datetime(2020,1,1) # Starting date in format (year,month,day)
end = dt.datetime(2020,12,1) # Ending date 

df = web.DataReader(ticker,"yahoo",start,end)
print(df.head()) # Prints first 5 columns of data
print(df.shape) # Prints the number of rows and columns
Enter fullscreen mode Exit fullscreen mode

You get the output:
Output

  • df = web.DataReader(ticker,"yahoo",start,end) - This stores the dataframe obtained in the variable df. The first value passed here is ticker i.e. “AAPL” , second is the source name . As we are using yahoo finance here so it should be “yahoo”. Then the end and start date (in the form of datetime). You can see other data sources here.
  • print(df.head()) - It prints the first 5 columns of the data obtained.
  • print(df.shape) - Prints the rows and columns in the dataframe . As seen in output there are 241 rows and 6 columns

There's more..

There's still want to know more you can find out all of these and more at our full article: Full article: how to get and chart historical stock data

Top comments (0)