paint-brush
How To Retrieve Company Data With Python and yfinanceby@codingandfun
1,788 reads
1,788 reads

How To Retrieve Company Data With Python and yfinance

by CodingandFunMay 11th, 2021
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Python offers very good libraries for data science. By learning 3 or 4 libraries we can do almost all kind of analysis. Yfinance is a great tool that lets us retrieve financial data from Yahoo Finance. With four lines of code, we are able to retrieve 1 year of historical prices from Apple. Pandas make the calculation of moving averages super straightforward. We can also use Pandas to calculate and plot Apple cumulative returns using the pct_change and cumsum methods. This is perfect for comparing how companies are performing relative to others.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - How To Retrieve Company Data With Python and yfinance
CodingandFun HackerNoon profile picture

My journey with Python started a few years back. I am not a developer but I decided to start learning Python for one single reason. The great potential that it offers for financial analysis. In this story, I intend to show you a few examples on how great Python is for financial analysis.

Why I decided to start learning Python?

I have a financial background and before learning Python my analysis routine was quite boring. I had to access different internet sites to manually retrieve company fundamentals and market data. Then, I collected and consolidated that data into an Excel file to perform some analysis.

Well, after a while of doing that, I had more than enough of the tedious manual work. That is why I decided to learn Python and automate as much as possible of my financial analysis.

While I was learning Python, I could not find much content related to Python for Finance. Therefore, I decided to share part of the aquired knowledge with the world. In this article, I want to show some of the great capabilities that Python offers for colleting and processing financial data.

Hopefully, I can help you see the great value of learning Python even if you do not having a programming background.

Retrieving Market Data with Python

Python offers very good libraries for data science. By learning 3 or 4 libraries we can do almost all kind of analysis. Feel free to have a look at my top 5 Python libraries for Financial Analysis. If you are new to Python, I recommend you to start learning Pandas.

Good, let's start with some coding. I will be using the yfinance library to retrieve historical prices and some other financial data. Yfinance is a great tool that lets us retrieve financial data from Yahoo Finance. It is super easy to use as well.

Note that if it is the first time using yfinance, you will have to install the library using below pip command in your terminal:

pip install yfinance

Historical Prices and Moving Averages

As shown below, the library is super easy to use. With four lines of code, we are able to retrieve 1 year of historical prices from Apple. Feel free to change the ticker to any other company of your interest.

import matplotlib.pyplot as plt
import yfinance as yf

aaple = yf.Ticker("AAPL")
prices = aaple.history(period="1y")

Note that we have used the yf.Ticker and the history method to retrieve historical prices. This returns the historical prices in a Pandas DataFrame format. That is perfect since we can start using Pandas to transform the data:

For example, with four new lines of codes and the power of Pandas and Matplotlibt, we are able to calculate the Apple 20 days and 200 days Moving Averages. Pandas make the calculation of moving averages super straightforward. We only need to use the rolling method.

import matplotlib.pyplot as plt
import yfinance as yf

aaple = yf.Ticker("AAPL")
prices = aaple.history(period="1y")

prices['20d'] = prices['Close'].rolling(20).mean()
prices['200d'] = prices['Close'].rolling(200).mean()

prices[['Close','20d','200d']].plot()
plt.title('Moving Averages Apple')

Calculate and Plot Cumulative Returns

We can also use Pandas to calculate and plot Apple cumulative returns using the pct_change and cumsum methods.

Pct_change will calculate the daily returns. Then, we use cumsum method in order to get the cumulation of all daily returns included in our selected time period.

import matplotlib.pyplot as plt
import yfinance as yf

aaple = yf.Ticker("AAPL")
prices = aaple.history(period="1y")

prices['daily_return'] = prices['Close'].pct_change()
prices['cumulative_return'] = prices['daily_return'].cumsum()

prices['cumulative_return'].plot()
plt.title('Cumulative Return Apple')

Retrieving Historical Prices for Multiple Companies

We can also use yfinance to retrieve historical prices for multiple companies. This is perfect for comparing how companies are performing relative to others.

Similarly to the previous sections, we only need a few lines of code in order to retrieve all historical prices for all companies. Here, we use a for-loop in order to retrieve each of the stock prices. Then, we append them in a Python list and convert it into a DataFrame :

import pandas as pd 
import matplotlib.pyplot as plt
import yfinance as yf

stocks =['AAPL','MSFT','FB','GME','TSLA','AMZN']
stock_list = []
for stock in stocks:
  returns = yf.Ticker(stock)
  returns = returns.history(period="1y")
  returns['returns'] =  returns['Close'].pct_change()

  returns.rename(columns={'returns': stock}, inplace=True)
  returns = returns[stock]
  stock_list.append(returns)

all_stock_returns =pd.DataFrame(stock_list).T
all_stock_returns

Wrapping Up and More Python for Finance

I really hope that you have found the story interesting and that now you feel motivated to keep learning. If you are a beginner, I encourage you to keep going and soon you will be able to code amazing programs or analyze data.

If you feel Python for Finance interesting, I have a blog where I share a lot of examples on how to retrieve and analyse financial data with Python.