avatarKhuong Lân Cao Thai

Summary

This article provides a tutorial on calculating daily returns and volatility of stocks, using Pfizer and Moderna as examples during the Covid-19 pandemic, to understand investment risk.

Abstract

The article titled "How to Calculate the Daily Returns And Volatility of a Stock with Python" focuses on practical data analysis for stock investors. It guides readers through the process of using Python and its libraries, such as yfinance, to retrieve and analyze stock data for Pfizer and Moderna during the Covid-19 pandemic. The tutorial covers the calculation of daily returns, the visualization of these returns over time, and the computation of daily, monthly, and annual volatility to assess investment risk. The author emphasizes the importance of understanding stock oscillations and volatility, illustrated by the significant fluctuations in the pharmaceutical sector due to vaccine development. The conclusion encourages further exploration of stock metrics and invites readers to follow for more insights.

Opinions

  • The author believes that the current market conditions, influenced by factors such as the Ukraine war and inflation, present an opportunity to enhance stock data analysis skills with Python.
  • There is an opinion that yfinance is a recommended tool for beginners to start experimenting with stock data.
  • The article suggests that the volatility of a stock is a critical measure of investment risk, with higher volatility indicating higher risk.
  • The author implies that the visualization of daily returns is a more effective way to monitor the magnitude of stock price changes over time, compared to raw data.
  • There is a perception that Moderna's stock volatility reflects investors' uncertainty about the company's future revenue beyond Covid-19 vaccines.
  • The author hints at Pfizer's stability as a well-established pharmaceutical company, despite its significant annual volatility.
  • The conclusion expresses the author's view that it is crucial for investors to be cautious and to consider various metrics when making investment decisions.

How to Calculate the Daily Returns And Volatility of a Stock with Python

Let’s practice with Pfizer and Moderna stocks’ performance during this pandemic.

Photo by Wance Paleri from Unsplash

“Bubble market crash”, “Crypto krach”, “Recession”…If you are a stock investor, chances are high you are often checking your portfolio these last weeks. Global stock markets are going down in 2022 due to many factors: the Ukraine war, inflation, oil price rise, and rising interest rates among others.

This is the perfect opportunity to start leveling up our skills with stock data with Python.

Disclaimer: The purpose of this blog post is only to show how to calculate the daily returns and volatility of a stock. There is no investment advice or promotion for any stock.

Content:

  1. The use case
  2. Required Python libraries
  3. Retrieve stock data with yfinance
  4. Calculating and plotting daily returns
  5. Calculate the daily, monthly, and annually volatility of a stock
  6. Conclusion

1. The use case

The Covid-19 pandemic has provoked dramatic changes in the world. Stock markets are no exception to that. Thanks to the mRNA vaccines, Moderna and Pfizer have become household names and saw their revenues boosted.

What are the daily returns and volatility for these 2 companies’ stocks over that period?

This will give us an indication of their level of risk. The higher the volatility, the riskier it is.

2. Required Python libraries

First, let’s import the libraries we need.

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

yfinance is a free and open-source Python library created by Ran Aroussi. You can find more information about it here. I recommend using it to start playing with stock data.

3. Retrieve stock data with yfinance

It’s straightforward.

  • To retrieve stock data, I need to use the respective ticker symbols for Pfizer and Moderna: PFE, MRNA
  • Then I indicate the period with the download method.
Example with Pfizer stock
ticker= "pfe"
pfizer = yf.download(ticker, start="2020-01-01", end="2022-06-17")
pfizer.head()
First lines of Pfizer stock data with yfinance

4. Calculating and plotting daily returns

Stock daily returns indicate the gain or loss per day for a given stock. We get it by subtracting the opening price from the closing price.

Conveniently, Pandas has the pct_change method to calculate the percentage of changes in the daily returns. Let’s use it and store it in a new column “daily_returns”.

Let’s start with Pfizer:

pfizer['daily_returns']=(pfizer['Close'].pct_change())*100

As usual, I prefer plotting the results so it’s easier to visualize.

pfizer.dropna(inplace=True)
fig,ax=plt.subplots(figsize=(12,6))
ax.spines[['top','right','left','bottom']].set_visible(False)
plt.plot(pfizer['daily_returns'], label = 'Daily Returns')
plt.legend(loc='best')
plt.title('Pfizer Stock Daily Returns Over Time')
plt.show()

Due to Covid-19, Pfizer stock oscillation was very strong in 2020 and got less pronounced in 2021 thanks to the Covid vaccines. We can see at the end of 2021 positive daily returns linked to Omicron variant appearance. This plot helps us to monitor the magnitude of the daily change over time.

Now let’s do the same with Moderna and see how its daily returns plot looks like on the same period:

The oscillations have a higher magnitude on the positive side. From January-22, we observe that the daily returns are more on the negative side. This corresponds to a decrease in the stock price.

5. Calculate the daily, monthly, and annually volatility of a stock

A stock’s volatility is the variation in its price over a period of time.

Daily volatility: to get it, we calculate the standard deviation of the daily returns. As a reminder, the standard deviation helps us to see how much the data is spread around the mean or average.

Monthly volatility: we make the assumption that there are 21 trading days in the month so we multiply the daily volatility by the square root of 21.

Annual volatility: we assume there are 252 trading days in a calendar year and we multiply the daily volatility by the square root of 252.

Here is the code below:

import math
daily_volatility_pfe = pfizer['daily_returns'].std()
print('Daily volatility:')
print('Pfizer: ', '{:.2f}%'.format(daily_volatility_pfe))
daily_volatility_mrna = moderna['daily_returns'].std()
print('Moderna: ', '{:.2f}% \n'.format(daily_volatility_mrna))
monthly_volatility_pfe = math.sqrt(21) * daily_volatility_pfe
print('Monthly volatility:')
print ('Pfizer: ', '{:.2f}%'.format(monthly_volatility_pfe))
monthly_volatility_mrna = math.sqrt(21) * daily_volatility_mrna
print ('Moderna: ', '{:.2f}%\n '.format(monthly_volatility_mrna))
annual_volatility_pfe = math.sqrt(252) * daily_volatility_pfe
print('Annual volatility:')
print ('Pfizer: ', '{:.2f}%'.format(annual_volatility_pfe ))
annual_volatility_mrna = math.sqrt(252) * daily_volatility_mrna
print ('Moderna: ', '{:.2f}%'.format(annual_volatility_mrna ))

Moderna stock had very high volatility: 90% annual and 26% monthly! This shows that investors have difficulty gauging the company as its revenue is for now based on Covid-19 vaccines. They are waiting to see if its potential will materialize.

Pfizer’s one on annual basis is 31% which is lower than Moderna but still significant. Pfizer is a huge pharma company with a lot of history.

6. Conclusion

It’s easy and accessible to get stock data and do some first calculations to evaluate the risk. The example of Moderna and Pfizer stocks shows how careful we need to be when investing in stocks. I will treat other metrics in future blog posts.

Thanks for reading me! Hit the follow button to read my future posts if you like them.

You can also find me on LinkedIn here.

Data Science
Python
Finance
Stock Market
Time Series Analysis
Recommended from ReadMedium