<jupyter_start><jupyter_text>Computing Historical Drawdown_"A maximum drawdown (MDD) is the maximum observed loss from a peak to a trough of a portfolio, before a new peak is attained. Maximum drawdown is an indicator of downside risk over a specified time period."_ Investopedia (https://www.investopedia.com/terms/m/maximum-drawdown-mdd.asp)  Calling the Libraries and Getting the dataThe data that we will use is the time series returns of IVV, it represents the SPY 500<jupyter_code>import yfinance as yf
import pandas as pd
import numpy as np

#We save the time series prices here (the maximum information available) 
security = yf.Ticker('IVV').history(period="max")
security.index = security.index.to_pydatetime()
#We calculate the returns
returns = security['Close'].pct_change().dropna()

security.Close.plot(title = 'IVV')<jupyter_output><empty_output><jupyter_text>Calculating the previous peaks<jupyter_code>previous_peaks = security.Close.cummax()
previous_peaks.plot(title = "Previous Peak Price")<jupyter_output><empty_output><jupyter_text>Calculating the Drawdown<jupyter_code>#It calculates the change from the peak in percentual format
drawdown = (security.Close - previous_peaks)/previous_peaks

#Plot the drawdown
p = drawdown.plot(title = "Historical Drawdown for IVV")
vals = p.get_yticks()
yaxis = p.set_yticklabels(['{:,.2%}'.format(x) for x in vals])<jupyter_output><ipython-input-60-00a895277cda>:7: UserWarning: FixedFormatter should only be used together with FixedLocator
  yaxis = p.set_yticklabels(['{:,.2%}'.format(x) for x in vals])<jupyter_text>Showing the Results<jupyter_code>maxDrawdown = -drawdown.min()

print(f'Maximum Drawdown {maxDrawdown*100:.2f}%')
print(f'At {str(drawdown.idxmin()).split()[0]}')<jupyter_output>Maximum Drawdown 55.25%
At 2009-03-09
{'fraction_non_alphanumeric': 0.11036789297658862, 'fraction_numerical': 0.01839464882943144, 'mean_word_length': 6.703862660944206, 'pattern_counts': {'":': 0, '<': 16, '<?xml version=': 0, '>': 16, 'https://': 1, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '647962', 'license': 'MIT', 'n_tokens_mistral': 623, 'n_tokens_neox': 582, 'n_words': 165, 'path': '4-MaxDrawdown/4 - maxDrawdown.ipynb', 'repo_name': 'Gabrielmastrangelo/Quantitative-Finance-with-Python', 'size': '1794'}