Lesson 19 · Real-World Data Analytics
Value at Risk (VaR) in Python: Historical, Parametric & Monte Carlo | Data Analytics #19
How much could you lose on a bad day? We calculate Value at Risk three ways in Python (historical, parametric and Monte Carlo), add expected shortfall…
- CourseReal-World Data Analytics
- Lesson19 of 100
- Video17 min
- 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_clean.csv preview58.9 KB
📓 Full notebook
Download .ipynbData Analytics 100, Video 19: Value-at-Risk and Drawdown Analysis#
- Video nineteen of the hundred-video real-world data analytics series.
- Three real ways to estimate Value-at-Risk, plus a full real drawdown and underwater-period breakdown for Apple.
- Let's get into it.
This lesson is for learners who can calculate returns and drawdowns and now want to measure downside risk the way risk teams do. The business question is: on a bad day, how much could an Apple position lose, how bad do the worst days get, and how long did investors sit below a previous high?
The data is the cleaned Apple price file used earlier in the series, aapl_clean.csv, with a Date column and the daily closing price AAPL.Close. From it you build 505 daily returns. Value-at-Risk (VaR) is the loss threshold that should only be exceeded on a small share of days, for example 5% of them at 95% confidence. You will estimate it three ways, measure Expected Shortfall, backtest the estimates, and break drawdowns down into underwater periods.
In this lesson you will:
- compute historical, parametric and Monte Carlo VaR, plus Conditional VaR
- backtest VaR by counting breaches and track it on a rolling window
- measure maximum drawdown, time underwater and drawdown episodes
Prerequisites: you should be comfortable with pct_change, cumprod and cummax; the backtesting video introduced drawdown if you need a refresher.
Part 1: Quantifying Real Tail Risk#
Tail risk is the risk of rare but large losses, the days that do the real damage. To measure it you first need daily returns. This step loads aapl_clean.csv with parse_dates=['Date'], then pct_change() turns closing prices into daily percentage changes and dropna() removes the empty first row. The result, returns, has one fewer row than the price data, which matters later when dates are lined up with iloc[1:]. There is no output here; check len(returns) yourself if you want to confirm the count.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
aapl = pd.read_csv('aapl_clean.csv', parse_dates=['Date'])
returns = aapl['AAPL.Close'].pct_change().dropna()
Part 2: Real Historical VaR#
Historical VaR reads the threshold straight from past data, with no assumption about the shape of returns. np.percentile(returns, 5) finds the return below which only 5% of days fell. The output is -2.49%, meaning that on about one trading day in twenty, Apple lost more than 2.49%. This method is simple and honest about fat tails, but it assumes the future will look like this particular sample of history.
var95_historical = np.percentile(returns, 5)
round(var95_historical * 100, 2)
Part 3: Real Parametric VaR#
Parametric VaR assumes returns follow a normal (bell-shaped) distribution, so it only needs the mean and standard deviation. norm.ppf(0.05) from scipy gives the z-score that cuts off the lowest 5% of a standard normal, about -1.645. The code calculates mean + z * std to place that cut-off on Apple's returns. The output is again -2.49%, matching the historical figure here. Be aware that real returns usually have fatter tails than a normal curve, so this method can understate extreme losses.
from scipy.stats import norm
mean_return = returns.mean()
std_return = returns.std()
z_score_95 = norm.ppf(0.05)
var95_parametric = mean_return + z_score_95 * std_return
round(var95_parametric * 100, 2)
Part 4: Real Monte Carlo VaR#
Monte Carlo VaR simulates many possible days and reads the threshold from the simulated results. np.random.seed(42) makes the random numbers repeatable, np.random.normal draws 100,000 returns using Apple's mean and standard deviation, and np.percentile(..., 5) finds the 5th percentile. The output is -2.49% once more. Because the simulation draws from a normal distribution, it essentially reproduces the parametric result; its real power appears when you simulate richer models or whole portfolios.
np.random.seed(42)
simulated_returns = np.random.normal(mean_return, std_return, 100000)
var95_montecarlo = np.percentile(simulated_returns, 5)
round(var95_montecarlo * 100, 2)
Part 5: Comparing All Three Real VaR Methods#
Putting the three estimates side by side is a quick honesty check: if they disagree a lot, your assumptions matter. The code builds a pd.Series from a dictionary of the three results and multiplies by 100 to show percentages. The output shows all three at -2.49%. Agreement here suggests the normal assumption is a reasonable fit at the 95% level for this period. That agreement often breaks down at higher confidence levels, where fat tails have more influence.
var_comparison = pd.Series({'Historical': var95_historical, 'Parametric': var95_parametric, 'Monte Carlo': var95_montecarlo})
(var_comparison * 100).round(2)
Part 6: Real Conditional VaR (Expected Shortfall)#
VaR tells you where the bad days start, but not how bad they get. Conditional VaR (CVaR), also called Expected Shortfall, is the average return on the days that were worse than VaR. The code filters returns <= var95_historical to keep the worst 5% of days and takes their .mean(). The output is -3.45%, so once the VaR line is crossed, the average loss is about 3.45%, roughly 1 percentage point worse than VaR itself. Many regulators now prefer Expected Shortfall for this reason.
tail_losses = returns[returns <= var95_historical]
cvar95 = tail_losses.mean()
round(cvar95 * 100, 2)
Part 7: Visualizing Real VaR and Real CVaR on the Return Distribution#
Seeing VaR and CVaR on the return distribution makes both measures intuitive. plt.hist draws daily returns in 50 bins, and plt.axvline adds vertical dashed lines at the VaR (orange) and CVaR (red), with labels built from f-strings that include the values. The chart is saved to var_cvar_distribution.png and closed, so there is no inline output. When you open it, look at the small tail to the left of the orange line: those are the 5% of days that CVaR averages.
plt.figure(figsize=(11, 5))
plt.hist(returns, bins=50, color='steelblue', edgecolor='white', alpha=0.8)
plt.axvline(var95_historical, color='orange', linestyle='--', label=f'Real VaR 95% ({round(var95_historical*100,2)}%)')
plt.axvline(cvar95, color='red', linestyle='--', label=f'Real CVaR 95% ({round(cvar95*100,2)}%)')
plt.xlabel('Real Daily Return')
plt.ylabel('Real Frequency')
plt.title('Real Return Distribution with VaR and CVaR')
plt.legend()
plt.tight_layout()
plt.savefig('var_cvar_distribution.png', dpi=120)
plt.close()
Part 8: Real Multi-Day VaR Scaling#
Risk managers often need VaR over several days, such as a 10-day holding period. A common shortcut is the square-root-of-time rule: multiply one-day VaR by np.sqrt(10) or np.sqrt(30). The output gives -7.88% for 10 days and -13.66% for 30 days. This rule assumes returns are independent from day to day and have the same volatility, which is rarely exactly true, so treat multi-day figures as rough estimates.
var95_10day = var95_historical * np.sqrt(10)
var95_30day = var95_historical * np.sqrt(30)
round(var95_10day * 100, 2), round(var95_30day * 100, 2)
Part 9: Real VaR Backtesting, Counting Exceedances#
Backtesting VaR checks whether the model is well calibrated: a 95% VaR should be breached on about 5% of days. The code compares each return with the VaR, and .sum() counts the True values. It also computes the expected count as 5% of the number of days. The output (26, 25.2) shows 26 actual breaches versus 25.2 expected, a very close match. Keep in mind this is an in-sample test, since VaR was estimated from these same returns, so a close match is expected.
exceedances = (returns < var95_historical).sum()
expected_exceedances = len(returns) * 0.05
exceedances, round(expected_exceedances, 1)
Part 10: Real Exceedance Rate#
Expressing breaches as a rate makes it easy to compare with the target. The code divides the number of exceedances by the number of days and converts to a percentage. The output is 5.15%, just above the 5% target. A rate well above 5% would mean the model underestimates risk; well below would mean it is too cautious. With around 500 days, small differences like 5.15% versus 5% are well within normal random variation.
exceedance_rate = exceedances / len(returns)
round(exceedance_rate * 100, 2)
Part 11: Visualizing Real VaR Breaches Over Time#
Breaches that bunch together are more dangerous than breaches spread evenly, because they mean several bad days in a row. The code lines up dates with returns using aapl['Date'].iloc[1:], skipping the first date that has no return, and selects breach dates with a boolean mask. It plots all returns in grey, marks breaches as red dots with plt.scatter (where zorder=5 draws them on top), and adds the VaR line with plt.axhline. The chart is saved to var_breaches.png. Look for clusters of red dots during turbulent periods.
breach_dates = aapl['Date'].iloc[1:][returns.values < var95_historical]
breach_returns = returns[returns < var95_historical]
plt.figure(figsize=(11, 5))
plt.plot(aapl['Date'].iloc[1:], returns, color='gray', alpha=0.5, label='Real Daily Return')
plt.scatter(breach_dates, breach_returns, color='red', s=25, label='Real VaR Breach', zorder=5)
plt.axhline(var95_historical, color='orange', linestyle='--', label='Real VaR 95% Threshold')
plt.xlabel('Real Date')
plt.ylabel('Real Daily Return')
plt.title('Real VaR Breaches Over Time')
plt.legend()
plt.tight_layout()
plt.savefig('var_breaches.png', dpi=120)
plt.close()
Part 12: Real Drawdown Series#
A drawdown series shows, for every day, how far the investment sits below its highest point so far. (1 + returns).cumprod() builds the growth of $1, cummax() tracks the running peak, and the percentage gap between them is the drawdown. describe() shows 505 days with a mean drawdown of -15.1% and a median of -15.0%, a worst value of -32.1%, and a maximum of 0, which means at a new peak. A typical day was spent about 15% below the previous high.
cumulative = (1 + returns).cumprod()
running_peak = cumulative.cummax()
drawdown = (cumulative - running_peak) / running_peak
drawdown.describe().round(3)
Part 13: Real Maximum Drawdown#
Maximum drawdown is the single deepest fall from a peak, and the date of the bottom gives it context. drawdown.min() finds the worst value, and the date lookup matches it against the dates (skipping the first date with iloc[1:]), taking the first match with .iloc[0]. The output shows a maximum drawdown of -32.08%, reached on 12 May 2016. An investor who bought at the previous peak would have seen almost a third of their money disappear on paper by that day.
max_drawdown = drawdown.min()
max_drawdown_date = aapl['Date'].iloc[1:][drawdown.values == max_drawdown].iloc[0]
round(max_drawdown * 100, 2), max_drawdown_date
Part 14: Visualizing the Real Drawdown Curve#
A drawdown curve, sometimes called an underwater chart, shows the depth and duration of losses together. plt.fill_between shades the area between the drawdown percentage and zero, so every period below a previous peak appears as a filled red region. The figure is saved to full_drawdown_curve.png and closed, with no inline output. When you open it, look for the deepest point around May 2016 and how long the shaded area takes to climb back towards zero.
plt.figure(figsize=(11, 5))
plt.fill_between(aapl['Date'].iloc[1:], drawdown * 100, 0, color='crimson', alpha=0.5)
plt.xlabel('Real Date')
plt.ylabel('Real Drawdown (%)')
plt.title('Real Apple Drawdown from Prior Peak')
plt.tight_layout()
plt.savefig('full_drawdown_curve.png', dpi=120)
plt.close()
Part 15: Real Underwater Periods#
Time spent underwater, meaning below a previous peak, captures how long investors had to wait for a recovery. drawdown < 0 marks each day as True or False, and .mean() on a boolean Series gives the share of True values. The output is 98.8%, so Apple sat below a previous high on almost every day of this period. This shows that a stock can end up higher overall while still rarely setting new highs along the way.
is_underwater = drawdown < 0
pct_time_underwater = is_underwater.mean()
round(pct_time_underwater * 100, 1)
Part 16: Real Longest Underwater Streak#
The longest unbroken run of underwater days shows the worst waiting period an investor faced. The loop walks through the True and False flags, adding one to current_streak for each underwater day, resetting it to zero on a new peak, and keeping the largest value seen in longest_streak. The output is 497 consecutive days, out of 505 in total. In other words, after an early peak, Apple did not set a new high for almost the whole period.
longest_streak = 0
current_streak = 0
for underwater_flag in is_underwater:
if underwater_flag:
current_streak += 1
longest_streak = max(longest_streak, current_streak)
else:
current_streak = 0
longest_streak
Part 17: Real Recovery Time from Maximum Drawdown#
Knowing whether, and when, the stock recovered from its worst loss matters for planning and patience. argmin() finds the position of the deepest drawdown, iloc[bottom_idx:] keeps everything after it, and the filter >= -0.001 looks for days within 0.1% of the previous peak. The output True shows the price did get back to within 0.1% of its old high after the bottom. This step only confirms recovery; counting the days until the first such point would give the actual recovery time.
bottom_idx = drawdown.values.argmin()
post_bottom_drawdown = drawdown.iloc[bottom_idx:]
recovery_points = post_bottom_drawdown[post_bottom_drawdown >= -0.001]
recovered = len(recovery_points) > 0
recovered
Part 18: Real Number of Distinct Drawdown Episodes#
Counting separate drawdown episodes tells you whether losses came in one long slump or many short dips. The code compares each day's underwater flag with the previous day's using shift(1, fill_value=False); ~ means NOT, so a True result marks the first day of a new underwater stretch. .sum() counts these starts. The output, 3, means there were only three distinct drawdown episodes, consistent with one very long slump that dominated the period.
underwater_starts = (is_underwater & ~is_underwater.shift(1, fill_value=False)).sum()
underwater_starts
Part 19: Real Average Drawdown Depth#
The average drawdown depth on underwater days describes the typical pain level, not just the worst moment. The code selects drawdown values where is_underwater is True and takes their .mean(). The output is -15.27%, meaning that on a typical underwater day Apple sat about 15% below its previous high. Pairing average depth with maximum depth gives a more rounded picture than the maximum alone, which happens on just one day.
average_drawdown_when_underwater = drawdown[is_underwater].mean()
round(average_drawdown_when_underwater * 100, 2)
Part 20: Real VaR at a Different Confidence Level#
A 99% VaR looks further into the tail, at the worst 1% of days. The code reuses np.percentile, this time at the 1st percentile. The output is -4.23%, compared with -2.49% at 95%. So the threshold for a one-in-a-hundred bad day is about 1.7 times the one-in-twenty threshold. With around 500 days, the 1% tail contains only about five observations, so 99% historical VaR is much less stable than the 95% figure.
var99_historical = np.percentile(returns, 1)
round(var99_historical * 100, 2)
Part 21: Real 99% Exceedance Backtest#
The same breach check applies at 99%, where you expect breaches on about 1% of days. The code counts returns below the 99% VaR and computes the expected count as 1% of the days. The output (6, 5.0) shows six actual breaches against about five expected. As before, this is in-sample, and with numbers this small, one extra breach is not evidence that the model is wrong.
exceedances_99 = (returns < var99_historical).sum()
expected_99 = len(returns) * 0.01
exceedances_99, round(expected_99, 1)
Part 22: Real Dollar VaR for a Hypothetical Position#
Percentages are abstract; a dollar figure is what managers and clients understand. The code multiplies a hypothetical $100,000 position by the absolute value of the 95% VaR, using `abs()` to turn the negative return into a positive loss. The output, 2493.43, means that on about one trading day in twenty, a $100,000 Apple position could be expected to lose more than about $2,493. Always state the confidence level and time horizon alongside a dollar VaR.
hypothetical_position_usd = 100000
dollar_var95 = hypothetical_position_usd * abs(var95_historical)
round(dollar_var95, 2)
Part 23: Real Rolling VaR Over Time#
Risk is not constant, so a single VaR for the whole period can hide calm and stormy stretches. rolling(60).apply(...) calculates the 5th percentile over each 60-day window, with raw=True passing plain numpy arrays to the function, which is faster. The output covers 446 windows with a median VaR of -2.27%, ranging from -4.24% in the riskiest window to -0.72% in the calmest. Daily risk thresholds clearly moved a lot over time, more than the single -2.49% figure suggests.
rolling_var95 = returns.rolling(60).apply(lambda x: np.percentile(x, 5), raw=True)
rolling_var95.dropna().describe().round(4)
Part 24: Visualizing Real Rolling VaR#
Plotting rolling VaR shows when risk rose and fell. The code draws the 60-day rolling VaR against the dates, using aapl['Date'].iloc[1:] so the dates line up with the returns, and saves rolling_var.png without inline output. The first 59 points are empty because the window needs 60 days of data. When you open the chart, look for periods where the line drops sharply, meaning losses were getting larger, and compare them with the breach clusters seen earlier.
plt.figure(figsize=(11, 5))
plt.plot(aapl['Date'].iloc[1:], rolling_var95, color='darkred')
plt.xlabel('Real Date')
plt.ylabel('Real Rolling 60-Day VaR (95%)')
plt.title('Real Rolling VaR Over Time, Apple')
plt.tight_layout()
plt.savefig('rolling_var.png', dpi=120)
plt.close()
Part 25: Saving the Real VaR and Drawdown Summary#
A saved summary lets you share the key risk numbers or compare them with future runs. The code builds a small DataFrame with six metrics, from the three 95% VaR estimates to CVaR, 99% VaR and maximum drawdown, writes it with to_csv(index=False) and reads it back. The output True confirms the file contains all six rows. Storing values in percentage units, as here, avoids confusion with decimals when others read the file.
risk_summary = pd.DataFrame({'Metric': ['Historical VaR 95%', 'Parametric VaR 95%', 'Monte Carlo VaR 95%', 'CVaR 95%', 'Historical VaR 99%', 'Max Drawdown'], 'ValuePct': [round(var95_historical*100,2), round(var95_parametric*100,2), round(var95_montecarlo*100,2), round(cvar95*100,2), round(var99_historical*100,2), round(max_drawdown*100,2)]})
risk_summary.to_csv('var_drawdown_summary.csv', index=False)
reloaded = pd.read_csv('var_drawdown_summary.csv')
reloaded.shape[0] == 6
Part 26: Real Sanity Check, VaR Ordering#
Sanity checks catch logical errors in risk numbers. Two rules should always hold: 99% VaR should be more negative than 95% VaR, and CVaR should be at or below VaR. The code checks both, but Jupyter only displays the last expression, so the output np.True_ confirms the second check: CVaR is at or below VaR. To see both results, wrap them in a tuple or combine them with and.
var99_historical < var95_historical
cvar95 <= var95_historical
Part 27: Real Sanity Check, Drawdown Bounds#
By definition, drawdown can never be positive, because the running peak is always at least as high as the current value. The code tests (drawdown <= 0).all(), which returns True only if every value meets the condition. The output np.True_ confirms the drawdown series is valid. If this ever failed, it would point to a bug such as using cummin() instead of cummax(), or misaligned data.
(drawdown <= 0).all()
Part 28: Real Comparison, VaR vs Real Max Drawdown#
VaR and maximum drawdown answer different questions: one bad day versus a sustained decline. Dividing one by the other shows how different they can be. The code takes absolute values with abs() and divides the maximum drawdown by the 95% VaR. The output, 12.9, means the worst peak-to-trough fall was nearly 13 times the size of a one-in-twenty bad day. Relying on daily VaR alone would badly understate the losses a long-term holder actually experienced.
round(abs(max_drawdown) / abs(var95_historical), 1)
Part 29: Real Number of Drawdown Episodes vs Real VaR Breaches#
Comparing episode counts with breach counts highlights the different nature of the two measures. The code simply displays the two numbers calculated earlier as a tuple. The output (3, 26) shows 3 drawdown episodes but 26 VaR breaches. Bad days are relatively frequent, while drawdown episodes are few but long. Both perspectives matter: VaR for daily trading limits, drawdown for an investor's patience and capital planning.
underwater_starts, exceedances
Part 30: Real Recap Print#
A one-sentence recap turns the analysis into something a manager can read quickly. The f-string combines the number of days, the 95% VaR, the Expected Shortfall, the maximum drawdown rounded to one decimal place and the longest underwater streak. The printed output reads: across 505 trading days, Apple had a -2.49% one-day VaR, a -3.45% Expected Shortfall, and a -32.1% maximum drawdown that lasted up to 497 consecutive underwater days. Note the 497 days describe the longest underwater run rather than the length of the maximum drawdown itself.
print(f'Across {len(returns)} real trading days, Apple had a {round(var95_historical*100,2)}% one-day VaR, a {round(cvar95*100,2)}% Expected Shortfall, and a {round(max_drawdown*100,1)}% maximum drawdown that lasted up to {longest_streak} real consecutive underwater days.')
Wrap-Up: What You Learned#
- Historical, parametric, and Monte Carlo VaR are three genuinely different ways to estimate the real same downside threshold, and comparing them is a real honesty check.
- Conditional VaR, or Expected Shortfall, answers the real question VaR leaves open: how bad does it actually get once the threshold is breached.
- Backtesting VaR by counting real exceedances against the real theoretically expected rate is how you check whether a risk model is actually well-calibrated.
- Drawdown and VaR measure genuinely different things, VaR is about a real single bad day, drawdown is about a real sustained decline from a prior peak.
- Underwater period length and real recovery time turn an abstract percentage into a real, human sense of how long a loss actually took to live through.
- Next video: the Domain 2 capstone, building one real multi-asset portfolio report that pulls together everything covered across this whole finance domain.
Practice on your own
- Calculate 99% CVaR by averaging returns at or below
var99_historical, and compare the gap between 99% VaR and 99% CVaR with the 95% gap. - Extend the recovery step to count how many trading days it took from the bottom on 12 May 2016 to the first day within 0.1% of the old peak.
- Recalculate rolling VaR with a 20-day and a 120-day window, and compare their minimum, median and maximum with the 60-day results.
The next video is the Domain 2 capstone, a multi-asset portfolio report that brings together everything covered across this finance domain.
🧠 Test yourself
Pick an answer to check it. Your best score is saved in this browser.
A stock's 95% one-day historical VaR is -2.0%. What does that mean?
Historical VaR is a percentile of past returns. A 95% VaR of -2% means the worst 5% of days were below -2%, and it says nothing about how bad those days were.
How is parametric VaR at 95% computed in the lesson?
It assumes normal returns: norm.ppf(0.05) is about -1.645, so VaR is the mean minus 1.645 standard deviations.
What is Conditional VaR (Expected Shortfall) in the lesson?
CVaR is
returns[returns <= var].mean(). It answers how bad losses are on average once the VaR line is breached.A one-day 95% VaR is -2%. Using the lesson's square-root-of-time scaling, what is the approximate 10-day VaR?
Scaling multiplies by sqrt(10), about 3.16. So -2% * 3.16 is roughly -6.3%.
In the lesson, drawdown is computed as
(cumulative - cumulative.cummax()) / cumulative.cummax(). What does a value of -0.25 mean?Drawdown measures the fall from the running peak. It can be -0.25 even if the starting value is still lower or higher, because it only compares with the highest value so far.
💻 Practice exercises
Try each one in the notebook or in your own editor before opening the solution.
Given daily returns [-0.03, 0.01, 0.02, -0.01, 0.015, -0.02, 0.005, 0.01, -0.005, 0.0] compute the 95% historical VaR using np.percentile and print it in percent.
💡 Hint
Use np.percentile(returns, 5).
✅ Show solution
import numpy as np returns = np.array([-0.03, 0.01, 0.02, -0.01, 0.015, -0.02, 0.005, 0.01, -0.005, 0.0]) var95 = np.percentile(returns, 5) print(round(var95 * 100, 2), '%')
Simulate 1000 daily returns (seed 42, normal mean 0.0005 std 0.012). Compute historical 95% VaR, parametric 95% VaR (using scipy norm.ppf), and CVaR (average of returns at or below the historical VaR). Print them in percent.
💡 Hint
Parametric VaR = mean + norm.ppf(0.05) * std.
✅ Show solution
import numpy as np from scipy.stats import norm rng = np.random.default_rng(42) returns = rng.normal(0.0005, 0.012, 1000) hist = np.percentile(returns, 5) param = returns.mean() + norm.ppf(0.05) * returns.std() cvar = returns[returns <= hist].mean() print('Historical VaR %:', round(hist * 100, 2)) print('Parametric VaR %:', round(param * 100, 2)) print('CVaR %:', round(cvar * 100, 2))
Simulate 500 daily returns (seed 7, normal mean 0.0006 std 0.015). Build the cumulative growth, compute the drawdown series, the maximum drawdown in percent, the percent of days underwater (drawdown < 0), the longest underwater streak in days, and the number of exceedances of the 95% historical VaR compared with the 5% expected.
💡 Hint
Use a loop with a running counter for the streak.
✅ Show solution
import numpy as np import pandas as pd rng = np.random.default_rng(7) returns = pd.Series(rng.normal(0.0006, 0.015, 500)) cum = (1 + returns).cumprod() dd = (cum - cum.cummax()) / cum.cummax() print('Max drawdown %:', round(dd.min() * 100, 2)) underwater = dd < 0 print('Days underwater %:', round(underwater.mean() * 100, 1)) longest = current = 0 for flag in underwater: current = current + 1 if flag else 0 longest = max(longest, current) print('Longest underwater streak:', longest) var95 = np.percentile(returns, 5) print('Exceedances:', int((returns < var95).sum()), 'expected:', len(returns) * 0.05)
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



