Compute Drawdowns#

The compute_drawdowns() function calculates the drawdowns of a given pandas DataFrame of prices. Drawdowns represent the percentage decline in the value of an investment from its peak. It’s an essential risk measure for investors, as it helps to understand the potential losses during unfavorable market conditions.

To use the compute_drawdowns() function, you need to provide a pandas DataFrame containing price data with a datetime index.

After passing the DataFrame to the compute_drawdowns() function, it will return a pandas DataFrame containing the drawdowns for each column in the input DataFrame. This enables investors to evaluate the risk associated with different financial instruments and make informed decisions about their portfolio.

Function#

def compute_return(dataframe: pd.DataFrame, years: int = None) -> pd.Series:
    """
    Compute the return of a time series given a DataFrame of prices.

    Parameters
    ----------
    dataframe : pandas.DataFrame
        DataFrame containing price data. The index should be of datetime type.
    years : int, optional
        Number of years to filter the data before computing the return. If not provided,
        the return will be calculated using the entire DataFrame.

    Returns
    -------
    pandas.Series
        A pandas Series containing the return for each column in the input DataFrame.
    """
    # Validate input
    if not isinstance(dataframe, pd.DataFrame):
        raise TypeError("Input 'dataframe' must be a pandas DataFrame.")

    # Filter data by the number of years if specified
    if years is not None:
        if not isinstance(years, int) or years < 1:
            raise ValueError("Input 'years' must be a positive integer.")
        start_date = dataframe.index[-1] - pd.DateOffset(years=years)
        dataframe = dataframe.loc[start_date:]

    # Compute the return
    return (dataframe.iloc[-1] / dataframe.iloc[0] - 1) * 100

Example#

import pandas as pd
import yfinance as yf
import ds4finance as dsf

# Download historical data for SPY #
spy = yf.download("SPY", start="2015-01-01", end="2020-12-31", progress=False)

# Calculate drawdowns
drawdowns = dsf.compute_drawdowns(spy[["Adj Close"]])

# Rename Colname
drawdowns.columns = ['SPY DD']

# Display drawdowns
drawdowns.head()
SPY DD
Date
2015-01-02 0.000000
2015-01-05 -1.805941
2015-01-06 -2.730839
2015-01-07 -1.518734
2015-01-08 0.000000

Notes:

  • The function calculates drawdowns as a percentage.

  • Make sure the input is a pandas DataFrame with a datetime index.