How to compute volatility in Python

2 min

Measuring volatility is quite a big question in financial analysis. Since it measures movement, the estimate will become better as your number of observations grows. (e.g. instead of daily you have it hourly)

One cheap approximation is to measure volatility using the standard deviation.

Here is the standard deviation formula.

The standard deviation formula

In order to evaluate whether an asset has been volatile in the past, a rolling standard deviation can be used to approximate the historical volatility.

Real world example

Let's take APPLE stock price 7 days standard deviation based on the close price as a proxy for historical volatility.

In order to get our stock prices data we use the yfinance library that utilizes yahoo finance to directly fetch financial data and transform it into a Pandas DataFrame.

# In order to get Apple stock price data from yahoo
import yfinance as yf

# We download the stock price from start date until end date
df ="AAPL", start="2021-01-01", end="2021-06-01")
Getting AAPL stock price data

Computing historical volatility

Here we compute the 7 days historical volatility using the pandas .rolling() method.

We can specify the number of periods we want to apply a method on.

Here we've put 7 in order to have the past 7 days' historical daily returns.

We then apply the standard deviation method .std() on the past 7 days and thus compute our historical volatility.

df["7d_vol"] = df["Close"].pct_change().rolling(7).std()
We compute the historical volatility using a rolling mean and std

Plotting historical volatility

In order to see if we did a good job when computing historical volatility, we can easily plot it using the .plot() function

df["7d_vol"].plot(title="7 days close price historical volatility")
The plot that shows the 7 days historical volatility

Here you are! A lot of concepts to take in, but you will see it will get easier over time. Take your time.