Learn how to calculate standard deviation with Part I.
Standard deviation in trading as a measure of volatility
In trading and finance, it is important to quantify the volatility of an asset. An asset’s volatility, unlike its return or price, is an unobserved variable.
Standard deviation has a special significance in risk management and performance analysis as it is often used as a proxy for the volatility of a security. For example, the well-established blue-chip securities have a lower standard deviation in their returns compared to that of small-cap stocks.
On the other hand, assets like cryptocurrency have a higher standard deviation, as their returns vary widely from their mean.
Moving forward, let us discuss the computation of the annualised volatility of stocks using Python.
Computing annualised volatility of stocks using Python
Let us now compute and compare the annualized volatility for two Indian stocks namely, ITC and Reliance. We begin with fetching the end of day close price data using the yfinance library for a period of the last 5 years:
import yfinance as yf import warnings warnings.filterwarnings('ignore') # Download the data for ITC and RELIANCE stocks using yahoo finance library itc_df = yf.download('ITC.NS', period = '5y')[['Adj Close']] reliance_df = yf.download('RELIANCE.NS', period = '5y')[['Adj Close']] # Taking a peek at the fetched data itc_df.tail()
import_lib_download_data.py hosted with ❤ by GitHub
Output:
Date Adj Close 2021-10-19 245.949997 2021-10-20 246.600006 2021-10-21 244.699997 2021-10-22 236.600006 2021-10-25 234.350006
reliance_df.tail()
show_data.py hosted with ❤ by GitHub
Output:
Date Adj Close 2021-10-19 2731.850098 2021-10-20 2700.399902 2021-10-21 2622.500000 2021-10-22 2627.399902 2021-10-25 2607.300049
Below, we calculate the daily returns using the pct_change() method and the standard deviation of those returns using the std() method to get the daily volatilities of the two stocks:
# Compute the returns of the two stocks itc_df['Returns'] = itc_df['Adj Close'].pct_change() reliance_df['Returns'] = reliance_df['Adj Close'].pct_change() print(reliance_df[['Adj Close','Returns']])
compute_ret.py hosted with ❤ by GitHub
Output:
Date Adj Close Returns 2016-10-25 511.991608 NaN 2016-10-26 508.709717 -0.006410 2016-10-27 506.127686 -0.005076 2016-10-28 509.144104 0.005960 2016-11-01 507.237701 -0.003744 ... ... ... 2021-10-19 2731.850098 0.008956 2021-10-20 2700.399902 -0.011512 2021-10-21 2622.500000 -0.028848 2021-10-22 2627.399902 0.001868 2021-10-25 2607.300049 -0.007650
# Compute the standard deviation of the returns using the pandas std() method daily_sd_itc = itc_df['Returns'].std() daily_sd_rel = reliance_df['Returns'].std() reliance_df.dropna(inplace=True) reliance_df.head()
compute_sd_ret.py hosted with ❤ by GitHub
Output:
Date Adj Close Returns 2016-10-26 508.709717 -0.006410 2016-10-27 506.127686 -0.005076 2016-10-28 509.144104 0.005960 2016-11-01 507.237701 -0.003744 2016-11-02 494.086243 -0.025928
In general, the volatility of assets is quoted in annual terms. So below, we convert the daily volatilities to annual volatilities by multiplying with the square root of 252 (the number of trading days in a year):
import numpy as np # Annualized standard deviation annualized_sd_itc = daily_sd_itc * np.sqrt(252) annualized_sd_rel = daily_sd_rel * np.sqrt(252) print(f'The annualized standard deviation of the ITC stock daily returns is: {annualized_sd_itc*100:.2f}%') print(f'The annualized standard deviation of the Reliance stock daily returns is: {annualized_sd_rel*100:.2f}%')
annualized_sd.py hosted with ❤ by GitHub
Output:
The annualized standard deviation of the ITC stock daily returns is: 27.39% The annualized standard deviation of the Reliance stock daily returns is: 31.07%
Now we will compute the standard deviation with Bessel's correction. To do this, we provide a ddof parameter to the Numpy std function. Here, ddof means ‘Delta Degrees of Freedom'.
By default, Numpy uses ddof=0 for calculating standard deviation- this is the standard deviation of the population. For calculating the standard deviation of a sample, we give ddof=1, so that in the formula, (n−1) is used as the divisor. Below, we do the same:
# Compute the standard deviation with Bessel's correction daily_sd_itc_b = itc_df['Returns'].std(ddof=1) daily_sd_rel_b = reliance_df['Returns'].std(ddof=1) # Annualized standard deviation with Bessel's correction annualized_sd_itc_b = daily_sd_itc_b * np.sqrt(252) annualized_sd_rel_b = daily_sd_rel_b * np.sqrt(252) print(f'The annualized standard deviation of the ITC stock daily returns with Bessel\'s correction is: {annualized_sd_itc_b*100:.2f}%') print(f'The annualized standard deviation of the Reliance stock daily returns with Bessel\'s correction is: {annualized_sd_rel_b*100:.2f}%')
Bessel's_corr.py hosted with ❤ by GitHub
Output:
The annualized standard deviation of the ITC stock daily returns with Bessel's correction is: 27.39% The annualized standard deviation of the Reliance stock daily returns with Bessel's correction is: 31.07%
Thus, we can observe that, as the sample size is very large, Bessel's correction does not have much impact on the obtained values of standard deviation. In addition, based on the given data, we can say that the Reliance stock is more volatile compared to the ITC stock.
Note: The purpose of this illustration is to show how standard deviation is used in the context of the financial markets, in a highly simplified manner. There are factors such as rolling statistics (outside the scope of this write-up) that should be explored when using these concepts in strategy implementation.
Stay tuned for the next installment to learn about z-score.
Author: Chainika Thakar (Originally written by Ashutosh Dave and Udisha Alok)
Originally posted on QuantInsti blog.
Disclosure: Interactive Brokers
Information posted on IBKR Campus that is provided by third-parties does NOT constitute a recommendation that you should contract for the services of that third party. Third-party participants who contribute to IBKR Campus are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.
This material is from QuantInsti and is being posted with its permission. The views expressed in this material are solely those of the author and/or QuantInsti and Interactive Brokers is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to buy or sell any security. It should not be construed as research or investment advice or a recommendation to buy, sell or hold any security or commodity. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.
Disclosure: Digital Assets
Trading in digital assets, including cryptocurrencies, is especially risky and is only for individuals with a high risk tolerance and the financial ability to sustain losses. Eligibility to trade in digital asset products may vary based on jurisdiction.
Join The Conversation
If you have a general question, it may already be covered in our FAQs. If you have an account-specific question or concern, please reach out to Client Services.