Conditional Value at Risk

Minimum CVaR

class
skportfolio.frontier._efficientfrontier.MinimumCVar(returns_data=False, frequency=252, weight_bounds=(0, 1), l2_gamma=0.0, beta=0.95, rets_estimator=MeanHistoricalLinearReturns(), market_neutral=False)
Bases
skportfolio.frontier._efficientfrontier._EfficientCVarEstimator skportfolio.frontier._mixins._EfficientCVarMixin skportfolio.frontier._mixins._BaseFrontierMixin abc.ABC skportfolio.frontier._efficientfrontier._BaseCVarCDarEstimator skportfolio.frontier._efficientfrontier._BaseEfficientFrontierPortfolioEstimator skportfolio._base.PortfolioEstimator sklearn.base.BaseEstimator

Minimum Conditional Var portfolio

Classes
  • ABCMeta Metaclass for defining Abstract Base Classes (ABCs).
Methods
  • add_constraints(cnstr) (object) Add a list of constraints to the convex optimization problem
  • estimate_frontier(X, num_portfolios, random_seed) (tuple) Estimates the efficient frontier given either returns or prices (depending on self.returns_data attribute), and number of points along the frontier. It always starts from the least risky portfolio and increasing the portfolio returns, it looks for the efficient risk portfolio until the riskiest portfolio (and the one with the highest return) is met.
  • fit(X, y) (self) Fit the portfolio model from asset prices.
  • get_params(deep) (params : dict) Get parameters for this estimator.
  • predict(X) (pd.Series) Applies the estimated weights to the prices to get the portfolio value. In other words, generates the equity curve of the portfolio.
  • score(X, y, **kwargs) (float) Score the portfolio using one of the metrics expressed as PortfolioScorer in the metrics module.
  • set_dummy_weights(X) (A series of assets with NaN weights.) Creates weights with NaN values, typically used when method cannot converge or solution is unfeasible.
  • set_params(**params) (self : estimator instance) Set the parameters of this estimator.
  • set_returns_data(returns_data) Inform subsequent .fit method that the input data X are returns, otherwise prices are expected. Some portfolio estimators work independently with both, but is very important to specify what is contained in the .fit argument X.
  • set_returns_estimator(rets_est) (self) Modify the base returns estimator with a specified rets_est
  • set_risk_estimator(risk_est) (self) Modify the base risk estimator with a new risk estimator
method
get_params(deep=True)

Get parameters for this estimator.

Parameters
  • deep (bool, default=True) If True, will return the parameters for this estimator and contained subobjects that are estimators.
Returns (params : dict)

Parameter names mapped to their values.

method
set_params(**params)

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects (such as :class:~sklearn.pipeline.Pipeline). The latter have parameters of the form <component>__<parameter> so that it's possible to update each component of a nested object.

Parameters
  • **params (dict) Estimator parameters.
Returns (self : estimator instance)

Estimator instance.

method
predict(X)

Applies the estimated weights to the prices to get the portfolio value. In other words, generates the equity curve of the portfolio.

Parameters
  • X (pd.DataFrame) The prices expressed as a pandas dataframe
Returns (pd.Series)

The estimated portfolio value time series

method
score(X, y=None, **kwargs)

Score the portfolio using one of the metrics expressed as PortfolioScorer in the metrics module.

Parameters
  • X (pd.DataFrame) Dataframe with asset prices. Do not feed returns here!
  • **kwargs (Dict) Additional parameters to specify to the portfolio returns scorer, like risk_free_rate for Sharpe ratio. Alternatively you can also specify the score function to be used, like sharpe_ratio, or sortino_ratio
Returns (float)

The specific score value from the specified, Sharpe ratio is returned if not specified.

method
set_dummy_weights(X)

Creates weights with NaN values, typically used when method cannot converge or solution is unfeasible.

Parameters
  • X (pd.DataFrame) Prices or returns data, only used to pick asset names
method
set_returns_data(returns_data=False)

Inform subsequent .fit method that the input data X are returns, otherwise prices are expected. Some portfolio estimators work independently with both, but is very important to specify what is contained in the .fit argument X.

method
set_returns_estimator(rets_est)

Modify the base returns estimator with a specified rets_est

Parameters
  • rets_est (BaseReturnsEstimator) The new returns estimator
method
set_risk_estimator(risk_est)

Modify the base risk estimator with a new risk estimator

Parameters
  • risk_est (BaseRiskEstimator) The new risk estimator
class
abc.ABCMeta(name, bases, namespace, **kwargs)

Metaclass for defining Abstract Base Classes (ABCs).

Use this metaclass to create an ABC. An ABC can be subclassed directly, and then acts as a mix-in class. You can also register unrelated concrete classes (even built-in classes) and unrelated ABCs as 'virtual subclasses' -- these and their descendants will be considered subclasses of the registering ABC by the built-in issubclass() function, but the registering ABC won't show up in their MRO (Method Resolution Order) nor will method implementations defined by the registering ABC be callable (not even via super()).

Methods
  • __instancecheck__(cls, instance) Override for isinstance(instance, cls).
  • __subclasscheck__(cls, subclass) Override for issubclass(subclass, cls).
  • register(cls, subclass) Register a virtual subclass of an ABC.
staticmethod
register(cls, subclass)

Register a virtual subclass of an ABC.

Returns the subclass, to allow usage as a class decorator.

staticmethod
__instancecheck__(cls, instance)

Override for isinstance(instance, cls).

staticmethod
__subclasscheck__(cls, subclass)

Override for issubclass(subclass, cls).

method
estimate_frontier(X, num_portfolios=20, random_seed=None)

Estimates the efficient frontier given either returns or prices (depending on self.returns_data attribute), and number of points along the frontier. It always starts from the least risky portfolio and increasing the portfolio returns, it looks for the efficient risk portfolio until the riskiest portfolio (and the one with the highest return) is met.

Parameters
  • X (pd.DataFrame) The prices or returns to fit multiple times the efficient risk/return portfolio
  • num_portfolios (int) Number of portfolios along the frontier.
  • random_seed (int, optional) Only when the portfolio returns estimator is PerturbedReturns, this is needed to lock the same stochastic sample of the expected returns across the entire frontier.
Returns (tuple)

The first two elements represent, the risk and return coordinates of the portfolios along the efficient frontier. The last element contains the portfolio weights. Portfolios are indexed from the least risky to the maximum return along the frontier.

Examples

If you need to compute the efficient frontier for the Markowitz Mean-Variance portfolio for 128 points using 16 parallel CPU cores you can simply do:

>>> from skportfolio import MinimumVolatility
>>> from skportfolio.datasets import load_tech_stock_prices
>>> MinimumVolatility().estimate_frontier(load_tech_stock_prices(), num_portfolios=128)
method
add_constraints(cnstr)

Add a list of constraints to the convex optimization problem

Parameters
  • cnstr (list) List of constraints, to be added to the optimization problem
Returns (object)

The portfolio estimator object

method
fit(X, y=None)

Fit the portfolio model from asset prices.

Parameters
  • X (pd.DataFrame) Asset prices
  • y (None) There for compatibility
Returns (self)

The current estimator

Efficient return optimization on CVaR frontier

class
skportfolio.frontier._efficientfrontier.CVarEfficientReturn(returns_data=False, frequency=252, weight_bounds=(0, 1), l2_gamma=0.0, beta=0.95, rets_estimator=MeanHistoricalLinearReturns(), market_neutral=False, target_return=0.02)
Bases
skportfolio.frontier._mixins._TargetReturnMixin skportfolio.frontier._efficientfrontier._EfficientCVarEstimator skportfolio.frontier._mixins._EfficientCVarMixin skportfolio.frontier._mixins._BaseFrontierMixin abc.ABC skportfolio.frontier._efficientfrontier._BaseCVarCDarEstimator skportfolio.frontier._efficientfrontier._BaseEfficientFrontierPortfolioEstimator skportfolio._base.PortfolioEstimator sklearn.base.BaseEstimator

Efficient return at given target CVar

Classes
  • ABCMeta Metaclass for defining Abstract Base Classes (ABCs).
Methods
  • add_constraints(cnstr) (object) Add a list of constraints to the convex optimization problem
  • estimate_frontier(X, num_portfolios, random_seed) (tuple) Estimates the efficient frontier given either returns or prices (depending on self.returns_data attribute), and number of points along the frontier. It always starts from the least risky portfolio and increasing the portfolio returns, it looks for the efficient risk portfolio until the riskiest portfolio (and the one with the highest return) is met.
  • fit(X, y) (self) Fit the portfolio model from asset prices.
  • get_params(deep) (params : dict) Get parameters for this estimator.
  • predict(X) (pd.Series) Applies the estimated weights to the prices to get the portfolio value. In other words, generates the equity curve of the portfolio.
  • score(X, y, **kwargs) (float) Score the portfolio using one of the metrics expressed as PortfolioScorer in the metrics module.
  • set_dummy_weights(X) (A series of assets with NaN weights.) Creates weights with NaN values, typically used when method cannot converge or solution is unfeasible.
  • set_params(**params) (self : estimator instance) Set the parameters of this estimator.
  • set_returns_data(returns_data) Inform subsequent .fit method that the input data X are returns, otherwise prices are expected. Some portfolio estimators work independently with both, but is very important to specify what is contained in the .fit argument X.
  • set_returns_estimator(rets_est) (self) Modify the base returns estimator with a specified rets_est
  • set_risk_estimator(risk_est) (self) Modify the base risk estimator with a new risk estimator
method
get_params(deep=True)

Get parameters for this estimator.

Parameters
  • deep (bool, default=True) If True, will return the parameters for this estimator and contained subobjects that are estimators.
Returns (params : dict)

Parameter names mapped to their values.

method
set_params(**params)

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects (such as :class:~sklearn.pipeline.Pipeline). The latter have parameters of the form <component>__<parameter> so that it's possible to update each component of a nested object.

Parameters
  • **params (dict) Estimator parameters.
Returns (self : estimator instance)

Estimator instance.

method
predict(X)

Applies the estimated weights to the prices to get the portfolio value. In other words, generates the equity curve of the portfolio.

Parameters
  • X (pd.DataFrame) The prices expressed as a pandas dataframe
Returns (pd.Series)

The estimated portfolio value time series

method
score(X, y=None, **kwargs)

Score the portfolio using one of the metrics expressed as PortfolioScorer in the metrics module.

Parameters
  • X (pd.DataFrame) Dataframe with asset prices. Do not feed returns here!
  • **kwargs (Dict) Additional parameters to specify to the portfolio returns scorer, like risk_free_rate for Sharpe ratio. Alternatively you can also specify the score function to be used, like sharpe_ratio, or sortino_ratio
Returns (float)

The specific score value from the specified, Sharpe ratio is returned if not specified.

method
set_dummy_weights(X)

Creates weights with NaN values, typically used when method cannot converge or solution is unfeasible.

Parameters
  • X (pd.DataFrame) Prices or returns data, only used to pick asset names
method
set_returns_data(returns_data=False)

Inform subsequent .fit method that the input data X are returns, otherwise prices are expected. Some portfolio estimators work independently with both, but is very important to specify what is contained in the .fit argument X.

method
set_returns_estimator(rets_est)

Modify the base returns estimator with a specified rets_est

Parameters
  • rets_est (BaseReturnsEstimator) The new returns estimator
method
set_risk_estimator(risk_est)

Modify the base risk estimator with a new risk estimator

Parameters
  • risk_est (BaseRiskEstimator) The new risk estimator
class
abc.ABCMeta(name, bases, namespace, **kwargs)

Metaclass for defining Abstract Base Classes (ABCs).

Use this metaclass to create an ABC. An ABC can be subclassed directly, and then acts as a mix-in class. You can also register unrelated concrete classes (even built-in classes) and unrelated ABCs as 'virtual subclasses' -- these and their descendants will be considered subclasses of the registering ABC by the built-in issubclass() function, but the registering ABC won't show up in their MRO (Method Resolution Order) nor will method implementations defined by the registering ABC be callable (not even via super()).

Methods
  • __instancecheck__(cls, instance) Override for isinstance(instance, cls).
  • __subclasscheck__(cls, subclass) Override for issubclass(subclass, cls).
  • register(cls, subclass) Register a virtual subclass of an ABC.
staticmethod
register(cls, subclass)

Register a virtual subclass of an ABC.

Returns the subclass, to allow usage as a class decorator.

staticmethod
__instancecheck__(cls, instance)

Override for isinstance(instance, cls).

staticmethod
__subclasscheck__(cls, subclass)

Override for issubclass(subclass, cls).

method
estimate_frontier(X, num_portfolios=20, random_seed=None)

Estimates the efficient frontier given either returns or prices (depending on self.returns_data attribute), and number of points along the frontier. It always starts from the least risky portfolio and increasing the portfolio returns, it looks for the efficient risk portfolio until the riskiest portfolio (and the one with the highest return) is met.

Parameters
  • X (pd.DataFrame) The prices or returns to fit multiple times the efficient risk/return portfolio
  • num_portfolios (int) Number of portfolios along the frontier.
  • random_seed (int, optional) Only when the portfolio returns estimator is PerturbedReturns, this is needed to lock the same stochastic sample of the expected returns across the entire frontier.
Returns (tuple)

The first two elements represent, the risk and return coordinates of the portfolios along the efficient frontier. The last element contains the portfolio weights. Portfolios are indexed from the least risky to the maximum return along the frontier.

Examples

If you need to compute the efficient frontier for the Markowitz Mean-Variance portfolio for 128 points using 16 parallel CPU cores you can simply do:

>>> from skportfolio import MinimumVolatility
>>> from skportfolio.datasets import load_tech_stock_prices
>>> MinimumVolatility().estimate_frontier(load_tech_stock_prices(), num_portfolios=128)
method
add_constraints(cnstr)

Add a list of constraints to the convex optimization problem

Parameters
  • cnstr (list) List of constraints, to be added to the optimization problem
Returns (object)

The portfolio estimator object

method
fit(X, y=None)

Fit the portfolio model from asset prices.

Parameters
  • X (pd.DataFrame) Asset prices
  • y (None) There for compatibility
Returns (self)

The current estimator

Efficient risk optimization on CDaR frontier

class
skportfolio.frontier._efficientfrontier.CVarEfficientRisk(returns_data=False, frequency=252, weight_bounds=(0, 1), l2_gamma=0.0, beta=0.95, rets_estimator=MeanHistoricalLinearReturns(), market_neutral=False, target_risk=0.02)
Bases
skportfolio.frontier._mixins._TargetRiskMixin skportfolio.frontier._efficientfrontier._EfficientCVarEstimator skportfolio.frontier._mixins._EfficientCVarMixin skportfolio.frontier._mixins._BaseFrontierMixin abc.ABC skportfolio.frontier._efficientfrontier._BaseCVarCDarEstimator skportfolio.frontier._efficientfrontier._BaseEfficientFrontierPortfolioEstimator skportfolio._base.PortfolioEstimator sklearn.base.BaseEstimator

Efficient CVar at given target return

Classes
  • ABCMeta Metaclass for defining Abstract Base Classes (ABCs).
Methods
  • add_constraints(cnstr) (object) Add a list of constraints to the convex optimization problem
  • estimate_frontier(X, num_portfolios, random_seed) (tuple) Estimates the efficient frontier given either returns or prices (depending on self.returns_data attribute), and number of points along the frontier. It always starts from the least risky portfolio and increasing the portfolio returns, it looks for the efficient risk portfolio until the riskiest portfolio (and the one with the highest return) is met.
  • fit(X, y) (self) Fit the portfolio model from asset prices.
  • get_params(deep) (params : dict) Get parameters for this estimator.
  • predict(X) (pd.Series) Applies the estimated weights to the prices to get the portfolio value. In other words, generates the equity curve of the portfolio.
  • score(X, y, **kwargs) (float) Score the portfolio using one of the metrics expressed as PortfolioScorer in the metrics module.
  • set_dummy_weights(X) (A series of assets with NaN weights.) Creates weights with NaN values, typically used when method cannot converge or solution is unfeasible.
  • set_params(**params) (self : estimator instance) Set the parameters of this estimator.
  • set_returns_data(returns_data) Inform subsequent .fit method that the input data X are returns, otherwise prices are expected. Some portfolio estimators work independently with both, but is very important to specify what is contained in the .fit argument X.
  • set_returns_estimator(rets_est) (self) Modify the base returns estimator with a specified rets_est
  • set_risk_estimator(risk_est) (self) Modify the base risk estimator with a new risk estimator
method
get_params(deep=True)

Get parameters for this estimator.

Parameters
  • deep (bool, default=True) If True, will return the parameters for this estimator and contained subobjects that are estimators.
Returns (params : dict)

Parameter names mapped to their values.

method
set_params(**params)

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects (such as :class:~sklearn.pipeline.Pipeline). The latter have parameters of the form <component>__<parameter> so that it's possible to update each component of a nested object.

Parameters
  • **params (dict) Estimator parameters.
Returns (self : estimator instance)

Estimator instance.

method
predict(X)

Applies the estimated weights to the prices to get the portfolio value. In other words, generates the equity curve of the portfolio.

Parameters
  • X (pd.DataFrame) The prices expressed as a pandas dataframe
Returns (pd.Series)

The estimated portfolio value time series

method
score(X, y=None, **kwargs)

Score the portfolio using one of the metrics expressed as PortfolioScorer in the metrics module.

Parameters
  • X (pd.DataFrame) Dataframe with asset prices. Do not feed returns here!
  • **kwargs (Dict) Additional parameters to specify to the portfolio returns scorer, like risk_free_rate for Sharpe ratio. Alternatively you can also specify the score function to be used, like sharpe_ratio, or sortino_ratio
Returns (float)

The specific score value from the specified, Sharpe ratio is returned if not specified.

method
set_dummy_weights(X)

Creates weights with NaN values, typically used when method cannot converge or solution is unfeasible.

Parameters
  • X (pd.DataFrame) Prices or returns data, only used to pick asset names
method
set_returns_data(returns_data=False)

Inform subsequent .fit method that the input data X are returns, otherwise prices are expected. Some portfolio estimators work independently with both, but is very important to specify what is contained in the .fit argument X.

method
set_returns_estimator(rets_est)

Modify the base returns estimator with a specified rets_est

Parameters
  • rets_est (BaseReturnsEstimator) The new returns estimator
method
set_risk_estimator(risk_est)

Modify the base risk estimator with a new risk estimator

Parameters
  • risk_est (BaseRiskEstimator) The new risk estimator
class
abc.ABCMeta(name, bases, namespace, **kwargs)

Metaclass for defining Abstract Base Classes (ABCs).

Use this metaclass to create an ABC. An ABC can be subclassed directly, and then acts as a mix-in class. You can also register unrelated concrete classes (even built-in classes) and unrelated ABCs as 'virtual subclasses' -- these and their descendants will be considered subclasses of the registering ABC by the built-in issubclass() function, but the registering ABC won't show up in their MRO (Method Resolution Order) nor will method implementations defined by the registering ABC be callable (not even via super()).

Methods
  • __instancecheck__(cls, instance) Override for isinstance(instance, cls).
  • __subclasscheck__(cls, subclass) Override for issubclass(subclass, cls).
  • register(cls, subclass) Register a virtual subclass of an ABC.
staticmethod
register(cls, subclass)

Register a virtual subclass of an ABC.

Returns the subclass, to allow usage as a class decorator.

staticmethod
__instancecheck__(cls, instance)

Override for isinstance(instance, cls).

staticmethod
__subclasscheck__(cls, subclass)

Override for issubclass(subclass, cls).

method
estimate_frontier(X, num_portfolios=20, random_seed=None)

Estimates the efficient frontier given either returns or prices (depending on self.returns_data attribute), and number of points along the frontier. It always starts from the least risky portfolio and increasing the portfolio returns, it looks for the efficient risk portfolio until the riskiest portfolio (and the one with the highest return) is met.

Parameters
  • X (pd.DataFrame) The prices or returns to fit multiple times the efficient risk/return portfolio
  • num_portfolios (int) Number of portfolios along the frontier.
  • random_seed (int, optional) Only when the portfolio returns estimator is PerturbedReturns, this is needed to lock the same stochastic sample of the expected returns across the entire frontier.
Returns (tuple)

The first two elements represent, the risk and return coordinates of the portfolios along the efficient frontier. The last element contains the portfolio weights. Portfolios are indexed from the least risky to the maximum return along the frontier.

Examples

If you need to compute the efficient frontier for the Markowitz Mean-Variance portfolio for 128 points using 16 parallel CPU cores you can simply do:

>>> from skportfolio import MinimumVolatility
>>> from skportfolio.datasets import load_tech_stock_prices
>>> MinimumVolatility().estimate_frontier(load_tech_stock_prices(), num_portfolios=128)
method
add_constraints(cnstr)

Add a list of constraints to the convex optimization problem

Parameters
  • cnstr (list) List of constraints, to be added to the optimization problem
Returns (object)

The portfolio estimator object

method
fit(X, y=None)

Fit the portfolio model from asset prices.

Parameters
  • X (pd.DataFrame) Asset prices
  • y (None) There for compatibility
Returns (self)

The current estimator