Widget HTML Atas

Download Stock Price Data R

Downloading historical stock prices in Python

We will be looking at a quick and automated way to download the historical stock prices in Python. This article will cover creating the analytical dataset to aid in analyzing the stock market.

Rohan Joseph

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

Open up a notebook and follow along:

Step 1: Download the required packages.

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 pd
import yfinance as yf
import datetime
import time
import requests
import io

Step 2: Set the date range

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)

Step 3: Get the Stock Ticker Symbols

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).content          companies = 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:

Dataframe containing company symbol and information

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

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

The list showing the first 10 stock tickers

Step 4: Download the historical stock prices

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 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=',', 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 .

Source: https://towardsdatascience.com/downloading-historical-stock-prices-in-python-93f85f059c1f

Posted by: handroebs.blogspot.com