Mean Variance Optimization - efficient frontier API

Minimum Volatility

class
skportfolio.frontier._efficientfrontier.MinimumVolatility(returns_data=False, frequency=252, weight_bounds=(0, 1), l2_gamma=0.0, risk_estimator=SampleCovariance())
Bases
skportfolio.frontier._efficientfrontier._BaseMeanVariancePortfolio skportfolio.frontier._efficientfrontier._BaseEfficientFrontierPortfolioEstimator skportfolio._base.PortfolioEstimator sklearn.base.BaseEstimator skportfolio.frontier._mixins._EfficientMeanVarianceMixin skportfolio.frontier._mixins._BaseFrontierMixin

Minimum volatility (minimum variance) portfolio. It does not need estimates of the expected returns, but only estimation of the covariance matrix. The following optimization problem is being solved.

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.
  • risk_reward(model) Computes the risk-return for the current 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
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
risk_reward(model=None)

Computes the risk-return for the current portfolio

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

MeanVarianceEfficientRisk

class
skportfolio.frontier._efficientfrontier.MeanVarianceEfficientRisk(returns_data=False, frequency=252, weight_bounds=(0, 1), l2_gamma=0.0, risk_estimator=SampleCovariance(), rets_estimator=MeanHistoricalLinearReturns(), target_risk=0.02)
Bases
skportfolio.frontier._mixins._TargetRiskMixin skportfolio.frontier._efficientfrontier._BaseMeanVariancePortfolio skportfolio.frontier._efficientfrontier._BaseEfficientFrontierPortfolioEstimator skportfolio._base.PortfolioEstimator sklearn.base.BaseEstimator skportfolio.frontier._mixins._EfficientMeanVarianceMixin skportfolio.frontier._mixins._BaseFrontierMixin

Efficient risk in the Markowitz's Mean Variance framework.

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, **kwargs) (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.
  • risk_reward(model) Computes the risk-return for the current 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
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
risk_reward(model=None)

Computes the risk-return for the current portfolio

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

Fit the portfolio model from asset prices.

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

The current estimator

MeanVarianceEfficientReturn

class
skportfolio.frontier._efficientfrontier.MeanVarianceEfficientReturn(returns_data=False, frequency=252, weight_bounds=(0, 1), l2_gamma=0.0, risk_estimator=SampleCovariance(), rets_estimator=MeanHistoricalLinearReturns(), target_return=0.02)
Bases
skportfolio.frontier._mixins._TargetReturnMixin skportfolio.frontier._efficientfrontier._BaseMeanVariancePortfolio skportfolio.frontier._efficientfrontier._BaseEfficientFrontierPortfolioEstimator skportfolio._base.PortfolioEstimator sklearn.base.BaseEstimator skportfolio.frontier._mixins._EfficientMeanVarianceMixin skportfolio.frontier._mixins._BaseFrontierMixin

Base class for all estimators in scikit-learn.

Notes

All estimators should specify all the parameters that can be set at the class level in their __init__ as explicit keyword arguments (no *args or **kwargs).

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, **kwargs) (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.
  • risk_reward(model) Computes the risk-return for the current 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
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
risk_reward(model=None)

Computes the risk-return for the current portfolio

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

Fit the portfolio model from asset prices.

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

The current estimator