How To Download A Real Stock Into Python
This article was published as a part of the Data Science Blogathon
Introduction
The article aims to empower you to create your projects by learning how to create your data frame and collect data most the stock market place and the crypto market from the internet and then base your code on it. This will permit you to create your ML models and experiment with real-earth data.
In this commodity, I will demonstrate 2 methods and both use Yahoo Finance as the data source since it is free and no registration is required. You can use any other data source like Quandi, Tiingo, IEX Cloud, and more.

Getting Gear up
In the starting time approach, we will consider the finance module in python and it is a very easy module to work with. The other module nosotros will talk about is yahoofinancials which requires extra attempt but gives back a whole lot of actress data in return. Nosotros will discuss that after and now we will brainstorm by importing the required modules into our lawmaking.
Initial Setup:
We need to load the following libraries:
import pandas as pd import yfinance equally yf from yahoofinancials import YahooFinancials
If you lot practise not have these libraries, yous can install them via pip.
!pip install yfinance !pip install yahoofinancials
First Method: How to apply yfinance
It was previously known equally 'fix_yahoo_finance' but afterwards information technology transformed into a module of its own but it is not an official one past Yahoo. The module 'yfinance' is at present a very popular library that is very python friendly and can be used as a patch to pandas_datareader or a standalone library in itself. It has many potential uses and many people apply it to download stock prices and also crypto prices. Without any further delay, allow u.s. execute the post-obit code. We will begin past downloading the stock price of 'Apple tree'
Lawmaking :
aapl_df = yf.download('AAPL', start='2019-01-01', stop='2021-06-12', progress=Imitation, ) aapl_df.head()
Output :

The information interval is gear up to 1 day but the internal can be externally specified with values like 1m,5m,15m,30m,60m,1h,1d,1wk,1mo, and more. The in a higher place command for downloading the data shows a beginning and an end engagement only you tin can too simply download the data with the code given below :
Code :
aapl_df = yf.download('AAPL')
Output :

In that location are many parameters of the download function which you lot can find in the documentation and start and end are some of the nigh common ones to be used. Since the information was pocket-sized, the progress bar was set to faux and showing it makes no sense and should be used for high volume or data.
We tin can also download multiple stock prices of more than than one asset at in one case. Past providing a list of visitor names in a list format ( eg. ['FB',' MSFT','AAPL'] )as the tickers argument. We tin also provide an additional statement which is automobile-suit=True, so that all the electric current prices are adjusted for potential corporate actions similar splits.
Apart from the yf.download function, we tin can as well utilise the ticker module and you can execute the beneath code to download the terminal 5year stock prices of Apple.
Code :
ticker = yf.Ticker('AAPL') aapl_df = ticker.history(period="5y") aapl_df['Close'].plot(title="APPLE's stock toll")
Output :

The one reward of using a ticker module is that the multiple methods which are connected to information technology can exist exploited. The available methods we can employ are :
-
info– This method prints out a JSON formatter output which contains a lot of data about the visitor starting from their business concern full proper noun, summary, industry, exchanges listed on with country and time zone, and more. Information technology as well comes equipped with the beta coefficient.
-
recommendations – This method contains a historical list of recommendations made by different analysts regarding the stock and whether to buy sell or give suggestions on it.

-
deportment – This displays the actions like splits and dividends.

-
major_holders – This method displays the major holders of the share forth with other relevant details.

-
institutional_holders – This method shows all the institutional holders of a item share.

-
calendar – This function shows all the incoming events such as the earnings and you can even add this to your google calendar through code. Basically, it shows the important dividend dates for a company.

If you still desire to explore more regarding the working of the functions, y'all tin can check out this GitHub repository of yfinance.
Second Method: How to use yahoofinancials?
The 2d method is to utilize the yahoofinancials module which is a bit tougher to piece of work with only it provides much more information than yfinance. We will begin by downloading Apple tree's stock prices.
To do this we volition first pass an object of YahooFinancials bypassing the Employ ticker name so utilise a diversity of important information to get out the required information. Here the returned data is in a JSON format and hence nosotros exercise some beautification to it so that it tin be transformed into a DataFrame to display it properly.
Code :
yahoo_financials = YahooFinancials('AAPL') information = yahoo_financials.get_historical_price_data(start_date='2019-01-01', end_date='2019-12-31', time_interval='weekly') aapl_df = pd.DataFrame(data['AAPL']['prices']) aapl_df = aapl_df.drop('date', centrality=one).set_index('formatted_date') aapl_df.head()
Output :

Coming down on a technical level, the process of obtaining a historical stock price is a bit longer than the case of yfinance but that is mostly due to the huge book of data. At present nosotros move onto some of the important functions of yahoofinancials.
-
get_stock_quote_type_data() – This method returns a lot of generic information about a stock which is similar to the yfinance info() function. The output is something like this.
-
get_summary_data() – This method returns a summary of the whole company along with useful data like the beta value, toll to book value, and more than.
-
get_stock_earnings_data() – THis method returns the information on the quarterly and yearly earnings of the company along with the next appointment when the company will report its earnings.
-
get_financial_stmts() – This is another useful method to retrieve financial statements of a company which is useful for the analysis of a stock
-
get_historical_price_data() – This is a method similar to the download() or Ticker() function to become the prices of stock with start_date, end_date and interval ranges.
The above module tin also be used to download company data at once like yfinance and cryptocurrency information tin can also exist downloaded equally shown in the following code.
Code :
yahoo_financials = YahooFinancials('BTC-USD') data=yahoo_financials.get_historical_price_data("2019-07-ten", "2021-05-30", "monthly") btc_df = pd.DataFrame(data['BTC-USD']['prices']) btc_df = btc_df.driblet('engagement', axis=1).set_index('formatted_date') btc_df.head()
Output :

For more than details about the module, you can cheque out its GitHub Repository.
EndNotes
The full information is ultimately sourced from Yahoo Finance and at present yous know how to import whatsoever stock or cryptocurrency cost and information dataset into your lawmaking and begin exploring and experimenting with them. Good luck with your adventures and feel gratuitous to share your code with me on LinkedIn or feel gratis to reach out to me in case of whatever doubts or errors.
Cheers for reading till the finish. Promise you are doing well and stay condom and are getting vaccinated soon or already are.
About the Author :
Arnab Mondal
Information Engineer & Python Developer | Freelance Tech Writer
Link to my other articles
DOWNLOAD HERE
Posted by: rolleritaind.blogspot.com