Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 4

Measuring Volatility

Recommended resources

Hello! In our previous lessons, we've done the essential work of preparing a clean, time-aligned, and fully adjusted historical price series. With this reliable data as our foundation, we can now move on to one of the most fundamental concepts in quantitative finance: measuring risk.

This lesson introduces volatility, which is the standard measure for the magnitude of price fluctuations in an asset. You will learn what historical and rolling volatility are, why they are indispensable for any trading system, and how to calculate them efficiently in Python. Understanding volatility is the first step toward quantifying risk, which will inform everything from how you size your positions to the very logic of your trading strategies.

What is Volatility?

In simple terms, volatility measures how much an asset's price swings around its average. A highly volatile stock sees large, rapid price changes, while a low-volatility stock tends to be much more stable. For a trader, volatility is synonymous with both risk and opportunity.

Finance professionals distinguish between two main types of volatility:

  1. Historical Volatility: This is a backward-looking measure calculated from past price data. It tells us how volatile an asset has been.
  2. Implied Volatility: This is a forward-looking measure derived from options prices. It represents the market's consensus on how volatile an asset is expected to be in the future.

In this lesson, we will focus exclusively on historical volatility, as it's a critical component for backtesting and risk management that can be calculated directly from the price data we've already prepared.

To get a formal handle on the concept, please begin by reading the introductory sections of the SimTrade blog post on Historical Volatility.

Historical Volatility - SimTrade blog

This article clearly defines volatility and explains the foundational steps for its calculation, starting with returns.

Please read the first two main sections: The Introduction, which defines volatility and differentiates between historical and implied volatility. The section on Returns, which explains why we use logarithmic returns for these calculations—a concept that builds on our first lesson.


The Calculation: From Returns to Volatility

As the article highlights, volatility is not calculated on prices, but on returns. Specifically, it is the standard deviation of the logarithmic returns over a certain period. The process involves three main steps:

  1. Calculate Logarithmic Returns: For each period (e.g., daily), calculate the log return: .
  2. Calculate Standard Deviation: Compute the standard deviation of these returns over a chosen lookback window.
  3. Annualize the Volatility: Scale the result to an annual figure for comparability.

The standard deviation gives us the volatility for the period of the returns (e.g., daily volatility from daily returns). To make it meaningful and comparable across different assets and timeframes, we annualize it. This is done by multiplying the daily volatility by the square root of the number of trading days in a year, which is conventionally taken as 252.

The SimTrade article provides a clear walkthrough of this.

Historical Volatility - SimTrade blog

This part of the article walks through the statistical formula and the crucial step of annualization.

Continue reading the next three subsections: Standard deviation of the distribution of returns, which presents the formula for the standard deviation of returns. Annualized volatility, explaining the "square-root of time" rule for scaling. The first part of the section titled Historical Volatility, which summarizes the formula for annualized historical volatility.


From Theory to Practice: Rolling Volatility in Python

Calculating a single volatility number over your entire dataset (unconditional volatility) gives you a long-term average, but it's not very useful for active trading. Volatility is not static; it changes over time, with quiet periods followed by turbulent ones. To capture this dynamic nature, we use a rolling volatility.

A rolling volatility is calculated using a moving window. For example, a 21-day rolling volatility would, for each day, calculate the standard deviation of the log returns of the preceding 21 trading days. This gives us a time series of volatility, allowing us to see how risk is evolving.

Given your proficiency in Python, you'll find the pandas library makes this calculation incredibly straightforward. The following video by Matt Macarty provides a concise demonstration of the .rolling() method, which is the core of this technique.

Python Pandas || Moving Averages and Rolling Window Statistics for Stock Prices

This video shows the practical steps in Python to calculate log returns and then apply a rolling standard deviation.

Please watch the segment from this timestamp. The author first calculates logarithmic returns and then computes a 21-day rolling historical volatility using .rolling(21).std(). Note how he also uses .shift(1) to avoid lookahead bias, ensuring that the volatility for a given day is calculated using data available before that day starts.

Combining what you've learned, the complete process in pandas is:

  1. Calculate log returns: log_returns = np.log(df['Adjusted Close'] / df['Adjusted Close'].shift(1))
  2. Calculate rolling annualized volatility: rolling_vol = log_returns.rolling(window=21).std() * np.sqrt(252)

The image below shows both the Python code for this calculation and the resulting plot. This is exactly the kind of output you can now generate to visualize how an asset's risk profile has changed over time.

This image demonstrates the Python code used to calculate 21-day annualized rolling volatility and the corresponding line plot, showing significant volatility spikes, such as the one in early 2020.

An Improvement: Exponentially Weighted Moving Average (EWMA)

The simple rolling window (a Simple Moving Average, or SMA) has one notable drawback: a single large return shock will stay in the calculation for the entire window length and then abruptly disappear, causing a sudden drop in the volatility reading even if nothing happened in the market on that day. This is sometimes called a "ghosting" or "leverage" effect.

A more responsive and widely-used method is the Exponentially Weighted Moving Average (EWMA). EWMA calculates the standard deviation by giving more weight to recent returns and exponentially less weight to older ones. This means shocks fade out smoothly, and the volatility estimate adapts more quickly to new market information.

The EODHD article "Estimate Volatility with SMA and EWMA in Python" provides an excellent comparison of these two approaches.

Estimate Volatility with SMA and EWMA in Python

This article explains the main limitation of simple rolling volatility and presents EWMA as a more robust alternative, complete with Python code.

Focus on these key sections: Read the paragraph in the "An Introduction to Simple Moving Averages" section that describes the leverage effect. This is the core problem with the simple rolling window. Read the introduction to "Exponentially Weighted Moving Averages" to understand how EWMA assigns weights. Skim the Python code sections for both SMA Volatility Estimates and EWMA Volatility Estimates. You can implement EWMA in pandas very easily with the .ewm() method, for example: log_returns.ewm(span=21).std() * np.sqrt(252). Finally, read A final comparison and the Conclusion to solidify the differences between the two methods.

For most quantitative trading applications, EWMA-based volatility is preferred over the simple rolling window due to its responsiveness and smoother decay.


Why This Matters for Your Trading System

Measuring volatility isn't just an academic exercise. It's a practical tool that directly informs trading decisions. By quantifying the market's current risk level, you can:

  • Adjust Position Size: Take smaller positions in highly volatile markets and larger positions in calmer ones. This is known as "volatility targeting" and is a powerful risk management technique we will cover later.
  • Filter Trading Signals: Some strategies work best in low-volatility, mean-reverting environments, while others (like breakouts) thrive on high volatility. You can use a volatility measure as a filter to turn your strategy on or off.
  • Set Dynamic Exits: Stop-loss and take-profit levels can be set as a multiple of the current volatility (e.g., place a stop at 2x the daily volatility), making them adapt to changing market conditions.

The plot below shows a practical application of this idea, where predicted volatility is used to define different trading regimes, each with a different level of capital exposure.

This chart illustrates how an asset's predicted volatility can be divided into regimes (low, medium, high). A trading system could then be designed to adjust its exposure—for example, using 2x leverage in low volatility, 1x in medium, and holding no position in high volatility.

Conclusion

In this lesson, you have learned how to measure and interpret one of the most critical metrics in finance.

Here are the key takeaways:

  • Volatility is the standard deviation of an asset's logarithmic returns and is the primary measure of its price risk.
  • Volatility is annualized by multiplying the daily volatility by the square root of 252, allowing for standardized comparisons.
  • Rolling volatility provides a dynamic view of how an asset's risk evolves over time, which is far more useful for trading than a single static value.
  • EWMA-based volatility is generally superior to a simple rolling window because it adapts more quickly to new information and avoids the abrupt "ghosting" effect of old data points dropping out of the window.
  • Measuring volatility is a cornerstone of risk management, influencing position sizing, strategy filtering, and exit placement.

You have moved from simply processing data to extracting a meaningful risk metric from it. In our next lesson, we will explore another crucial aspect of risk: drawdown. While volatility measures the general magnitude of price swings, drawdown measures the specific pain of a losing streak from a portfolio's peak to its trough.