Lesson 14 · Real-World Data Analytics
Rolling Volatility, Sharpe Ratio & Drawdown in Python | Data Analytics #14
Risk isn't constant. We measure how Apple and Tesla risk changes over time in Python with rolling volatility, rolling Sharpe and Sortino ratios, drawdowns,…
- CourseReal-World Data Analytics
- Lesson14 of 100
- FormatJupyter notebook · 30 code cells
- Data1 dataset
What you'll learn
Datasets used in this lesson
Save these next to the notebook. In Google Colab, upload them with the 📁 icon on the left first.
- aapl_tsla_merged.csv preview17.9 KB
📓 Full notebook
Download .ipynbData Analytics 100, Video 14: Volatility Analysis and Rolling Risk Metrics#
- Video fourteen of the hundred-video real-world data analytics series.
- Measuring real risk itself as it changes over time, using rolling windows on real Apple and real Tesla returns.
- Let's get into it.
This lesson is for learners who can already calculate a single volatility or Sharpe figure and want to see how those numbers change over time. The business question: is a stock's risk steady, or does it come in waves, and how should an analyst track that so a risk report reflects current conditions rather than a long-run average?
You reuse aapl_tsla_merged.csv, the aligned Apple and Tesla table from earlier in this domain: 338 shared trading days from October 2015 to February 2017 with daily returns (AAPL_Return, TSLA_Return) and the cumulative growth column AAPL_Cumulative.
In this lesson you will:
- Compute 20-day and 60-day rolling volatility and test for volatility clustering
- Build rolling Sharpe, downside deviation and rolling Sortino ratios
- Flag high-volatility regimes and compare returns inside them
- Measure rolling maximum drawdown, EWMA volatility and historical Value-at-Risk
Prerequisites: you should be comfortable with rolling(), standard deviation and annualising with 252 trading days, all covered in the earlier finance lessons.
Part 1: Risk Is Not Constant#
Every risk figure you have calculated so far has been one number for the whole period, which hides calm and stormy stretches. This lesson makes risk time-varying. The code reloads the merged Apple and Tesla table with parse_dates=['Date'] so dates are real datetimes, and checks the row count. The output shows 338 shared trading days, matching the merged table saved earlier. Rolling calculations lose rows at the start of the series, so it helps to know the full count before you begin.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
merged = pd.read_csv('aapl_tsla_merged.csv', parse_dates=['Date'])
merged.shape[0]
Part 2: Real 20-Day Rolling Volatility#
Rolling volatility answers the question: how risky was this stock over the last month? The code uses .rolling(20).std() on daily returns, roughly one trading month, and multiplies by np.sqrt(252) to annualise. The first 20 values are NaN, so after .dropna() the first shown date is 2015-11-12, when Apple's 20-day volatility was 0.282 (28.2%) and Tesla's 0.577 (57.7%). Both are well above their full-period averages, which suggests a turbulent autumn in 2015.
merged['AAPL_Vol20'] = merged['AAPL_Return'].rolling(20).std() * np.sqrt(252)
merged['TSLA_Vol20'] = merged['TSLA_Return'].rolling(20).std() * np.sqrt(252)
merged[['Date', 'AAPL_Vol20', 'TSLA_Vol20']].dropna().head(3).round(3)
Part 3: Real 60-Day Rolling Volatility#
Window length is a trade-off: short windows react quickly but are noisy, long windows are steady but slow. The code adds a 60-day version, about three months, and then compares the two Apple measures with .corr(). The output shows a correlation of 0.642 between the 20-day and 60-day volatility. They broadly agree, but far from perfectly, so the window you pick changes what your risk report says on any given day. Mention the window length whenever you quote a rolling figure.
merged['AAPL_Vol60'] = merged['AAPL_Return'].rolling(60).std() * np.sqrt(252)
merged['TSLA_Vol60'] = merged['TSLA_Return'].rolling(60).std() * np.sqrt(252)
merged[['AAPL_Vol20', 'AAPL_Vol60']].dropna().corr().round(3)
Part 4: Real Rolling Volatility Summary Stats#
Summary statistics show the typical level and range of risk, not just its latest value. The code runs .describe() on both 20-day volatility series. Apple's output, shown first, has a mean of 0.218 and ranges from 0.077 to 0.430, so its risk varied more than fivefold. The second output shows Tesla's mean at 0.362, with a range from 0.163 to 0.736. Even Tesla's calmest month was riskier than Apple's average month at the 25th percentile of 0.161, and Tesla's peak almost doubles Apple's.
aapl_vol_summary = merged['AAPL_Vol20'].dropna().describe().round(3)
tsla_vol_summary = merged['TSLA_Vol20'].dropna().describe().round(3)
aapl_vol_summary
tsla_vol_summary
Part 5: Visualizing Real Rolling Volatility#
A chart makes risk regimes obvious in a way that tables cannot. The code plots both 20-day volatility series against date on the same axes, labels them for the legend and saves the figure to rolling_volatility.png, so nothing is shown inline. When you open it, look for the spikes: periods where both lines jump together point to market-wide stress, while a spike in only one line points to news about that company.
plt.figure(figsize=(11, 6))
plt.plot(merged['Date'], merged['AAPL_Vol20'], label='Real Apple 20-Day Vol')
plt.plot(merged['Date'], merged['TSLA_Vol20'], label='Real Tesla 20-Day Vol')
plt.xlabel('Real Date')
plt.ylabel('Real Annualized Volatility')
plt.title('Real Rolling 20-Day Volatility, Apple vs Tesla')
plt.legend()
plt.tight_layout()
plt.savefig('rolling_volatility.png', dpi=120)
plt.close()
Part 6: Real Volatility Clustering Check#
Volatility clustering means calm days tend to follow calm days and turbulent days follow turbulent ones. The code tests this by shifting Apple's 20-day volatility back one day with shift(-1), aligning the two series on the same index with .loc, and correlating today with tomorrow. The output is 0.967, very high. Part of this is built in, since two consecutive 20-day windows share 19 days, but it still shows why recent volatility is a reasonable first guess for the near future.
vol_today = merged['AAPL_Vol20'].dropna()
vol_next_day = vol_today.shift(-1).dropna()
aligned_today = vol_today.loc[vol_next_day.index]
round(aligned_today.corr(vol_next_day), 3)
Part 7: Real Rolling Sharpe Ratio#
A rolling Sharpe ratio shows whether the reward for taking risk was good recently, not just on average. The code annualises the 20-day mean return with * 252 and divides by the matching 20-day annualised volatility, with no risk-free rate subtracted. The last rows show Apple at 6.79 to 7.07 and Tesla dropping from 10.10 to 4.66 in three days. These values look huge because a strong month, annualised, implies an unrealistic yearly return. Treat short-window Sharpe ratios as a direction indicator, not a forecast.
aapl_roll_return20 = merged['AAPL_Return'].rolling(20).mean() * 252
merged['AAPL_RollSharpe20'] = aapl_roll_return20 / merged['AAPL_Vol20']
tsla_roll_return20 = merged['TSLA_Return'].rolling(20).mean() * 252
merged['TSLA_RollSharpe20'] = tsla_roll_return20 / merged['TSLA_Vol20']
merged[['Date', 'AAPL_RollSharpe20', 'TSLA_RollSharpe20']].dropna().tail(3).round(2)
Part 8: Visualizing Real Rolling Sharpe Ratio#
Plotting the rolling Sharpe ratios shows how quickly risk-adjusted performance swings. The code draws both series with a dashed zero line from axhline(0) and saves the chart to rolling_sharpe.png; there is no inline output. When you open it, look at how often each line crosses zero, meaning a month of losses, and how extreme the peaks and troughs get. That jumpiness is a reminder that a single Sharpe figure from a short period is very unreliable.
plt.figure(figsize=(11, 5))
plt.plot(merged['Date'], merged['AAPL_RollSharpe20'], label='Real Apple Rolling Sharpe')
plt.plot(merged['Date'], merged['TSLA_RollSharpe20'], label='Real Tesla Rolling Sharpe')
plt.axhline(0, color='gray', linestyle='--')
plt.xlabel('Real Date')
plt.ylabel('Real Rolling Sharpe Ratio')
plt.title('Real Rolling 20-Day Sharpe Ratio, Apple vs Tesla')
plt.legend()
plt.tight_layout()
plt.savefig('rolling_sharpe.png', dpi=120)
plt.close()
Part 9: Real Downside Deviation#
Standard deviation counts big up days as risk, which investors rarely complain about. Downside deviation looks only at losing days. The helper defines an inner function that keeps returns below zero, takes their .std(), annualises it, and returns NaN if there are fewer than two losses. rolling(window).apply(..., raw=False) runs it on each 20-day window as a pandas Series. The output shows Apple's rolling downside volatility averages 0.132 and ranges from 0.010 to 0.316. Note the standard deviation of only the losses measures how varied they were, a simplified version of the formal definition.
def rolling_downside_vol(returns, window):
def only_losses(x):
losses = x[x < 0]
return losses.std() * np.sqrt(252) if len(losses) > 1 else np.nan
return returns.rolling(window).apply(only_losses, raw=False)
merged['AAPL_DownsideVol20'] = rolling_downside_vol(merged['AAPL_Return'], 20)
merged['AAPL_DownsideVol20'].dropna().describe().round(3)
Part 10: Real Downside vs Real Total Volatility#
Comparing downside to total volatility tells you how much of the risk came from losses. The code divides the downside series by the 20-day total volatility and takes the mean. The output is 0.6: on average, downside volatility was about 60% of total volatility for Apple. This is a rough comparison, since the two measures are calculated on different sets of days, but it gives a sense of the balance between up and down swings.
downside_ratio = (merged['AAPL_DownsideVol20'] / merged['AAPL_Vol20']).dropna()
round(downside_ratio.mean(), 3)
Part 11: Real High-Volatility Regime Flagging#
Regime flagging turns a continuous risk measure into a simple label you can filter on. The code takes the median 20-day volatility for Apple and flags any day where volatility exceeds 1.5 times that median. The comparison returns True or False, and .sum() counts the Trues. The output shows 23 high-volatility days, a small share of the 318 days with a value. The 1.5 multiplier is a judgement call; try other thresholds to see how sensitive the count is.
aapl_median_vol = merged['AAPL_Vol20'].median()
merged['AAPL_HighVolFlag'] = merged['AAPL_Vol20'] > (aapl_median_vol * 1.5)
merged['AAPL_HighVolFlag'].sum()
Part 12: Real Returns During High-Volatility Regimes#
Once regimes are flagged, you can test whether returns behave differently inside them. The code selects Apple returns on flagged days with .loc, and the rest with ~, which flips True and False. .fillna(False) handles the early rows where the flag could not be computed. The output shows average daily returns of 0.019% in high-volatility periods versus 0.071% normally. Turbulent stretches delivered lower returns here, but 23 days is a small sample, so treat this as a hint rather than a rule.
high_vol_returns = merged.loc[merged['AAPL_HighVolFlag'], 'AAPL_Return']
normal_returns = merged.loc[~merged['AAPL_HighVolFlag'].fillna(False), 'AAPL_Return']
round(high_vol_returns.mean() * 100, 3), round(normal_returns.mean() * 100, 3)
Part 13: Real Rolling Maximum Drawdown#
A single maximum drawdown tells you the worst moment of the whole period; a rolling version shows how deep the recent pain was at each point. The function tracks the highest cumulative value over the last 60 days with rolling(window, min_periods=1).max(), measures each day's fall from that peak, and takes the worst fall in the window with rolling(window).min(). The output covers 279 days, with a mean of -0.168 (about -16.8%) and a worst value of -0.238. The least severe window still had a drawdown of about 5.8%.
def rolling_max_drawdown(cumulative, window):
roll_peak = cumulative.rolling(window, min_periods=1).max()
drawdown = (cumulative - roll_peak) / roll_peak
return drawdown.rolling(window).min()
merged['AAPL_RollMaxDD60'] = rolling_max_drawdown(merged['AAPL_Cumulative'], 60)
merged['AAPL_RollMaxDD60'].dropna().describe().round(3)
Part 14: Visualizing Real Rolling Drawdown#
Drawdowns are naturally shown as a shaded area dipping below zero. The code uses plt.fill_between to fill between the drawdown, multiplied by 100 for percentages, and the zero line, in semi-transparent crimson. The chart is saved to rolling_drawdown.png. When you open it, look for the deepest trough and how long it lasts; a wide, deep red area means a long stretch of losses rather than a single bad day.
plt.figure(figsize=(11, 5))
plt.fill_between(merged['Date'], merged['AAPL_RollMaxDD60'] * 100, 0, color='crimson', alpha=0.5)
plt.xlabel('Real Date')
plt.ylabel('Real Rolling 60-Day Max Drawdown (%)')
plt.title('Real Rolling Maximum Drawdown, Apple')
plt.tight_layout()
plt.savefig('rolling_drawdown.png', dpi=120)
plt.close()
Part 15: Real Worst Rolling Drawdown Window#
Pinning down the worst window gives your risk report a concrete date to discuss. The code uses idxmin() to find the row with the most negative rolling drawdown, then .loc to look up its date and value. The output shows the worst 60-day drawdown, -23.77%, was reached on 2016-01-27. That is the same date as Apple's worst single day in the earlier cleaning lesson, which suggests a sharp drop on top of an existing decline.
worst_dd_idx = merged['AAPL_RollMaxDD60'].idxmin()
worst_dd_date = merged.loc[worst_dd_idx, 'Date']
worst_dd_value = round(merged.loc[worst_dd_idx, 'AAPL_RollMaxDD60'] * 100, 2)
worst_dd_date, worst_dd_value
Part 16: Real Volatility Ratio, Tesla vs Apple#
A ratio of the two volatilities shows how much riskier Tesla is than Apple at each point in time. The code divides Tesla's 20-day volatility by Apple's and summarises it with .describe(). The output shows an average ratio of 1.82, a median of 1.70, and a range from 0.68 to 3.63. So Tesla was usually close to twice as volatile, but in some windows it was actually calmer than Apple, and at its peak more than three and a half times as volatile.
merged['VolRatio_TSLA_AAPL'] = merged['TSLA_Vol20'] / merged['AAPL_Vol20']
merged['VolRatio_TSLA_AAPL'].dropna().describe().round(2)
Part 17: Real Rolling Metrics Table Preview#
Before saving, it is worth viewing all the new metrics side by side to make sure they look sensible together. The code lists the columns in risk_cols, drops rows with any missing value, and shows the last three rows. On 2017-02-16, for example, Apple's 20-day volatility was 0.222 and Tesla's 0.275, giving a ratio of 1.240. Wide tables like this wrap across several blocks in the output, so read the column names carefully.
risk_cols = ['Date', 'AAPL_Vol20', 'AAPL_Vol60', 'TSLA_Vol20', 'TSLA_Vol60', 'AAPL_RollSharpe20', 'TSLA_RollSharpe20', 'AAPL_DownsideVol20', 'AAPL_RollMaxDD60', 'VolRatio_TSLA_AAPL']
merged[risk_cols].dropna().tail(3).round(3)
Part 18: Saving the Real Rolling Risk Table#
Saving the table lets you build dashboards or later analyses on these metrics directly. The code writes the risk_cols subset rounded to four decimals with index=False, reloads it, and compares row counts. The output is True. Unlike the preview, this save keeps the early rows with missing values, so all 338 days are present and blanks mark the warm-up period.
merged[risk_cols].round(4).to_csv('rolling_risk_metrics.csv', index=False)
reloaded = pd.read_csv('rolling_risk_metrics.csv')
reloaded.shape[0] == merged.shape[0]
Part 19: Real Sanity Check on Annualization#
A manual check against the pipeline catches errors that are easy to miss in chained rolling code. The code takes the last 20 returns with .tail(20), computes their standard deviation and annualises it, then compares this with the final value of AAPL_Vol20. Rounding the difference and testing it is below 1e-6 allows for tiny floating-point differences. The output is True, so the rolling calculation does exactly what you expect.
manual_check = merged['AAPL_Return'].tail(20).std() * np.sqrt(252)
pipeline_value = merged['AAPL_Vol20'].iloc[-1]
round(abs(manual_check - pipeline_value), 8) < 1e-6
Part 20: Real Recap Print#
A one-line summary turns the analysis into something you can paste into a report. The code averages each 20-day volatility series with .mean(), which skips NaNs, converts to percent and prints with an f-string. The output reads: across 338 days, Apple averaged 21.8% annualised rolling volatility versus Tesla at 36.2%. These match the means in the earlier summary statistics.
aapl_mean_vol_pct = round(merged['AAPL_Vol20'].mean() * 100, 1)
tsla_mean_vol_pct = round(merged['TSLA_Vol20'].mean() * 100, 1)
print(f'Across {merged.shape[0]} real overlapping trading days, Apple averaged {aapl_mean_vol_pct}% annualized rolling volatility versus Tesla at {tsla_mean_vol_pct}%.')
Part 21: Real EWMA Volatility (RiskMetrics Style)#
Simple rolling volatility gives every day in the window equal weight and then drops it suddenly. EWMA volatility, short for exponentially weighted moving average and popularised by the RiskMetrics system, gives recent days more weight and lets old days fade gradually. The code squares the returns, averages them with ewm(alpha=0.06, adjust=False), where alpha is the weight on the newest day, then takes the square root and annualises. The output covers 337 days, with a mean of 0.224 and a range of 0.102 to 0.407, very close to the simple measure.
aapl_sq_returns = merged['AAPL_Return'] ** 2
ewma_variance = aapl_sq_returns.ewm(alpha=0.06, adjust=False).mean()
merged['AAPL_EWMA_Vol'] = np.sqrt(ewma_variance) * np.sqrt(252)
merged['AAPL_EWMA_Vol'].dropna().describe().round(3)
Part 22: Real EWMA vs Real Simple Rolling Volatility#
Plotting the two methods together shows their different behaviour. The code draws Apple's simple 20-day volatility and its EWMA volatility on the same chart and saves it to ewma_vs_rolling_vol.png. There is no inline output. When you open it, look for how the simple measure drops abruptly when a big day leaves the 20-day window, while the EWMA line decays smoothly; that smoothness is why many risk teams prefer EWMA.
plt.figure(figsize=(11, 5))
plt.plot(merged['Date'], merged['AAPL_Vol20'], label='Real Simple 20-Day Vol')
plt.plot(merged['Date'], merged['AAPL_EWMA_Vol'], label='Real EWMA Vol')
plt.xlabel('Real Date')
plt.ylabel('Real Annualized Volatility')
plt.title('Real Simple Rolling vs Real EWMA Volatility, Apple')
plt.legend()
plt.tight_layout()
plt.savefig('ewma_vs_rolling_vol.png', dpi=120)
plt.close()
Part 23: Real Rolling Sortino Ratio#
The Sortino ratio is like the Sharpe ratio but divides by downside volatility instead of total volatility, so it only penalises losses. The code reuses the 20-day annualised mean return and divides by the rolling downside volatility. The output shows values of 107.40 to 161.53 at the end of the period, far above the Sharpe ratios of about 7. That happens because recent downside volatility was tiny, around 0.010 to 0.014, so dividing by it explodes the result. Always check the denominator before reporting an extreme ratio.
merged['AAPL_RollSortino20'] = aapl_roll_return20 / merged['AAPL_DownsideVol20']
merged[['Date', 'AAPL_RollSharpe20', 'AAPL_RollSortino20']].dropna().tail(3).round(2)
Part 24: Real Tesla High-Volatility Regime#
Applying the same regime rule to Tesla lets you compare how often each stock is in a turbulent phase. The code flags Tesla days where its 20-day volatility exceeds 1.5 times its own median, then shows both counts. The output is 23 high-volatility days for Apple and 38 for Tesla. Because each stock is judged against its own median, this says Tesla's risk spikes more often relative to its normal level, not just that it is riskier overall.
tsla_median_vol = merged['TSLA_Vol20'].median()
merged['TSLA_HighVolFlag'] = merged['TSLA_Vol20'] > (tsla_median_vol * 1.5)
merged['AAPL_HighVolFlag'].sum(), merged['TSLA_HighVolFlag'].sum()
Part 25: Real Historical Value-at-Risk on Rolling Windows#
Value-at-Risk (VaR) answers a question managers care about: on a bad day, how much might we lose? Historical 95% VaR is the 5th percentile of past returns, so only 5% of days were worse. The code applies np.percentile(x, 5) to each 60-day window with rolling(60).apply(..., raw=True), where raw=True passes a fast NumPy array. The output shows an average rolling VaR of -2.03%: on a typical 1-in-20 bad day, Apple fell about 2% or more. VaR says nothing about how bad losses beyond that threshold can be.
def rolling_var_95(returns, window):
return returns.rolling(window).apply(lambda x: np.percentile(x, 5), raw=True)
merged['AAPL_RollVaR95_60'] = rolling_var_95(merged['AAPL_Return'], 60)
round(merged['AAPL_RollVaR95_60'].dropna().mean() * 100, 2)
Part 26: Real Tightest and Real Widest VaR Windows#
Finding the extremes of VaR shows when risk was lowest and highest. The tightest VaR is the least negative value, found with idxmax(), and the widest is the most negative, found with idxmin(). The output shows the tightest window ended on 2017-02-10 and the widest on 2016-01-12. That matches the rest of the lesson: early 2016 was Apple's most stressful period, while early 2017 was calm.
tightest_var_date = merged.loc[merged['AAPL_RollVaR95_60'].idxmax(), 'Date']
widest_var_date = merged.loc[merged['AAPL_RollVaR95_60'].idxmin(), 'Date']
tightest_var_date, widest_var_date
Part 27: Real Correlation Between Volatility and Drawdown#
Different risk measures should tell a consistent story. The code pairs 60-day volatility with the 60-day rolling drawdown, drops missing rows, and correlates them. The output is -0.813, a strong negative relationship. Because drawdowns are negative numbers, this means higher volatility goes with deeper drawdowns. When measures agree this strongly, you can be confident they are capturing the same underlying risk.
vol_dd_pair = merged[['AAPL_Vol60', 'AAPL_RollMaxDD60']].dropna()
round(vol_dd_pair['AAPL_Vol60'].corr(vol_dd_pair['AAPL_RollMaxDD60']), 3)
Part 28: Real Current Volatility Percentile Rank#
A percentile rank puts today's risk in context: is it high or low compared with history? The code takes the latest 20-day volatility, compares every past value with it, and .mean() on the resulting booleans gives the share of days that were lower. The output is 50.0, so current volatility sits exactly at the median of this history. This is a neat way to tell a non-specialist whether things are calmer or rougher than usual.
current_vol = merged['AAPL_Vol20'].dropna().iloc[-1]
vol_percentile = (merged['AAPL_Vol20'].dropna() < current_vol).mean() * 100
round(vol_percentile, 1)
Part 29: Saving the Real Extended Risk Table#
The final save adds the newer metrics to the risk table. The code builds extended_cols by joining risk_cols with the EWMA volatility, rolling Sortino, Tesla regime flag and rolling VaR columns using + on the lists. After writing and reloading, it checks the number of columns with .shape[1] rather than rows. The output is True, so every intended column made it into the file. Checking columns as well as rows catches the common mistake of forgetting to include a new metric.
extended_cols = risk_cols + ['AAPL_EWMA_Vol', 'AAPL_RollSortino20', 'TSLA_HighVolFlag', 'AAPL_RollVaR95_60']
merged[extended_cols].round(4).to_csv('rolling_risk_metrics_extended.csv', index=False)
reloaded_ext = pd.read_csv('rolling_risk_metrics_extended.csv')
reloaded_ext.shape[1] == len(extended_cols)
Wrap-Up: What You Learned#
- Volatility genuinely changes over time, and rolling windows are how you make that real variation visible instead of averaging it away.
- Rolling Sharpe ratios show how a real risk-adjusted return itself shifts as market conditions change.
- Downside deviation isolates the real risk investors actually worry about, losses, rather than penalizing real upside swings too.
- Flagging real high-volatility regimes lets you test whether returns genuinely behave differently during turbulent stretches.
- Rolling maximum drawdown tracks the real worst pain an investor would have felt within any given real window, not just once at the end.
- Next video: real correlation and diversification across a wider set of real assets, going beyond just this one real pair.
Practice on your own
- Build the downside volatility and rolling Sortino ratio for Tesla using the same helper function, and compare its average downside ratio with Apple's 0.6.
- Change the high-volatility threshold from 1.5 to 1.25 times the median and see how the 23 Apple regime days and the high-volatility average return change.
- Compute a rolling 60-day 99% VaR with
np.percentile(x, 1)and count how many days Apple's actual return fell below the previous day's VaR.
The next lesson widens the view to correlation and diversification across a larger set of assets, beyond this one pair.
🧠 Test yourself
Pick an answer to check it. Your best score is saved in this browser.
The lesson computes 20-day rolling volatility with
returns.rolling(20).std() * np.sqrt(252). What does the result represent?The rolling std is daily volatility over the latest 20 days. Multiplying by sqrt(252) converts it to an annual scale.
Why use a rolling window rather than a single full-period volatility?
One number averages calm and turbulent periods together. A rolling measure reveals when risk rises or falls.
What is downside deviation as used in the lesson?
It ignores upside swings and measures spread among losing days, which is closer to what investors worry about. It is the base of the Sortino idea.
The lesson computes EWMA variance with
squared_returns.ewm(alpha=0.06, adjust=False).mean(). How does this differ from a plain rolling std?An exponentially weighted average decays old observations smoothly, so volatility reacts faster to new shocks than an equal-weight window.
What does
rolling(60).apply(lambda x: np.percentile(x, 5), raw=True)give on daily returns?The 5th percentile is the return that was worse than 95% of days in the window. It is a historical VaR estimate, usually a negative number.
💻 Practice exercises
Try each one in the notebook or in your own editor before opening the solution.
Given daily returns [0.01, -0.02, 0.015, -0.005, 0.02, -0.01], compute the daily standard deviation and the annualized volatility (252 trading days).
💡 Hint
Use pandas std() and multiply by np.sqrt(252).
✅ Show solution
import numpy as np import pandas as pd r = pd.Series([0.01, -0.02, 0.015, -0.005, 0.02, -0.01]) daily = r.std() annual = daily * np.sqrt(252) print(round(daily, 4), round(annual, 4))
Simulate 300 daily returns (seed 2, normal mean 0.0004, std 0.01). Compute 20-day rolling annualized volatility, print its min, max and latest values, and flag days where it exceeds 1.5 times its median (print how many).
💡 Hint
Use rolling(20).std() * np.sqrt(252) and median().
✅ Show solution
import numpy as np import pandas as pd rng = np.random.default_rng(2) ret = pd.Series(rng.normal(0.0004, 0.01, 300)) vol20 = ret.rolling(20).std() * np.sqrt(252) print('min', round(vol20.min(), 3), 'max', round(vol20.max(), 3), 'latest', round(vol20.iloc[-1], 3)) flag = vol20 > 1.5 * vol20.median() # NaN comparisons give False print('High-vol days:', int(flag.sum()))
Simulate 400 returns (seed 8, normal mean 0.0005, std 0.012). Compute a 60-day rolling 95% historical VaR (5th percentile), a 20-day rolling Sharpe (annualized mean / annualized vol), and the 60-day rolling maximum drawdown of the cumulative growth. Print the mean VaR in percent, and the worst rolling drawdown in percent.
💡 Hint
Use rolling(...).apply with np.percentile, and cummax-style drawdown on a rolling peak.
✅ Show solution
import numpy as np import pandas as pd rng = np.random.default_rng(8) ret = pd.Series(rng.normal(0.0005, 0.012, 400)) var95 = ret.rolling(60).apply(lambda x: np.percentile(x, 5), raw=True) vol20 = ret.rolling(20).std() * np.sqrt(252) sharpe20 = ret.rolling(20).mean() * 252 / vol20 cum = (1 + ret).cumprod() roll_peak = cum.rolling(60, min_periods=1).max() dd = (cum - roll_peak) / roll_peak roll_max_dd = dd.rolling(60).min() print('Mean 95% VaR (%):', round(var95.mean() * 100, 2)) print('Latest rolling Sharpe:', round(sharpe20.iloc[-1], 2)) print('Worst rolling drawdown (%):', round(roll_max_dd.min() * 100, 2))
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



