Compute Sharpe#

The compute_sharpe function calculates the Sharpe ratio for a given DataFrame of prices. The Sharpe ratio is a measure of risk-adjusted return, comparing the expected return of an investment to its risk. A higher Sharpe ratio indicates a better risk-adjusted performance.

To use the compute_sharpe 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, an optional years parameter, an optional freq parameter, and an optional risk_free_rate 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. The freq parameter indicates the frequency of the data, and the risk_free_rate parameter represents the risk-free rate of return.

After passing the DataFrame to the compute_sharpe function, it will return the Sharpe ratio for the given data.

compute_sharpe() function#

Function#

def compute_sharpe(dataframe, years='', freq='days', risk_free_rate=0):
    """
    Function to calculate the Sharpe ratio given a dataframe of prices.

    Parameters
    ----------
    dataframe : pandas.DataFrame
        DataFrame containing price data. Index should be of datetime type.
    years : int or empty string, optional
        The number of years to include in the calculation. Default is an empty string, which means the function uses the entire DataFrame.
    freq : str, optional
        Frequency of the data. Possible values: 'daily', 'monthly', 'quarterly', 'auto'. Default is 'daily'.
    risk_free_rate : float, optional
        The risk-free rate of return. Default is 0.

    Returns
    -------
    pandas.Series
        A pandas Series containing the Sharpe ratio for each column in the input DataFrame.
    """
    excess_return = compute_cagr(dataframe, years) - risk_free_rate
    return excess_return.div(compute_std_dev(dataframe, freq))

Description#

The compute_sharpe function computes the Sharpe ratio for a given pandas DataFrame of prices.

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.

  • freq (str, optional): Frequency of the data. Possible values: ‘daily’, ‘monthly’, ‘quarterly’, ‘auto’. Default is ‘daily’.

  • risk_free_rate (float, optional): The risk-free rate of return. Default is 0.

Returns#

pandas.Series: A pandas Series containing the Sharpe ratio for each column in the input DataFrame.

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 Sharpe ratio for the last 5 years with a risk-free rate of 0
sharpe_5_years = dsf.compute_sharpe(spy, years=5, freq='daily', risk_free_rate=0)
sharpe_5_years
spy    0.481203
dtype: float64
# Calculate the Sharpe ratio for the entire dataset with a risk-free rate of 2%
total_sharpe = dsf.compute_sharpe(spy, freq='daily', risk_free_rate=2)
total_sharpe
spy    0.493145
dtype: float64

In this example, we first calculate the Sharpe ratio for the last 5 years of the dataset with a risk-free rate of 0. Then, we calculate the Sharpe ratio for the entire dataset with a risk-free rate of 2%. The compute_sharpe function allows you to adjust the risk-free rate as needed to reflect the desired benchmark for comparison.