garpar.core package

Core subpackage of Garpar project.

This subpackage is centered around the StocksSet class, which represents both a portfolio and a market in a single structure. It provides accessors to compute various properties, graphs, and metrics of a portfolio.

Key Features:
  • Correlation and covariance analysis

  • Diversification metrics

  • Entropy-based analysis

  • Expected returns estimation

  • Market data handling and validation

  • Portfolio/market construction and rebalancing

  • Portfolio/market visualization tools

  • Price-related data and methods

  • Risk metrics calculation (variance, VaR, etc.)

  • Utility metrics calculation

Submodules

garpar.core.stocks_set module

Financial Portfolio/market Analysis with StocksSet.

A comprehensive toolset for analyzing and managing financial portfolios/markets through the StocksSet class. Provides functionality for portfolio/market optimization, risk assessment, and performance analysis.

Key Features:
  • Portfolio/market construction and rebalancing

  • Market data handling and validation

Examples

>>> import garpar
>>> prices_df = [[...], [...]]  # Your price data
>>> ss = garpar.mkss(
...     prices=prices_df,
...     weights=[0.4, 0.3, 0.3],
...     window_size=30
... )
>>> ss.risk.value_at_risk()
>>> ss.plot.returns()

or

>>> import garpar
>>> prices_df = pd.DataFrame(...)  # Your price data
>>> ss = garpar.StocksSet.from_prices(
...     prices=prices_df,
...     weights=[0.4, 0.3, 0.3],
...     window_size=30
... )
>>> ss.risk.value_at_risk()
>>> ss.plot.returns()

References

Markowitz, H.M. (1952). Portfolio Selection https://doi.org/10.1111/j.1540-6261.1952.tb01525.x

class garpar.core.stocks_set.StocksSet(prices_df, weights, entropy, window_size, metadata=NOTHING)

Bases: object

Represents a financial stocks set.

This class is a core component of the Garpar project, designed to aggregate assets along with their weight proportions that represent the percentage of invested capital in each asset, entropy measures, and metadata.

as_prices()

Return a copy of the prices as a DataFrame.

Returns:

Copy of the prices DataFrame.

Return type:

pd.DataFrame

as_returns(**kwargs)

Return a DataFrame of returns corresponding to the prices.

Parameters:

**kwargs – Additional arguments passed to returns_from_prices function.

Returns:

DataFrame of returns corresponding to the prices DataFrame.

Return type:

pd.DataFrame

copy(*, prices=None, weights=None, entropy=None, window_size=None, stocks=None, preserve_old_metadata=True, **metadata)

Create a copy of the StocksSet.

Parameters:
  • prices (pd.DataFrame, optional) – New prices DataFrame.

  • weights (array-like, optional) – New weights array.

  • entropy (array-like, optional) – New entropy array.

  • window_size (int or None, optional) – New window size for rolling calculations.

  • stocks (array-like, optional) – New list of stock names.

  • preserve_old_metadata (bool, optional) – Whether to preserve old metadata.

  • **metadata – Additional metadata to include.

Returns:

A new StocksSet instance with the specified modifications.

Return type:

garpar.core.stocks_set.StocksSet

property delisted

Return a Series indicating if a stock has been delisted.

Returns:

Series with boolean values indicating delisted status.

Return type:

pd.Series

delisted_prune()

Return copy of the object with the delisted stocks removed.

Returns:

A pruned StocksSet instance.

Return type:

garpar.core.stocks_set.StocksSet

dprune()

Return copy of the object with the delisted stocks removed.

Returns:

A pruned StocksSet instance.

Return type:

garpar.core.stocks_set.StocksSet

property entropy

Return the entropy values as a pandas Series.

Returns:

Series of entropy values.

Return type:

pd.Series

classmethod from_prices(prices, *, weights=None, entropy=None, window_size=None, stocks=None, **metadata)

Alternative constructor for the StocksSet class.

Parameters:
  • prices (pd.DataFrame or array-like) – DataFrame or array-like object containing the prices of the assets.

  • weights (array-like, optional) – Array of asset weights in the stocks set.

  • entropy (array-like, optional) – Array of entropy values associated with the assets.

  • window_size (int or None, optional) – Window size for rolling calculations, if applicable.

  • stocks (array-like, optional) – List of stock names.

  • **metadata – Additional metadata related to the stocks set.

Returns:

A new StocksSet instance.

Return type:

garpar.core.stocks_set.StocksSet

property iloc

Access a group of days and stocks by positions.

.iloc[] is primarily integer position based (from 0 to length-1 of the axis), but may also be used with a boolean array.

property loc

Access a group of days and stocks by label(s) or a boolean array.

.loc[] is primarily label based, but may also be used with a boolean array.

property metadata

Return the metadata as a dict-like object.

Returns:

A dict like object containing metadata.

Return type:

garpar.utils.bunch.Bunch

refresh_entropy(*, entropy='shannon', entropy_kws=None)

Refresh entropy values using a specified entropy calculation method.

Parameters:
  • entropy (str or callable, optional) – Method or function to use for calculating entropy.

  • entropy_kws (dict, optional) – Additional keyword arguments for the entropy calculation function.

Returns:

A StocksSet instance with refreshed entropy values.

Return type:

garpar.core.stocks_set.StocksSet

scale_weights(*, scaler='proportion')

Scales the weights to a specified range.

Parameters:

scaler (str or callable, optional) – Method or function to use for scaling weights.

Returns:

A StocksSet instance with scaled weights.

Return type:

garpar.core.stocks_set.StocksSet

property shape

Return the shape of the price DataFrame.

Returns:

Shape of the price DataFrame.

Return type:

tuple

property stocks

Return the stocks in the stocks set.

Returns:

Array of stock names.

Return type:

np.ndarray

property stocks_number

Return the number of stocks in the stocks set.

Returns:

Number of stocks in the stocks set.

Return type:

int

to_dataframe()

Convert the StocksSet object to a pandas DataFrame.

Returns:

DataFrame representation of the StocksSet object.

Return type:

pd.DataFrame

to_hdf5(stream_or_buff, **kwargs)

Save the StocksSet to an HDF5 file.

Parameters:
  • stream_or_buff (str or file-like) – Path or file-like object to save the HDF5 file.

  • **kwargs – Additional arguments to pass to the HDF5 writer.

Return type:

None

property weights

Return the weights as a pandas Series.

Returns:

Series of asset weights.

Return type:

pd.Series

weights_prune(threshold=1e-09)

Return a pruned copy of the object based on weight threshold.

Parameters:

threshold (float, optional) – Threshold below which weights are considered insignificant.

Returns:

A pruned StocksSet instance.

Return type:

garpar.core.stocks_set.StocksSet

property window_size

Return the window size for rolling calculations.

Returns:

Window size for rolling calculations.

Return type:

int or None

wprune(threshold=1e-09)

Return a pruned copy of the object based on weight threshold.

Parameters:

threshold (float, optional) – Threshold below which weights are considered insignificant.

Returns:

A pruned StocksSet instance.

Return type:

garpar.core.stocks_set.StocksSet

garpar.core.stocks_set.mkss(prices, *, weights=None, entropy=None, window_size=None, stocks=None, **metadata)

Alternative constructor for the StocksSet class.

Parameters:
  • prices (pd.DataFrame or array-like) – DataFrame or array-like object containing the prices of the assets.

  • weights (array-like, optional) – Array of asset weights in the stocks set.

  • entropy (array-like, optional) – Array of entropy values associated with the assets.

  • window_size (int or None, optional) – Window size for rolling calculations, if applicable.

  • stocks (array-like, optional) – List of stock names.

  • **metadata – Additional metadata related to the stocks set.

Returns:

A new StocksSet instance.

Return type:

garpar.core.stocks_set.StocksSet

garpar.core.coercer_mixin module

Coercer mixin for Garpar project.

The coercer mixin module provides a specific mixin class used to coerce expected returns, weights, and covariance matrices into the desired formats.

Example

>>> from garpar import mkss
>>> ss = mkss([...])
>>> ss.covariance.sample_cov()
>>> ss.covariance.ledoit_wolf_cov()
>>> ss.covariance.oracle_approximating_cov()
>>> ss.correlation.sample_corr()
>>> ss.correlation.oracle_approximating_corr()
class garpar.core.coercer_mixin.CoercerMixin

Bases: object

A mixin class that contains utility methods for various accessors.

This class provides methods to coerce expected returns, weights, and covariance matrices into desired formats.

coerce_covariance_matrix(cov_matrix, kw, asarray=True)

Coerce covariance matrix into the desired format.

Parameters:
  • cov_matrix (None, str, or array-like) – The covariance matrix specification or values. If None, the sample covariance matrix is used.

  • kw (dict, optional) – Additional keyword arguments for the covariance matrix method, by default None.

  • asarray (bool, optional) – Whether to return the result as a numpy array, by default True.

Returns:

The coerced covariance matrix.

Return type:

array-like

coerce_expected_returns(expected_returns, kw, asarray=True)

Coerce expected returns into the desired format.

Parameters:
  • expected_returns (str or array-like) – The expected returns specification or values.

  • kw (dict) – Additional keyword arguments for the expected returns method.

  • asarray (bool, optional) – Whether to return the result as a numpy array, by default True.

Returns:

The coerced expected returns.

Return type:

array-like

coerce_weights(weights, asarray=True)

Coerce weights into the desired format.

Parameters:
  • weights (None, StocksSet, or array-like) – The weights specification or values. If None, equal weights are assigned.

  • asarray (bool, optional) – Whether to return the result as a numpy array, by default True.

Returns:

The coerced weights.

Return type:

array-like

garpar.core.covcorr_acc module

Covariance Accessor.

The covariance accessor module provides an accessor class to compute various covariance matrices. The module also defines the CorrelationAccessor class, which provides methods for calculating different correlation matrices.

Key Features:
  • Correlation and covariance analysis

Example

>>> import garpar
>>> ss = garpar.mkss(prices=[...])
>>> ss.covariance.sample_cov()
>>> ss.covariance.exp_cov()
>>> ss.covariance.semi_cov()
>>> ss.covariance.ledoit_wolf_cov()
>>> ss.covariance.oracle_approximating_cov()
>>> ss.correlation.sample_corr()
>>> ss.correlation.exp_corr()
>>> ss.correlation.semi_corr()
>>> ss.correlation.ledoit_wolf_corr()
>>> ss.correlation.oracle_approximating_corr()
class garpar.core.covcorr_acc.CorrelationAccessor(ss)

Bases: AccessorABC

Accessor class for calculating various correlation matrices.

exp_corr(**kwargs)

Compute the exponentially-weighted correlation matrix.

Parameters:

**kwargs – Additional keyword arguments passed to self._ss.covariance.exp_cov.

Returns:

Exponentially-weighted correlation matrix.

Return type:

pandas.DataFrame

ledoit_wolf_corr(**kwargs)

Compute the Ledoit-Wolf correlation matrix.

Parameters:

**kwargs – Additional keyword arguments passed to self._ss.covariance.ledoit_wolf_cov.

Returns:

Ledoit-Wolf correlation matrix.

Return type:

pandas.DataFrame

oracle_approximating_corr(**kwargs)

Compute the Oracle-approximating correlation matrix.

Parameters:

**kwargs – Additional keyword arguments passed to self._ss.covariance.oracle_approximating_cov.

Returns:

Oracle-approximating correlation matrix.

Return type:

pandas.DataFrame

sample_corr(**kwargs)

Compute the sample correlation matrix.

Parameters:

**kwargs – Additional keyword arguments passed to self._ss.covariance.sample_cov.

Returns:

Sample correlation matrix.

Return type:

pandas.DataFrame

semi_corr(**kwargs)

Compute the semi-correlation matrix.

Parameters:

**kwargs – Additional keyword arguments passed to self._ss.covariance.semi_cov.

Returns:

Semi-correlation matrix.

Return type:

pandas.DataFrame

class garpar.core.covcorr_acc.CovarianceAccessor(ss)

Bases: AccessorABC

Accessor class for calculating various covariance matrices.

exp_cov(**kwargs)

Compute the exponentially-weighted covariance matrix.

Parameters:

**kwargs – Additional keyword arguments passed to risk_models.exp_cov.

Returns:

Exponentially-weighted covariance matrix.

Return type:

pandas.DataFrame

ledoit_wolf_cov(shrinkage_target='constant_variance', **kwargs)

Compute the Ledoit-Wolf covariance matrix.

Compute the Ledoit-Wolf covariance matrix with optional shrinkage target

Parameters:
  • shrinkage_target (str, optional) – Shrinkage target for Ledoit-Wolf covariance estimation, default is “constant_variance”.

  • **kwargs – Additional keyword arguments passed to risk_models.CovarianceShrinkage.ledoit_wolf.

Returns:

Ledoit-Wolf covariance matrix.

Return type:

pandas.DataFrame

oracle_approximating_cov(**kwargs)

Compute the Oracle-approximating covariance matrix.

Parameters:

**kwargs – Additional keyword arguments passed to risk_models.CovarianceShrinkage.oracle_approximating.

Returns:

Oracle-approximating covariance matrix.

Return type:

pandas.DataFrame

sample_cov(**kwargs)

Compute the sample covariance matrix.

Parameters:

**kwargs – Additional keyword arguments passed to risk_models.sample_cov.

Returns:

Sample covariance matrix.

Return type:

pandas.DataFrame

semi_cov(**kwargs)

Compute the semi-covariance matrix.

Parameters:

**kwargs – Additional keyword arguments passed to risk_models.semicovariance.

Returns:

Semi-covariance matrix.

Return type:

pandas.DataFrame

garpar.core.div_acc module

Diversification Accessor.

The diversification accessor module provides an accessor class to compute diversification metrics for a given stocks set.

Key Features:
  • Diversification metrics calculation

Example

>>> import garpar
>>> ss = garpar.mkss(prices=[...])
>>> ss.diversification.ratio()
>>> ss.diversification.mrc()
>>> ss.diversification.pdi()
class garpar.core.div_acc.DiversificationMetricsAccessor(ss)

Bases: AccessorABC, CoercerMixin

A class to calculate various diversification metrics for a StocksSet.

cross_entropy(benchmark_weights=None)

Calculate cross entropy.

Parameters:

benchmark_weights (array-like, optional) – The benchmark weights to compare against.

Returns:

Cross entropy.

Return type:

float

Example

>>> accessor = DiversificationMetricsAccessor(ss)
>>> cross_entropy = accessor.cross_entropy()
ke_zang_entropy(*, covariance='sample_cov', covariance_kw=None)

Calculate Ke and Zang’s entropy.

Parameters:
  • covariance (str, optional) – The method to compute the covariance matrix, by default “sample_cov”.

  • covariance_kw (dict, optional) – Additional keyword arguments for the covariance method.

Returns:

Ke and Zang’s entropy.

Return type:

float

Example

>>> accessor = DiversificationMetricsAccessor(ss)
>>> entropy = accessor.ke_zang_entropy()
mrc(*, covariance='sample_cov', covariance_kw=None)

Calculate the marginal risk contribution.

Parameters:
  • covariance (str, optional) – The method to compute the covariance matrix, by default “sample_cov”.

  • covariance_kw (dict, optional) – Additional keyword arguments for the covariance method.

Returns:

The marginal risk contribution.

Return type:

Series

Example

>>> accessor = DiversificationMetricsAccessor(ss)
>>> mrc = accessor.mrc()
pdi(*, n_components=None, whiten=False, svd_solver='auto', tol=0.0, iterated_power='auto', n_oversamples=10, power_iteration_normalizer='auto', random_state=None)

Calculate the stocks set diversification index.

Parameters:
  • n_components (int, optional) – Number of components to keep, by default None.

  • whiten (bool, optional) – Whether to whiten the components, by default False.

  • svd_solver (str, optional) – The solver to use for SVD, by default “auto”.

  • tol (float, optional) – Tolerance for singular values, by default 0.0.

  • iterated_power (int or str, optional) – Number of iterations for power method, by default “auto”.

  • n_oversamples (int, optional) – Number of oversamples for randomized SVD, by default 10.

  • power_iteration_normalizer (str, optional) – Normalizer for power iterations, by default “auto”.

  • random_state (int, RandomState instance or None, optional) – Seed or random number generator for reproducibility, by default None.

Returns:

The stocks set diversification index.

Return type:

float

Example

>>> accessor = DiversificationMetricsAccessor(ss)
>>> pdi = accessor.pdi()
ratio(*, covariance='sample_cov', covariance_kw=None)

Calculate the diversification ratio.

Parameters:
  • covariance (str, optional) – The method to compute the covariance matrix, by default “sample_cov”.

  • covariance_kw (dict, optional) – Additional keyword arguments for the covariance method.

Returns:

The diversification ratio.

Return type:

float

Example

>>> accessor = DiversificationMetricsAccessor(ss)
>>> ratio = accessor.ratio()
zheng_entropy()

Calculate Zheng’s entropy.

Returns:

Zheng’s entropy.

Return type:

float

Example

>>> accessor = DiversificationMetricsAccessor(ss)
>>> entropy = accessor.zheng_entropy()

garpar.core.ereturns_acc module

Expected Returns Accessor.

The expected returns accessor module provides an accessor class with methods to compute expected returns for a given stocks set.

Key Features:
  • Expected returns estimation

Example

>>> import garpar
>>> ss = garpar.mkss(prices=[...])
>>> ss.expected_returns.capm()
>>> ss.expected_returns.mah()
>>> ss.expected_returns.emah()
class garpar.core.ereturns_acc.ExpectedReturnsAccessor(ss)

Bases: AccessorABC

Accessor class for computing expected returns of a stocks set.

capm(**kwargs)

Compute expected returns using the CAPM method.

Parameters:

**kwargs – Additional keyword arguments passed to expected_returns.capm_return.

Returns:

Series containing computed expected returns with name “CAPM”.

Return type:

pandas.Series

emah(**kwargs)

Compute expected returns using the emah method.

Compute expected returns using the exponential moving average historical method.

Parameters:

**kwargs (keyword arguments) – Additional keyword arguments passed to expected_returns.ema_historical_return. For example, you might pass parameters like span, min_periods, etc., which control the behavior of the exponential moving average calculation.

Returns:

A pandas Series containing the computed expected returns using the exponential moving average historical method, with the name “EMAH”.

Return type:

pandas.Series

mah(**kwargs)

Compute expected returns using the mean historical method.

Parameters:

**kwargs – Additional keyword arguments passed to expected_returns.mean_historical_return.

Returns:

Series containing computed expected returns with name “MAH”.

Return type:

pandas.Series

garpar.core.plot_acc module

Plot Accessor.

The plot accessor module provides an accessor class to visualize stocks set data, including line plots, heatmaps, and other visualizations.

Key Features:
  • Portfolio/market visualization tools

Example

>>> import garpar
>>> ss = garpar.mkss(prices=[...])
>>> ss.plot.line()
>>> ss.plot.heatmap()
class garpar.core.plot_acc.StocksSetPlotterAccessor(ss)

Bases: AccessorABC

Accessor class for plotting stocks set data.

box(returns=False, **kwargs)

Make a box plot of the stocks set.

A box plot is a method for graphically depicting groups of numerical data through their quartiles.

For further details see Wikipedia’s entry for boxplot.

Parameters:

**kwargs – Additional keyword arguments are passed and are documented in seaborn.boxplot.

Return type:

matplotlib.axes.Axes or numpy.ndarray of them

heatmap(returns=False, **kwargs)

Plot the stocks set matrix as a color-encoded matrix.

Parameters:

**kwargs – Additional keyword arguments are passed and are documented in seaborn.heatmap.

Return type:

matplotlib.axes.Axes or numpy.ndarray of them

hist(returns=False, **kwargs)

Draw one histogram of the stocks set.

A histogram is a representation of the distribution of data. This function groups the values of all given Series in the DataFrame into bins and draws all bins in one matplotlib.axes.Axes.

Parameters:

**kwargs – Additional keyword arguments are passed and are documented in seaborn.histplot.

Return type:

matplotlib.axes.Axes or numpy.ndarray of them

kde(returns=False, **kwargs)

Stock kernel density plot using Gaussian kernels.

In statistics, kernel density estimation (KDE) is a non-parametric way to estimate the probability density function (PDF) of a random variable. This function uses Gaussian kernels and includes automatic bandwidth determination.

Parameters:

**kwargs – Additional keyword arguments are passed and are documented in seaborn.kdeplot.

Return type:

matplotlib.axes.Axes or numpy.ndarray of them

line(returns=False, **kwargs)

Plot data as a line plot.

Parameters:
  • returns (bool, optional) – Whether to plot returns data (default is False).

  • **kwargs – Additional keyword arguments passed to seaborn.lineplot.

Returns:

The matplotlib Axes object containing the plot.

Return type:

matplotlib.axes.Axes

ogive(returns=False, **kwargs)

Plot data as an ogive (empirical cumulative distribution function).

Parameters:
  • returns (bool, optional) – Whether to plot returns data (default is False).

  • **kwargs – Additional keyword arguments passed to seaborn.ecdfplot.

Returns:

The matplotlib Axes object containing the plot.

Return type:

matplotlib.axes.Axes

wbox(**kwargs)

Make a box plot of the weights.

A box plot is a method for graphically depicting groups of numerical data through their quartiles.

For further details see Wikipedia’s entry for boxplot.

Parameters:

**kwargs – Additional keyword arguments are passed and are documented in seaborn.boxplot.

Return type:

matplotlib.axes.Axes or numpy.ndarray of them

wheatmap(**kwargs)

Plot weights as a color-encoded matrix.

Parameters:

**kwargs – Additional keyword arguments are passed and are documented in seaborn.heatmap.

Return type:

matplotlib.axes.Axes or numpy.ndarray of them

whist(**kwargs)

Draw one histogram of the weights.

A histogram is a representation of the distribution of data. This function groups the values of all given Series in the DataFrame into bins and draws all bins in one matplotlib.axes.Axes.

Parameters:

**kwargs – Additional keyword arguments are passed and are documented in seaborn.histplot.

Return type:

matplotlib.axes.Axes or numpy.ndarray of them

wkde(**kwargs)

Weights kernel density plot using Gaussian kernels.

In statistics, kernel density estimation (KDE) is a non-parametric way to estimate the probability density function (PDF) of a random variable. This function uses Gaussian kernels and includes automatic bandwidth determination.

Parameters:

**kwargs – Additional keyword arguments are passed and are documented in seaborn.kdeplot.

Return type:

matplotlib.axes.Axes or numpy.ndarray of them

garpar.core.prices_acc module

Prices Accessor.

The prices accessor module offers an accessor class to perform a variety of statistical and mathematical operations on stock prices, leveraging a predefined whitelist of permitted methods.

Key Features:
  • Price-related data and methods

Example

>>> import garpar
>>> ss = garpar.mkss(prices=[...])
>>> ss.prices.describe()
>>> ss.prices.log()
class garpar.core.prices_acc.PricesAccessor(ss)

Bases: AccessorABC

Accessor for price-related data and methods.

The PricesAccessor class provides a convenient interface to perform various statistical and mathematical operations on price data, using a predefined whitelist of allowable methods.

log()

Apply the natural logarithm to the price data.

Returns:

The natural logarithm of the price data.

Return type:

DataFrame

log10()

Apply the base 10 logarithm to the price data.

Returns:

The base 10 logarithm of the price data.

Return type:

DataFrame

log2()

Apply the base 2 logarithm to the price data.

Returns:

The base 2 logarithm of the price data.

Return type:

DataFrame

mad(skipna=True)

Return the mean absolute deviation of the values over a given axis.

Parameters:

skipna (bool, default True) – Exclude NA/null values when computing the result.

Returns:

The mean absolute deviation of the values.

Return type:

Series

mean_tendency_size()

Compute the mean size of consecutive winning or losing streaks.

Returns:

A Series with the mean streak size for each asset, representing the average length of consecutive up or down movements in returns.

Return type:

Series

garpar.core.risk_acc module

Risk Accessor.

The risk accessor module provides an accessor class to compute stock and stocks set betas, Treynor ratio, stocks set variance, Sharpe ratio, and Value at Risk (VaR).

Key Features:
  • Risk metrics calculation (variance, VaR, etc.)

Example

>>> import garpar
>>> ss = garpar.mkss(prices=[...])
>>> ss.risk.ss_beta()
>>> ss.risk.treynor_ratio()
>>> ss.risk.ss_variance()
>>> ss.risk.sharpe_ratio()
>>> ss.risk.value_at_risk()
class garpar.core.risk_acc.RiskAccessor(ss)

Bases: AccessorABC, CoercerMixin

Accessor for various risk metrics.

The RiskAccessor class provides methods to compute stock and stocks set betas, Treynor ratio, stocks set variance, Sharpe ratio, and Value at Risk (VaR).

sharpe_ratio(*, expected_returns='capm', covariance='sample_cov', expected_returns_kw=None, covariance_kw=None, **kwargs)

Compute the Sharpe ratio of the stocks set.

Parameters:
  • expected_returns (str, optional) – The method to compute the expected returns, by default ‘capm’.

  • covariance (str, optional) – The method to compute the covariance matrix, by default ‘sample_cov’.

  • expected_returns_kw (dict, optional) – Additional keyword arguments for the expected returns method, by default None.

  • covariance_kw (dict, optional) – Additional keyword arguments for the covariance method, by default None.

  • **kwargs – Additional keyword arguments.

Returns:

The Sharpe ratio of the stocks set.

Return type:

float

ss_beta(*, benchmark_weights=None, log_returns=False)

Compute the beta of the entire stocks set.

Parameters:
  • benchmark_weights (array-like, optional) – The weights of the benchmark stocks set, by default None.

  • log_returns (bool, optional) – Whether to compute log returns, by default False.

Returns:

The beta of the stocks set.

Return type:

float

ss_var(covariance='sample_cov', covariance_kw=None)

Compute the variance of the stocks set.

Parameters:
  • covariance (str, optional) – The method to compute the covariance matrix, by default ‘sample_cov’.

  • covariance_kw (dict, optional) – Additional keyword arguments for the covariance method, by default None.

Returns:

The variance of the stocks set.

Return type:

float

stock_beta(market_prices=None, log_returns=False)

Compute the beta of individual stocks in the stocks set.

Parameters:
  • market_prices (DataFrame, optional) – Market prices data, by default None.

  • log_returns (bool, optional) – Whether to compute log returns, by default False.

Returns:

The beta values for individual stocks.

Return type:

Series

stocks_set_beta(*, benchmark_weights=None, log_returns=False)

Compute the beta of the entire stocks set.

Parameters:
  • benchmark_weights (array-like, optional) – The weights of the benchmark stocks set, by default None.

  • log_returns (bool, optional) – Whether to compute log returns, by default False.

Returns:

The beta of the stocks set.

Return type:

float

stocks_set_variance(covariance='sample_cov', covariance_kw=None)

Compute the variance of the stocks set.

Parameters:
  • covariance (str, optional) – The method to compute the covariance matrix, by default ‘sample_cov’.

  • covariance_kw (dict, optional) – Additional keyword arguments for the covariance method, by default None.

Returns:

The variance of the stocks set.

Return type:

float

treynor_ratio(*, expected_returns='capm', expected_returns_kw=None, negative=True, benchmark_weights=None, log_returns=False)

Compute the Treynor ratio of the stocks set.

Parameters:
  • expected_returns (str, optional) – The method to compute the expected returns, by default ‘capm’.

  • expected_returns_kw (dict, optional) – Additional keyword arguments for the expected returns method, by default None.

  • negative (bool, optional) – Whether to return the negative of the Treynor ratio, by default True.

  • benchmark_weights (array-like, optional) – The weights of the benchmark stocks set, by default None.

  • log_returns (bool, optional) – Whether to compute log returns, by default False.

Returns:

The Treynor ratio of the stocks set.

Return type:

float

value_at_risk(*, alpha=0.05)

Compute the Value at Risk (VaR) of the stocks set.

Parameters:

alpha (float, optional) – The significance level, by default 0.05.

Returns:

The Value at Risk (VaR) for each stock in the stocks set.

Return type:

Series

var(*, alpha=0.05)

Compute the Value at Risk (VaR) of the stocks set.

Parameters:

alpha (float, optional) – The significance level, by default 0.05.

Returns:

The Value at Risk (VaR) for each stock in the stocks set.

Return type:

Series

garpar.core.utilities_acc module

Utilities Accessor.

The utlities accessor module provides an accessor class to compute ex-ante tracking error, ex-post tracking error, stocks set return, and quadratic utility for a given stocks set.

Key Features:
  • Utility metrics calculation

Example

>>> import garpar
>>> ss = garpar.mkss(prices=[...])
>>> ss.utilities.ex_ante_tracking_error()
>>> ss.utilities.ex_post_tracking_error()
>>> ss.utilities.ss_return()
>>> ss.utilities.quadratic_utility()
class garpar.core.utilities_acc.UtilitiesAccessor(ss)

Bases: AccessorABC, CoercerMixin

Accessor for various utility and performance metrics.

The UtilitiesAccessor class provides methods to compute ex-ante tracking error, ex-post tracking error, stocks set return, and quadratic utility for a given stocks set.

ex_ante_tracking_error(*, covariance='sample_cov', covariance_kw=None, benchmark_weights=None)

Compute the ex-ante tracking error of the stocks set.

Parameters:
  • covariance (str, optional) – The method to compute the covariance matrix, by default ‘sample_cov’.

  • covariance_kw (dict, optional) – Additional keyword arguments for the covariance method, by default None.

  • benchmark_weights (array-like, optional) – The weights of the benchmark stocks set, by default None.

Returns:

The ex-ante tracking error of the stocks set.

Return type:

float

ex_post_tracking_error(*, historic_returns='capm', benchmark_returns='capm', historic_returns_kw=None, benchmark_returns_kw=None)

Compute the ex-post tracking error of the stocks set.

Parameters:
  • historic_returns (str, optional) – The method to compute the historic returns, by default ‘capm’.

  • benchmark_returns (str, optional) – The method to compute the benchmark returns, by default ‘capm’.

  • historic_returns_kw (dict, optional) – Additional keyword arguments for the historic returns method, by default None.

  • benchmark_returns_kw (dict, optional) – Additional keyword arguments for the benchmark returns method, by default None.

Returns:

The ex-post tracking error of the stocks set.

Return type:

float

quadratic_utility(*, expected_returns='capm', covariance='sample_cov', risk_aversion=0.5, expected_returns_kw=None, covariance_kw=None, **kwargs)

Compute the quadratic utility of the stocks set.

Parameters:
  • expected_returns (str, optional) – The method to compute the expected returns, by default ‘capm’.

  • covariance (str, optional) – The method to compute the covariance matrix, by default ‘sample_cov’.

  • risk_aversion (float, optional) – The risk aversion coefficient, by default 0.5.

  • expected_returns_kw (dict, optional) – Additional keyword arguments for the expected returns method, by default None.

  • covariance_kw (dict, optional) – Additional keyword arguments for the covariance method, by default None.

  • **kwargs – Additional keyword arguments.

Returns:

The quadratic utility of the stocks set.

Return type:

float

qutility(*, expected_returns='capm', covariance='sample_cov', risk_aversion=0.5, expected_returns_kw=None, covariance_kw=None, **kwargs)

Compute the quadratic utility of the stocks set.

Parameters:
  • expected_returns (str, optional) – The method to compute the expected returns, by default ‘capm’.

  • covariance (str, optional) – The method to compute the covariance matrix, by default ‘sample_cov’.

  • risk_aversion (float, optional) – The risk aversion coefficient, by default 0.5.

  • expected_returns_kw (dict, optional) – Additional keyword arguments for the expected returns method, by default None.

  • covariance_kw (dict, optional) – Additional keyword arguments for the covariance method, by default None.

  • **kwargs – Additional keyword arguments.

Returns:

The quadratic utility of the stocks set.

Return type:

float

ss_return(*, expected_returns='capm', expected_returns_kw=None, negative=True)

Compute the expected return of the stocks set.

Parameters:
  • expected_returns (str, optional) – The method to compute the expected returns, by default ‘capm’.

  • expected_returns_kw (dict, optional) – Additional keyword arguments for the expected returns method, by default None.

  • negative (bool, optional) – Whether to return the negative of the expected return, by default True.

Returns:

The expected return of the stocks set.

Return type:

float

stocks_set_return(*, expected_returns='capm', expected_returns_kw=None, negative=True)

Compute the expected return of the stocks set.

Parameters:
  • expected_returns (str, optional) – The method to compute the expected returns, by default ‘capm’.

  • expected_returns_kw (dict, optional) – Additional keyword arguments for the expected returns method, by default None.

  • negative (bool, optional) – Whether to return the negative of the expected return, by default True.

Returns:

The expected return of the stocks set.

Return type:

float