python trading strategies

How To Calculate The Drawdown In Python For Your Trading Strategy

Investors often evaluate the performance of their portfolios by examining various metrics, and one crucial measure is drawdown. Drawdown represents the peak-to-trough decline in the value of a stock or portfolio during a specific period. It helps investors assess the risk and volatility associated with their investments.

In this article, we will explore how to compute drawdown in Python, providing a step-by-step guide for investors and analysts.

Related articles:

What Is Drawdown?

Drawdown is a measure of the largest loss from a peak to a trough of a portfolio’s value. It is typically expressed as a percentage and provides valuable insights into the potential risk and downside of an investment. The formula for drawdown is:


  • Peak Value is the highest value of the portfolio.
  • Trough Value is the lowest value reached after the peak.

Why Is Drawdown So Important?

Drawdown is a crucial metric in the world of finance and investing because it provides valuable insights into the risk and potential losses associated with a particular investment or portfolio.

Very few traders can handle huge drawdowns. As a result, they do the opposite of what they should do: They buy into strength because of FOMO, and sell into weakness because of fear. They make cognitive mistakes (please click here for what is bias in trading).

Here are several reasons why drawdown is considered an important measure:

  1. Risk Assesment: Drawdown helps investors assess the downside risk of their investments. By understanding the maximum historical loss, investors can gauge the potential impact on their portfolio during adverse market conditions.
  2. Volatility Measurement: Volatility is a key factor in investment risk. Drawdown captures the volatility by measuring the magnitude of the declines in the value of an investment. Higher drawdowns generally indicate higher volatility and vice versa. We want to avoid drawdowns as much as possible, but it’s inevitable, so we better be prepared for it.
  3. Psychological Impact: Drawdowns can have a significant psychological impact on investors, just like we wrote above about trading bias. Knowing how much their investment could lose during challenging market periods helps investors prepare mentally and emotionally, reducing the likelihood of panic selling during downturns. In general, traders don’t tolerate huge drawdowns.
  4. Performance Evaluation: Drawdown is an essential component when evaluating the historical performance of an investment strategy or portfolio. It provides a more comprehensive picture than just looking at returns, as it considers both the peaks and troughs in the value of the investment.
  5. Setting Realistic Expectations: Investors often have expectations about the potential returns of their investments. Drawdown helps set realistic expectations by showing that even successful investments may experience periods of decline.

How To Calculate The Drawdown In Python – Code

The heart of calculating drawdown lies in the following steps. You need to define a function to compute the drawdown using the provided stock price data. Here is the code explained line by line:

  1. Define a function name calculate_drawdown whose input is a data frame of a stock historical prices.
  2. Calculate the cumulative of strat using the cumprod() function and multiply the results by 100. 
  3. Calculate the rolling maximum of the df variable. This will give you a pandas Series or DataFrame with the highest historical value of the strategy’s cumulative returns at each point in time. 
  4. Computes the drawdown of the strategy by subtracting the previous peaks from the cumulative returns and then dividing them by the previous peaks. 
  5. Finally, the function calculates the maximum drawdown by finding the minimum value in the drawdown variable and multiplying it by 100 to convert it back to a percentage. The %.2f formatting is used to round the result to two decimal places. The + ‘%’ appends a percentage sign to the formatted result. 

How To Calculate The Drawdown In Python – a Practical Example

Before diving into the computation, let’s import the libraries we’ll need. The primary libraries for numerical and data analysis in Python are NumPy and Pandas. Then we are going to use Matplot to make a chart and visualize the drawdown.

You will also need historical data for the stock or portfolio.

For this example, are going to download the data historical data of Microsoft from Yahoo Finance using the library yfinance.

To compute drawdown, you’ll need to calculate the daily returns of the stock or portfolio.

Next, calculate the cumulative returns, which represent the overall performance of the investment.

Now, let’s compute the drawdown by finding the peak and trough values.

And that’s it! Visualizing drawdown can provide a clearer understanding of the investment’s risk profile.

To find the maximum drawdown we simply use the function min.

Another way to do it is directly with a function. The inputs are the cumulative returns of Microsoft and the procedure is the same. The function returns the maximum drawdown of the stock.

How To Calculate The Drawdown In Python – Conclusion

In summary, drawdown is a critical metric that provides investors with a comprehensive understanding of the potential risks and losses associated with their investments.

Today, we have shown you how to calculate it in Python in two different ways. Incorporating drawdown analysis into the investment decision-making process contributes to a more informed and resilient investment strategy.

Similar Posts