Compute Return#

The compute_return function is designed to help financial analysts and investors analyze the performance of various financial instruments such as stocks, bonds, and other securities. It calculates the return of the given price data in percentage terms.

To use the compute_return function, you need to provide a pandas DataFrame containing price data with a datetime index. The function works with time series data.

The function takes the input DataFrame and an optional years parameter. If you provide an integer value for years, the function will filter the input data to include only the data within the specified number of years from the most recent data point. If you don’t provide the years parameter or pass an empty string, the function will use the entire DataFrame.

After passing the DataFrame to the compute_return function, it will return the return in percentage for the given data.

compute_return() function#

Function#

def compute_drawdowns(dataframe):
    """
    Compute the drawdowns of a given DataFrame of prices.

    Parameters
    ----------
    dataframe : pandas.DataFrame
        DataFrame containing price data. Index should be of datetime type.

    Returns
    -------
    pandas.DataFrame
        A DataFrame containing the drawdowns for each column in the input DataFrame.
    """
    # Compute the drawdowns as a percentage
    drawdowns = (dataframe / dataframe.cummax() - 1) * 100

    return drawdowns

Description#

The compute_return function computes the return of a given pandas DataFrame of prices in percentage terms.

Parameters#

  • dataframe (pandas.DataFrame): DataFrame containing price data. The index should be of datetime type.

  • years (int or empty string, optional): The number of years to include in the calculation. If an integer is provided, the function filters the data accordingly. Default is an empty string, which means the function uses the entire DataFrame.

Returns#

  • float: The return of the input data in percentage.

Example#

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

def download_data(ticker, start, end):
    data = yf.download(ticker, start=start, end=end, progress=False)
    adj_close = data['Adj Close']
    return adj_close

ticker = 'SPY'
start_date = '2015-12-31'
end_date = '2022-12-31'

# Load your price data into a pandas DataFrame
spy = pd.DataFrame(download_data(ticker, start_date, end_date))
spy.columns = ['spy']
# Calculate the return for the last 5 years
return_5_years = dsf.compute_return(spy, years=5)
return_5_years
spy    54.976401
dtype: float64
# Calculate the return for the entire dataset
total_return = dsf.compute_return(spy)
total_return
spy    112.756325
dtype: float64