Downloading historical stock prices in Python

Nosotros volition be looking at a quick and automatic way to download the historical stock prices in Python. This article volition comprehend creating the analytical dataset to aid in analyzing the stock marketplace.

Rohan Joseph

Photograph by https://unsplash.com/@m_b_m at unsplash

Open up up a notebook and follow along:

Step 1: Download the required packages.

What we need is pandas (the staff of life 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 treatment strings.

          import pandas equally pd
import yfinance as yf
import datetime
import time
import requests
import io

Step 2: Prepare the date range

Next, we want to provide the showtime and end dates , during which menstruum we want the daily stock prices. Below, I have provided the get-go date every bit 1st February 2020 (approximate kickoff of this year'south misery) and end appointment equally 11th Oct 2020, the current date when I executed this code. You could set the start and end date to anything y'all like- only what I am trying to clarify is the toll fluctuation from pre-pandemic times till at present.

          start = datetime.datetime(2020,2,1)
end = datetime.datetime(2020,10,eleven)

Step 3: Get the Stock Ticker Symbols

Nosotros want to get the stock ticker symbols listed on NASDAQ. You tin 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 hither is to look across the popular companies and unearth some interesting toll movements for the not-so-well-known companies.

The code below would admission 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.go(url).content          companies = pd.read_csv(io.StringIO(s.decode('utf-8')))        

Some of the companies provided in this dataset may be delisted or may non be available to download.

Let's take a look at how this dataset looks like:

Dataframe containing company symbol and information

From this dataset, permit's extract only the Symbols and convert them into a list.

          Symbols = companies['Symbol'].tolist()        

The list showing the first 10 stock tickers

Stride 4: Download the historical stock prices

Iterate over each stock symbol and using yahoo finance API, download the daily stock prices betwixt the start and end dates.

Append all the individual stock info and create the analytical dataset. Too, note that some symbols may be unavailable to download, for which we have added the 'try' and 'except' clauses to handle them.

          # create empty dataframe
stock_final = pd.DataFrame()
# iterate over each symbol
for i in Symbols:

# print the symbol which is being downloaded
print( str(Symbols.index(i)) + str(' : ') + i, sep=',', end=',', affluent=True)

effort:
# download the stock price
stock = []
stock = yf.download(i,outset=start, end=stop, progress=Imitation)

# append the individual stock prices
if len(stock) == 0:
None
else:
stock['Name']=i
stock_final = stock_final.suspend(stock,sort=False)
except Exception:
None

This is how the concluding dataset looks like.

          stock_final.caput()        

Voila! For each stock symbol and date, we have the opening, high, low and endmost and adapted closing price, along with the book traded.

This article covers the first step of stock market analysis which is creating the belittling dataset. The side by side stride would be diving further into this dataset to through exploratory data analysis, and automobile learning models.

Connect on LinkedIn and find notebook on Github .

DOWNLOAD HERE

Posted by: smithhasitualls.blogspot.com