Stock Information Retrieval in Python

If you have read my other posts about stock information retrieval, then you’ll be happy to know there is a MUCH simpler way to get the information you want in fewer lines of code. This code is easier to read and takes less time to process. If you have not read my other posts, then you’re in luck because you get to skip to the easy version!

In my previous method to retrieve information, I created a web scraper that would take all the information from Yahoo Finance’s web page. Although it was not the easiest thing to make, it worked. I initially looked for a Yahoo Finance API but could not find it, so I created the web scraper. I was happy with what I had because it got me the information I needed.

After some time, I finally found how to access theYahoo Finance API with ease, and web scraping was not needed. I’m pleasantly surprised with how easy this was and hope it helps you too.

First, import the necessary libraries.

Set a start and end variable. These variables will represent the date range from which you want to pull information. My start variable is 2019–01–01 (YEAR-MONTH-DAY). My end variable is today’s date (Jan 8, 2021).

Now we will create a user-friendly system to pull information from any stock on the Yahoo Finance API. x is my input variable, so I can enter the stock's name by its listing name(Tesla is TSLA, Amazon is AMZN). pandas_datareader is used to access the API. the name of the stock is the first parameter, followed by which website, the first date, and the last date. The final lime is saving the information as a CSV file as the stock name. I like the input method because then you do not have to enter the name of the stock in the first parameter or change what it will be saved as.

Now enter the stock you want to see. PLNT is Planet Fitness.

Check to see if it worked by reading in the CSV information, and we see new year’s day is not included. That is because the NYSE is closed that day, and there is no information to be pulled.

If you’ve read my other SMA posts, there is a code about how to graph your information.

Data Scientist

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store