Compute Standard Deviation#

The compute_std_dev function calculates the annualized standard deviation of a given DataFrame of prices. It helps financial analysts and investors understand the volatility of various financial instruments such as stocks, bonds, and other securities.

To use the compute_std_dev function, you need to provide a pandas DataFrame containing price data with a datetime index. The function takes an optional freq parameter to specify the frequency of the data (‘daily’, ‘monthly’, ‘quarterly’, or ‘auto’). If the frequency is not provided or set to ‘auto’, the function calculates the scaling factor based on the average frequency in the data.

After passing the DataFrame to the compute_std_dev function, it will return a pandas Series containing the annualized standard deviation for each column in the input DataFrame.

compute_std_dev() function#

Function#

def compute_std_dev(dataframe, freq='auto'):
    """
    Compute the annualized standard deviation of a given DataFrame of prices.

    Parameters
    ----------
    dataframe : pandas.DataFrame
        DataFrame containing price data. Index should be of datetime type.
    freq : str, optional
        Frequency of the data.
        Possible values: 'daily', 'monthly', 'quarterly', 'auto'.
        Default is 'auto', which calculates the scaling factor based on the average
        frequency in the data.

    Returns
    -------
    pandas.Series
        A pandas Series containing the annualized standard deviation
        for each column in the input DataFrame.
    """

    if not isinstance(dataframe, pd.DataFrame):
        raise TypeError("Input must be a pandas DataFrame")

    # Define a dictionary to map frequency to the appropriate scaling factor
    scaling_factors = {
        'daily': np.sqrt(252),
        'monthly': np.sqrt(12),
        'quarterly': np.sqrt(4)
    }

    # If freq is 'auto', calculate the scaling factor based on the average frequency in
    #  the data
    if freq == 'auto':
        avg_frequency = dataframe.index.to_series().diff().mean()
        sessions_per_year = pd.Timedelta(365, unit='D') / avg_frequency
        scaling_factor = np.sqrt(sessions_per_year)
    elif freq in scaling_factors:
        scaling_factor = scaling_factors[freq]
    else:
        raise ValueError(
            "Invalid frequency. Allowed values: 'daily', 'monthly', 'quarterly', 'auto'"
        )

    # Compute the percentage change in the price data
    pct_change = dataframe.pct_change()

    # Calculate the standard deviation, scale it according to the scaling factor,
    # and convert to percentage
    annualized_std_dev = pct_change.std().mul(scaling_factor).mul(100)

    return annualized_std_dev

Parameters#

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

  • freq (str, optional): Frequency of the data. Possible values: ‘daily’, ‘monthly’, ‘quarterly’, ‘auto’. Default is ‘auto’, which calculates the scaling factor based on the average frequency in the data.

Returns#

  • pandas.Series: A pandas Series containing the annualized standard deviation 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 annualized standard deviation for the given data
annualized_std_dev = dsf.compute_std_dev(spy)
print(annualized_std_dev)
spy    19.021099
dtype: float64