Downloading historical stock prices in Python | by Rohan Joseph | Towards Data Science

Open up a notebook and follow along:
What we need is pandas (the bread and butter for data science in python), yfinance for downloading the historical stock prices from yahoo finance, datetime and time which provides functions to manipulate dates and times, requests for sending HTTP requests and io for handling strings.
import pandas as pdimport yfinance as yfimport datetimeimport timeimport requestsimport io
Next, we want to provide the start and end dates, during which period we want the daily stock prices. Below, I have provided the start date as 1st February 2020 (approximate beginning of this year’s misery) and end date as 11th October 2020, the current date when I executed this code. You could set the start and end date to anything you like- but what I am trying to analyze is the price fluctuation from pre-pandemic times till now.
start = datetime.datetime(2020,2,1)end = datetime.datetime(2020,10,11)
We want to get the stock ticker symbols listed on NASDAQ. You can skip this step if you know exactly the companies you want the historical stock prices for (example: Tesla -> TSLA, Facebook -> FB etc). But the idea here is to look beyond the popular companies and unearth some interesting price movements for the not-so-well-known companies.
The code below would access the URL containing a CSV file with the company names and their stock symbol, and convert it to a pandas dataframe.
url="https://pkgstore.datahub.io/core/nasdaq-listings/nasdaq-listed_csv/data/7665719fb51081ba0bd834fde71ce822/nasdaq-listed_csv.csv"s = requests.get(url).contentcompanies = pd.read_csv(io.StringIO(s.decode('utf-8')))
Some of the companies provided in this dataset may be delisted or may not be available to download.
Let’s take a look at how this dataset looks like:
From this dataset, let’s extract only the Symbols and convert them into a list.
Symbols = companies['Symbol'].tolist()
Iterate over each stock symbol and using yahoo finance API, download the daily stock prices between the start and end dates.
Append all the individual stock info and create the analytical dataset. Also, note that some symbols may be unavailable to download, for which we have added the ‘try’ and ‘except’ clauses to handle them.
# create empty dataframestock_final = pd.DataFrame()# iterate over each symbolfor i in Symbols:          # print the symbol which is being downloaded    print( str(Symbols.index(i)) + str(' : ') + i, sep=',', end=',', flush=True)          try:        # download the stock price         stock = []        stock = yf.download(i,start=start, end=end, progress=False)                # append the individual stock prices         if len(stock) == 0:            None        else:            stock['Name']=i            stock_final = stock_final.append(stock,sort=False)    except Exception:        None
This is how the final dataset looks like.
stock_final.head()
Voila! For each stock symbol and date, we have the opening, high, low and closing and adjusted closing price, along with the volume traded.
This article covers the first step of stock market analysis which is creating the analytical dataset. The next step would be diving further into this dataset to through exploratory data analysis, and machine learning models.
Connect on LinkedIn and find notebook on Github.