azapy.Analyzers package¶
Submodules¶
azapy.Analyzers.BTADAnalyzer module¶
- class azapy.Analyzers.BTADAnalyzer.BTADAnalyzer(alpha=[0.0], coef=None, mktdata=None, colname='adjusted', freq='Q', hlength=3.25, name='BTAD', rtype='Sharpe', mu=None, d=1, mu0=0.0, aversion=None, ww0=None, detrended=False, method='ecos')
Bases:
_RiskAnalyzer
Mixture BTAD (Below Threshold Absolute Deviation) based optimal portfolio strategies.
- Attributes
status : int - the computation status (0 - success, any other value signifies an error)
ww : pandas.Series - the portfolio weights
RR : float - portfolio rate of return
risk : float - portfolio mBTAD risk
primary_risk_comp : list - portfolio mBTAD components
secondary_risk_comp : list - portfolio thresholds, alpha (input values)
sharpe : float - Omega ration if rtype is set to ‘Shapre’ or ‘Sharpe2’ otherwise None.
diverse : float - diversification factor if rtype is set to ‘Divers’ or ‘MaxDivers’ otherwise None.
name : str - portfolio name
- Note the following 2 important methods:
getWeights : Computes the optimal portfolio weights. During its computations the following class members are also set: risk, primery_risk_comp, secondary_risk_comp, sharpe, RR, divers.
getPositions : Provides practical information regarding the portfolio rebalancing delta positions and costs.
Methods
getDiversification
(ww[, rrate])Returns the value of the diversification factor for a give portfolio.
getPositions
([nshares, cash, ww, verbose])Computes the rebalanced number of shares.
getRisk
(ww[, rrate])Returns the value of the dispersion (risk) measure for a give portfolio.
Returns the risk of each portfolio component.
getWeights
([rtype, mu, d, mu0, aversion, ...])Computes the optimal portfolio weights.
set_method
(method)Sets computation method.
set_mktdata
(mktdata[, colname, freq, ...])Sets historical market data.
set_random_seed
([seed])Sets the seed for Dirichlet random generator used in viewFrontiers to select the random inefficient portfolios.
set_rrate
(rrate)Sets portfolio components historical rates of return.
set_rtype
([rtype, mu, d, mu0, aversion, ww0])Sets the optimization type.
viewFrontiers
([minrisk, efficient, ...])Computes the elements of the portfolio frontiers.
- __init__(alpha=[0.0], coef=None, mktdata=None, colname='adjusted', freq='Q', hlength=3.25, name='BTAD', rtype='Sharpe', mu=None, d=1, mu0=0.0, aversion=None, ww0=None, detrended=False, method='ecos')
Constructor
- Parameters:
- alphalist, optional
List of BTSD thresholds. The default is [0.].
- coeflist, optional
List of positive mixture coefficients. Must be the same size as alpha. A None value assumes an equal weighted risk mixture. The vector of coefficients will be normalized to unit. The default is None.
- mktdatapandas.DataFrame, optional
Historic daily market data for portfolio components in the format returned by azapy.mktData function. The default is None.
- colnamestr, optional
Name of the price column from mktdata used in the weight’s calibration. The default is ‘adjusted’.
- freqstr, optional
Rate of return horizon. It could be ‘Q’ for a quarter or ‘M’ for a month. The default is ‘Q’.
- hlengthfloat, optional
History length in number of years used for calibration. A fractional number will be rounded to an integer number of months. The default is 3.25 years.
- namestr, optional
Portfolio name. The default is ‘BTAD’.
- rtypestr, optional
Optimization type. Possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
The default is ‘Sharpe’.
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with thier sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- detrendedBoolean, optional
If it set to True then the rates of return are detrended (mean=0). The default value is True.
- methodstr, optional
Linear programming numerical method. Could be: ‘ecos’, ‘highs-ds’, ‘highs-ipm’, ‘highs’, ‘interior-point’, ‘glpk’ and ‘cvxopt’. The default is ‘ecos’.
- Returns:
- The object.
- getDiversification(ww, rrate=None)
Returns the value of the diversification factor for a give portfolio.
- Parameters:
- wwlist, numpy.array or pandas.Series;
Portfolio weights. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >=0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (not necessarily in the same order).
- rratepandas.DataFrame, optional
Contains the portfolio components historical rates of return. If it is not None then it will overwrite the rates of return computed in the constructor from mktdata. The default is None.
- Returns:
- `float`The diversification value.
- getPositions(nshares=None, cash=0, ww=None, verbose=True)
Computes the rebalanced number of shares.
- Parameters:
- nsharespanda.Series, optional
Initial number of shares per portfolio component. A missing component entry will be considered 0. A None value assumes that all components entries are 0. The name of the components must be present in the mrkdata. The default is None.
- cashfloat, optional
Additional cash to be added to the capital. A negative entry assumes a reduction in the total capital available for rebalance. The total capital cannot be < 0. The default is 0.
- wwpanda.Series, optional
External overwrite portfolio weights. If it not set to None these weights will overwrite the calibration results. The default is None.
- verboseBoolean, optional
Is it set to True the function prints the closing prices date. The default is True.
- Returns:
- `pandas.DataFrame`the rolling information.
- Columns:
- ‘old_nsh’ :
initial number of shares per portfolio component and the additional cash. These are input values.
- ‘new_nsh’ :
the new number of shares per component plus the residual cash (due to the rounding to an integer number of shares). A negative entry means that the investor needs to add more cash to cover for the roundup shortfall. It has a small value.
- ‘diff_nsh’ :
number of shares (buy/sale) needed to rebalance the portfolio.
- ‘weights’ :
portfolio weights used for rebalancing. The cash entry is the new portfolio value (invested capital).
- ‘prices’ :
the share prices used for rebalances evaluations.
Note: Since the prices are closing prices, the rebalance can be computed after the market close and before the trading execution (next day). Additional cash slippage may occur due to share price differential between the previous day closing and execution time.
- getRisk(ww, rrate=None)
Returns the value of the dispersion (risk) measure for a give portfolio.
- Parameters:
- wwlist, numpy.array or pandas.Series
Portfolio weights. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >=0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series than the index should be compatible with the rrate.columns or mktdata symbols (not necessarily in the same order).
- rratepandas.DataFrame, optional
Contains the portfolio components historical rates of return. If it is not None, it will overwrite the rates of return computed in the constructor from mktdata. The default is None.
- Returns:
- `float`The dispersion (risk) measure value.
- getRiskComp()
Returns the risk of each portfolio component.
- Returns:
- `pandas.Series`risk per symbol.
- getWeights(rtype=None, mu=None, d=1, mu0=0.0, aversion=None, ww0=None, mktdata=None, **params)
Computes the optimal portfolio weights.
- Parameters:
- rtypestr, optional
Optimization type. If is not None it will overwrite the value set by the constructor. The default is None. Other possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- mktdatapandas.DataFrame, optional
The portfolio components historical, prices or rates of return, see ‘pclose’ definition below. If it is not None, it will overwrite the set of historical rates of return computed in the constructor from ‘mktdata’. The default is None.
- **paramsother optional parameters
Most common:
- verboseBoolean, optional
If it set to True, then it will print a message when the optimal portfolio degenerates to a single asset. The default is False.
- pcloseBoolean, optional
If it is absent then the mktdata is considered to contain rates of return, with columns the asset symbols and indexed by the observation dates,
True : assumes mktdata contains closing prices only, with columns the asset symbols and indexed by the observation dates,
False : assumes mktdata is in the usual format returned by azapy.mktData function.
- Returns:
- `pandas.Series`portfolio weights per symbol.
- set_method(method)
Sets computation method.
- Parameters:
- methodstr;
Must be a valid method name. It will overwrite the value set by the constructor.
- Returns:
- None
- set_mktdata(mktdata, colname=None, freq=None, hlength=None, pclose=False)
Sets historical market data. It will overwrite the choice made in the constructor.
- Parameters:
- mktdatapandas.DataFrame
Historic daily market data for portfolio components in the format returned by azapy.mktData function.
- colnamestr, optional
Name of the price column from mktdata used in the weight’s calibration. The default is ‘adjusted’.
- freqstr, optional
Rate of return horizon. It could be ‘Q’ for a quarter or ‘M’ for a month. The default is ‘Q’.
- hlengthfloat, optional
History length in number of years used for calibration. A fractional number will be rounded to an integer number of months. The default is 3.25.
- pcloseBoolean, optional
True : assumes mktdata contains closing prices only, with columns the asset symbols and indexed by the observation dates,
False : assumes mktdata is in the usual format returned by azapy.mktData function.
- Returns:
- None
- set_random_seed(seed=42)
Sets the seed for Dirichlet random generator used in viewFrontiers to select the random inefficient portfolios.
- Parameters:
- seedint, optional
The random generator seed, in case you want to set it to a weird value other than 42 :). The default is 42.
- Returns:
- None
- set_rrate(rrate)
Sets portfolio components historical rates of return. It will overwrite the value computed by the constructor from mktdata.
- Parameters:
- rratepandas.DataFrame
Portfolio components historical rates of return. The columns are: ‘date’, ‘symbol1’, ‘symbol2’, etc.
- Returns
- ——-
- `None`
- set_rtype(rtype=None, mu=None, d=1, mu0=0.0, aversion=None, ww0=None)
Sets the optimization type. It will overwrite the value set in the constructor.
- Parameters:
- rtypestr, optional
Optimization type. Possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
The default is ‘Sharpe’.
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- Returns:
- None
- viewFrontiers(minrisk=True, efficient=20, inefficient=20, sharpe=True, musharpe=0.0, maxdiverse=False, diverse_efficient=0, diverse_inefficient=0, invN=True, invNrisk=True, invNdiverse=False, invNdrr=False, component=True, randomport=20, addport=None, fig_type='RR_risk', **opt)
Computes the elements of the portfolio frontiers.
- Parameters:
- minriskBoolean, optional
If it is True then the minimum risk portfolio will be visible. The default is True.
- efficientint, optional
Number of points along the efficient risk frontier (equally spaced along the rate of return axis). The default is 20.
- inefficientint, optional
Number of points along the inefficient risk frontier (equally spaced along the rate of returns axis). The default is 20.
- sharpeBoolean, optional
If it is True then the maximum Sharpe portfolio will be visible. The default is True.
- musharpefloat, optional
Risk-free rate value used in the evaluation of generalized Sharpe ratio. The default is 0.
- maxdiverseBoolean, optional
If it is True then the maximum diversified portfolio will be visible. The default is True.
- diverse_efficientint, optional
Number of points along the efficient diversification frontier (equally spaced along the rate of return axis). The default is 20.
- diverse_inefficientint, optional
Number of points along the inefficient diversification frontier (equally spaced along the rate of return axis). The default is 20.
- invNBoolean, optional
If it is True, then the equal weighted portfolio and the optimal portfolio with the same risk value are added to the plot. The default is True.
- invNriskBoolean, optional
If it is True, then the efficient risk portfolio with same risk as equal weighted portfolio is added to the plot. The default is False.
- invNdiverseBoolean, optional
If it is True, then the efficient diversified portfolio with the same diversification factor as the equal weighted portfolio is added to the plot. The default is False.
- invNdrrBoolean, optional
If it is True, then the efficient diversified portfolio with the same expected rate of return as the equal weighted portfolio is added to the plot. The default value is False.
- componentBoolean, optional
If it is True, then the single component portfolios are added to the plot. The default is True.
- randomportint, optional
Number of portfolios with random weights (inefficient) to be added to the plot (for reference). The default is 20.
- addportdict or pandas.DataFrame, optional
The weights of additional portfolio to be added to the plot. If it is a dict then the keys are the labels, and the values are list of weights in the order of rrate.columns. If it is a pandas.DataFrame the index are the labels, and each row is a set of weights. The columns names should match the symbols names. The default is None.
- fig_typestr, optional
Graphical representation format.
‘RR_risk’ : expected rate of return vs risk
‘Sharpe_RR’ : sharpe vs expected rate of return
‘Diverse_RR’ : diversification vs expected rate of return
The default is ‘RR_risk’.
- **optoptional
Additional parameters:
- ‘title’str
The default is ‘Portfolio frontiers’.
- ‘xlabel’str
The default is
‘risk’ if fig_type=’RR_risk’,
‘rate of returns’ otherwise.
- ‘ylabel’str
The default is
‘rate of returns’ if fig_type=’RR_risk’
‘sharpe’ if fig_type=’Sharpe_RR’
‘diversification’ if fig_type=diverse_RR
- ‘tangent’Boolean
If set to True, then the tangent (to max sharpe point) is added. It has effect only if fig_type=’RR_risk’. The default is True.
- savetostr
File name to save the figure. The extension dictates the format: png, pdf, svg, etc. For more details see the mathplotlib documentation for savefig. The default is None.
- datadefaultdict
Numerical data to construct the plot. If it is not None, then it will take precedence and no other numerical evaluations will be performed. It is meant to produce different plot representations without reevaluations. The default is None.
- invN_labelstr
The label for equal weighted portfolio. The default is ‘1/N’.
- invNrisk_labelstr
The lable for efficient portfolio with same risk as equal weighted portfolio. The default is invNrisk.
- invNdiverse_labelstr
The label for diverse-efficient portfolio with the same diversificeation factor as equal weighted porfolio. The default is ‘invNdiv’.
- invNdrr_labelstr
The label of diverse-efficient portfolio with the same expected rate of return as equal weighted portolio. The defualt is ‘invNdrr’.
- maxdiverse_labelstr
The label of maximum diverified portfolio. The default is ‘MaxD’.
- minrisk_label‘str’
The label of minimum risk portfolio. The default is ‘MinR’.
- sharpe_labelstr
The label of maximum Sharpe portfolio. The default is ‘Sharpe’.
- Returns:
- `dict`Numerical data used to make the plots. It can be passed back
- to reconstruct the plots without reevaluations.
azapy.Analyzers.BTSDAnalyzer module¶
- class azapy.Analyzers.BTSDAnalyzer.BTSDAnalyzer(alpha=[0.0], coef=None, mktdata=None, colname='adjusted', freq='Q', hlength=3.25, name='BTSD', rtype='Sharpe', mu=None, d=1, mu0=0.0, aversion=None, ww0=None, detrended=False, method='ecos')
Bases:
BTADAnalyzer
Mixture BTSD (Below Threshold Standard Deviation) based optimal portfolio strategies.
- Attributes
status : int - the computation status (0 - success, any other value signifies an error)
ww : pandas.Series - the portfolio weights
RR : float - portfolio rate of return
risk : float - portfolio mBTSD risk
primary_risk_comp : list - portfolio mBTSD components
secondary_risk_comp : list - portfolio thresholds, alpha (input values)
sharpe : float - Omega ration if rtype is set to ‘Shapre’ or ‘Sharpe2’ otherwise None.
diverse : float - diversification factor if rtype is set to ‘Divers’ or ‘MaxDivers’ otherwise None.
name : str - portfolio name
- Note the following 2 important methods:
getWeights : Computes the optimal portfolio weights. During its computations the following class members are also set: risk, primery_risk_comp, secondary_risk_comp, sharpe, RR, divers.
getPositions : Provides practical information regarding the portfolio rebalancing delta positions and costs.
Methods
getDiversification
(ww[, rrate])Returns the value of the diversification factor for a give portfolio.
getPositions
([nshares, cash, ww, verbose])Computes the rebalanced number of shares.
getRisk
(ww[, rrate])Returns the value of the dispersion (risk) measure for a give portfolio.
Returns the risk of each portfolio component.
getWeights
([rtype, mu, d, mu0, aversion, ...])Computes the optimal portfolio weights.
set_method
(method)Sets computation method.
set_mktdata
(mktdata[, colname, freq, ...])Sets historical market data.
set_random_seed
([seed])Sets the seed for Dirichlet random generator used in viewFrontiers to select the random inefficient portfolios.
set_rrate
(rrate)Sets portfolio components historical rates of return.
set_rtype
([rtype, mu, d, mu0, aversion, ww0])Sets the optimization type.
viewFrontiers
([minrisk, efficient, ...])Computes the elements of the portfolio frontiers.
- __init__(alpha=[0.0], coef=None, mktdata=None, colname='adjusted', freq='Q', hlength=3.25, name='BTSD', rtype='Sharpe', mu=None, d=1, mu0=0.0, aversion=None, ww0=None, detrended=False, method='ecos')
Constructor
- Parameters:
- alphalist, optional
List of BTSD thresholds. The default is [0.].
- coeflist, optional
List of positive mixture coefficients. Must be the same size as alpha. A None value assumes an equal weighted risk mixture. The vector of coefficients will be normalized to unit. The default is None.
- mktdatapandas.DataFrame, optional
Historic daily market data for portfolio components in the format returned by azapy.mktData function. The default is None.
- colnamestr, optional
Name of the price column from mktdata used in the weight’s calibration. The default is ‘adjusted’.
- freqstr, optional
Rate of return horizon. It could be ‘Q’ for a quarter or ‘M’ for a month. The default is ‘Q’.
- hlengthfloat, optional
History length in number of years used for calibration. A fractional number will be rounded to an integer number of months. The default is 3.25 years.
- namestr, optional
Portfolio name. The default is ‘BTSD’.
- rtypestr, optional
Optimization type. Possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
The default is ‘Sharpe’.
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with thier sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- detrendedBoolean, optional
If it set to True then the rates of return are detrended (mean=0). The default value is True.
- methodstr, optional
SOCP numerical method. Could be: ‘ecos’, or ‘cvxopt’. The defualt is ‘ecos’.
- Returns:
- The object.
- getDiversification(ww, rrate=None)
Returns the value of the diversification factor for a give portfolio.
- Parameters:
- wwlist, numpy.array or pandas.Series;
Portfolio weights. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >=0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (not necessarily in the same order).
- rratepandas.DataFrame, optional
Contains the portfolio components historical rates of return. If it is not None then it will overwrite the rates of return computed in the constructor from mktdata. The default is None.
- Returns:
- `float`The diversification value.
- getPositions(nshares=None, cash=0, ww=None, verbose=True)
Computes the rebalanced number of shares.
- Parameters:
- nsharespanda.Series, optional
Initial number of shares per portfolio component. A missing component entry will be considered 0. A None value assumes that all components entries are 0. The name of the components must be present in the mrkdata. The default is None.
- cashfloat, optional
Additional cash to be added to the capital. A negative entry assumes a reduction in the total capital available for rebalance. The total capital cannot be < 0. The default is 0.
- wwpanda.Series, optional
External overwrite portfolio weights. If it not set to None these weights will overwrite the calibration results. The default is None.
- verboseBoolean, optional
Is it set to True the function prints the closing prices date. The default is True.
- Returns:
- `pandas.DataFrame`the rolling information.
- Columns:
- ‘old_nsh’ :
initial number of shares per portfolio component and the additional cash. These are input values.
- ‘new_nsh’ :
the new number of shares per component plus the residual cash (due to the rounding to an integer number of shares). A negative entry means that the investor needs to add more cash to cover for the roundup shortfall. It has a small value.
- ‘diff_nsh’ :
number of shares (buy/sale) needed to rebalance the portfolio.
- ‘weights’ :
portfolio weights used for rebalancing. The cash entry is the new portfolio value (invested capital).
- ‘prices’ :
the share prices used for rebalances evaluations.
Note: Since the prices are closing prices, the rebalance can be computed after the market close and before the trading execution (next day). Additional cash slippage may occur due to share price differential between the previous day closing and execution time.
- getRisk(ww, rrate=None)
Returns the value of the dispersion (risk) measure for a give portfolio.
- Parameters:
- wwlist, numpy.array or pandas.Series
Portfolio weights. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >=0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series than the index should be compatible with the rrate.columns or mktdata symbols (not necessarily in the same order).
- rratepandas.DataFrame, optional
Contains the portfolio components historical rates of return. If it is not None, it will overwrite the rates of return computed in the constructor from mktdata. The default is None.
- Returns:
- `float`The dispersion (risk) measure value.
- getRiskComp()
Returns the risk of each portfolio component.
- Returns:
- `pandas.Series`risk per symbol.
- getWeights(rtype=None, mu=None, d=1, mu0=0.0, aversion=None, ww0=None, mktdata=None, **params)
Computes the optimal portfolio weights.
- Parameters:
- rtypestr, optional
Optimization type. If is not None it will overwrite the value set by the constructor. The default is None. Other possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- mktdatapandas.DataFrame, optional
The portfolio components historical, prices or rates of return, see ‘pclose’ definition below. If it is not None, it will overwrite the set of historical rates of return computed in the constructor from ‘mktdata’. The default is None.
- **paramsother optional parameters
Most common:
- verboseBoolean, optional
If it set to True, then it will print a message when the optimal portfolio degenerates to a single asset. The default is False.
- pcloseBoolean, optional
If it is absent then the mktdata is considered to contain rates of return, with columns the asset symbols and indexed by the observation dates,
True : assumes mktdata contains closing prices only, with columns the asset symbols and indexed by the observation dates,
False : assumes mktdata is in the usual format returned by azapy.mktData function.
- Returns:
- `pandas.Series`portfolio weights per symbol.
- set_method(method)
Sets computation method.
- Parameters:
- methodstr;
Must be a valid method name. It will overwrite the value set by the constructor.
- Returns:
- None
- set_mktdata(mktdata, colname=None, freq=None, hlength=None, pclose=False)
Sets historical market data. It will overwrite the choice made in the constructor.
- Parameters:
- mktdatapandas.DataFrame
Historic daily market data for portfolio components in the format returned by azapy.mktData function.
- colnamestr, optional
Name of the price column from mktdata used in the weight’s calibration. The default is ‘adjusted’.
- freqstr, optional
Rate of return horizon. It could be ‘Q’ for a quarter or ‘M’ for a month. The default is ‘Q’.
- hlengthfloat, optional
History length in number of years used for calibration. A fractional number will be rounded to an integer number of months. The default is 3.25.
- pcloseBoolean, optional
True : assumes mktdata contains closing prices only, with columns the asset symbols and indexed by the observation dates,
False : assumes mktdata is in the usual format returned by azapy.mktData function.
- Returns:
- None
- set_random_seed(seed=42)
Sets the seed for Dirichlet random generator used in viewFrontiers to select the random inefficient portfolios.
- Parameters:
- seedint, optional
The random generator seed, in case you want to set it to a weird value other than 42 :). The default is 42.
- Returns:
- None
- set_rrate(rrate)
Sets portfolio components historical rates of return. It will overwrite the value computed by the constructor from mktdata.
- Parameters:
- rratepandas.DataFrame
Portfolio components historical rates of return. The columns are: ‘date’, ‘symbol1’, ‘symbol2’, etc.
- Returns
- ——-
- `None`
- set_rtype(rtype=None, mu=None, d=1, mu0=0.0, aversion=None, ww0=None)
Sets the optimization type. It will overwrite the value set in the constructor.
- Parameters:
- rtypestr, optional
Optimization type. Possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
The default is ‘Sharpe’.
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- Returns:
- None
- viewFrontiers(minrisk=True, efficient=20, inefficient=20, sharpe=True, musharpe=0.0, maxdiverse=False, diverse_efficient=0, diverse_inefficient=0, invN=True, invNrisk=True, invNdiverse=False, invNdrr=False, component=True, randomport=20, addport=None, fig_type='RR_risk', **opt)
Computes the elements of the portfolio frontiers.
- Parameters:
- minriskBoolean, optional
If it is True then the minimum risk portfolio will be visible. The default is True.
- efficientint, optional
Number of points along the efficient risk frontier (equally spaced along the rate of return axis). The default is 20.
- inefficientint, optional
Number of points along the inefficient risk frontier (equally spaced along the rate of returns axis). The default is 20.
- sharpeBoolean, optional
If it is True then the maximum Sharpe portfolio will be visible. The default is True.
- musharpefloat, optional
Risk-free rate value used in the evaluation of generalized Sharpe ratio. The default is 0.
- maxdiverseBoolean, optional
If it is True then the maximum diversified portfolio will be visible. The default is True.
- diverse_efficientint, optional
Number of points along the efficient diversification frontier (equally spaced along the rate of return axis). The default is 20.
- diverse_inefficientint, optional
Number of points along the inefficient diversification frontier (equally spaced along the rate of return axis). The default is 20.
- invNBoolean, optional
If it is True, then the equal weighted portfolio and the optimal portfolio with the same risk value are added to the plot. The default is True.
- invNriskBoolean, optional
If it is True, then the efficient risk portfolio with same risk as equal weighted portfolio is added to the plot. The default is False.
- invNdiverseBoolean, optional
If it is True, then the efficient diversified portfolio with the same diversification factor as the equal weighted portfolio is added to the plot. The default is False.
- invNdrrBoolean, optional
If it is True, then the efficient diversified portfolio with the same expected rate of return as the equal weighted portfolio is added to the plot. The default value is False.
- componentBoolean, optional
If it is True, then the single component portfolios are added to the plot. The default is True.
- randomportint, optional
Number of portfolios with random weights (inefficient) to be added to the plot (for reference). The default is 20.
- addportdict or pandas.DataFrame, optional
The weights of additional portfolio to be added to the plot. If it is a dict then the keys are the labels, and the values are list of weights in the order of rrate.columns. If it is a pandas.DataFrame the index are the labels, and each row is a set of weights. The columns names should match the symbols names. The default is None.
- fig_typestr, optional
Graphical representation format.
‘RR_risk’ : expected rate of return vs risk
‘Sharpe_RR’ : sharpe vs expected rate of return
‘Diverse_RR’ : diversification vs expected rate of return
The default is ‘RR_risk’.
- **optoptional
Additional parameters:
- ‘title’str
The default is ‘Portfolio frontiers’.
- ‘xlabel’str
The default is
‘risk’ if fig_type=’RR_risk’,
‘rate of returns’ otherwise.
- ‘ylabel’str
The default is
‘rate of returns’ if fig_type=’RR_risk’
‘sharpe’ if fig_type=’Sharpe_RR’
‘diversification’ if fig_type=diverse_RR
- ‘tangent’Boolean
If set to True, then the tangent (to max sharpe point) is added. It has effect only if fig_type=’RR_risk’. The default is True.
- savetostr
File name to save the figure. The extension dictates the format: png, pdf, svg, etc. For more details see the mathplotlib documentation for savefig. The default is None.
- datadefaultdict
Numerical data to construct the plot. If it is not None, then it will take precedence and no other numerical evaluations will be performed. It is meant to produce different plot representations without reevaluations. The default is None.
- invN_labelstr
The label for equal weighted portfolio. The default is ‘1/N’.
- invNrisk_labelstr
The lable for efficient portfolio with same risk as equal weighted portfolio. The default is invNrisk.
- invNdiverse_labelstr
The label for diverse-efficient portfolio with the same diversificeation factor as equal weighted porfolio. The default is ‘invNdiv’.
- invNdrr_labelstr
The label of diverse-efficient portfolio with the same expected rate of return as equal weighted portolio. The defualt is ‘invNdrr’.
- maxdiverse_labelstr
The label of maximum diverified portfolio. The default is ‘MaxD’.
- minrisk_label‘str’
The label of minimum risk portfolio. The default is ‘MinR’.
- sharpe_labelstr
The label of maximum Sharpe portfolio. The default is ‘Sharpe’.
- Returns:
- `dict`Numerical data used to make the plots. It can be passed back
- to reconstruct the plots without reevaluations.
azapy.Analyzers.CVaRAnalyzer module¶
- class azapy.Analyzers.CVaRAnalyzer.CVaRAnalyzer(alpha=[0.975], coef=None, mktdata=None, colname='adjusted', freq='Q', hlength=3.25, name='CVaR', rtype='Sharpe', mu=None, d=1, mu0=0.0, aversion=None, ww0=None, method='ecos')
Bases:
_RiskAnalyzer
Mixture CVaR (Conditional Value at Risk) based optimal portfolio strategies.
- Attributes
status : int - the computation status (0 - success, any other value signifies an error)
ww : pandas.Series - the portfolio weights
RR : float - portfolio rate of return
risk : float - portfolio mCVaR risk
primary_risk_comp : list - CVaR components of portfolio mCVaR
secondary_risk_comp : list - VaR values associated with CVaR components
sharpe : float - mCVaR-Sharpe ration if rtype is set to ‘Shapre’ or ‘Sharpe2’ otherwise None.
diverse : float - diversification factor if rtype is set to ‘Divers’ or ‘MaxDivers’ otherwise None.
name : str - portfolio name
- Note the following 2 important methods:
getWeights : Computes the optimal portfolio weights. During its computations the following class members are also set: risk, primery_risk_comp, secondary_risk_comp, sharpe, RR, divers.
getPositions : Provides practical information regarding the portfolio rebalancing delta positions and costs.
Methods
getDiversification
(ww[, rrate])Returns the value of the diversification factor for a give portfolio.
getPositions
([nshares, cash, ww, verbose])Computes the rebalanced number of shares.
getRisk
(ww[, rrate])Returns the value of the dispersion (risk) measure for a give portfolio.
Returns the risk of each portfolio component.
getWeights
([rtype, mu, d, mu0, aversion, ...])Computes the optimal portfolio weights.
set_method
(method)Sets computation method.
set_mktdata
(mktdata[, colname, freq, ...])Sets historical market data.
set_random_seed
([seed])Sets the seed for Dirichlet random generator used in viewFrontiers to select the random inefficient portfolios.
set_rrate
(rrate)Sets portfolio components historical rates of return.
set_rtype
([rtype, mu, d, mu0, aversion, ww0])Sets the optimization type.
viewFrontiers
([minrisk, efficient, ...])Computes the elements of the portfolio frontiers.
- __init__(alpha=[0.975], coef=None, mktdata=None, colname='adjusted', freq='Q', hlength=3.25, name='CVaR', rtype='Sharpe', mu=None, d=1, mu0=0.0, aversion=None, ww0=None, method='ecos')
Constructor
- Parameters:
- alphalist, optional
List of distinct confidence levels. The default is [0.975].
- coeflist, optional
List of positive mixture coefficients. Must be the same size as alpha. A None value assumes an equal weighted risk mixture. The vector of coefficients will be normalized to unit. The default is None.
- mktdatapandas.DataFrame, optional
Historic daily market data for portfolio components in the format returned by azapy.mktData function. The default is None.
- colnamestr, optional
Name of the price column from mktdata used in the weight’s calibration. The default is ‘adjusted’.
- freqstr, optional
Rate of return horizon. It could be ‘Q’ for a quarter or ‘M’ for a month. The default is ‘Q’.
- hlengthfloat, optional
History length in number of years used for calibration. A fractional number will be rounded to an integer number of months. The default is 3.25 years.
- namestr, optional
Portfolio name. The default is ‘CVaR’.
- rtypestr, optional
Optimization type. Possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
The default is ‘Sharpe’.
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- methodstr, optional
Linear programming numerical method. Could be: ‘ecos’, ‘highs-ds’, ‘highs-ipm’, ‘highs’, ‘interior-point’, ‘glpk’ and ‘cvxopt’. The default is ‘ecos’.
- Returns:
- The object.
- getDiversification(ww, rrate=None)
Returns the value of the diversification factor for a give portfolio.
- Parameters:
- wwlist, numpy.array or pandas.Series;
Portfolio weights. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >=0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (not necessarily in the same order).
- rratepandas.DataFrame, optional
Contains the portfolio components historical rates of return. If it is not None then it will overwrite the rates of return computed in the constructor from mktdata. The default is None.
- Returns:
- `float`The diversification value.
- getPositions(nshares=None, cash=0, ww=None, verbose=True)
Computes the rebalanced number of shares.
- Parameters:
- nsharespanda.Series, optional
Initial number of shares per portfolio component. A missing component entry will be considered 0. A None value assumes that all components entries are 0. The name of the components must be present in the mrkdata. The default is None.
- cashfloat, optional
Additional cash to be added to the capital. A negative entry assumes a reduction in the total capital available for rebalance. The total capital cannot be < 0. The default is 0.
- wwpanda.Series, optional
External overwrite portfolio weights. If it not set to None these weights will overwrite the calibration results. The default is None.
- verboseBoolean, optional
Is it set to True the function prints the closing prices date. The default is True.
- Returns:
- `pandas.DataFrame`the rolling information.
- Columns:
- ‘old_nsh’ :
initial number of shares per portfolio component and the additional cash. These are input values.
- ‘new_nsh’ :
the new number of shares per component plus the residual cash (due to the rounding to an integer number of shares). A negative entry means that the investor needs to add more cash to cover for the roundup shortfall. It has a small value.
- ‘diff_nsh’ :
number of shares (buy/sale) needed to rebalance the portfolio.
- ‘weights’ :
portfolio weights used for rebalancing. The cash entry is the new portfolio value (invested capital).
- ‘prices’ :
the share prices used for rebalances evaluations.
Note: Since the prices are closing prices, the rebalance can be computed after the market close and before the trading execution (next day). Additional cash slippage may occur due to share price differential between the previous day closing and execution time.
- getRisk(ww, rrate=None)
Returns the value of the dispersion (risk) measure for a give portfolio.
- Parameters:
- wwlist, numpy.array or pandas.Series
Portfolio weights. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >=0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series than the index should be compatible with the rrate.columns or mktdata symbols (not necessarily in the same order).
- rratepandas.DataFrame, optional
Contains the portfolio components historical rates of return. If it is not None, it will overwrite the rates of return computed in the constructor from mktdata. The default is None.
- Returns:
- `float`The dispersion (risk) measure value.
- getRiskComp()
Returns the risk of each portfolio component.
- Returns:
- `pandas.Series`risk per symbol.
- getWeights(rtype=None, mu=None, d=1, mu0=0.0, aversion=None, ww0=None, mktdata=None, **params)
Computes the optimal portfolio weights.
- Parameters:
- rtypestr, optional
Optimization type. If is not None it will overwrite the value set by the constructor. The default is None. Other possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- mktdatapandas.DataFrame, optional
The portfolio components historical, prices or rates of return, see ‘pclose’ definition below. If it is not None, it will overwrite the set of historical rates of return computed in the constructor from ‘mktdata’. The default is None.
- **paramsother optional parameters
Most common:
- verboseBoolean, optional
If it set to True, then it will print a message when the optimal portfolio degenerates to a single asset. The default is False.
- pcloseBoolean, optional
If it is absent then the mktdata is considered to contain rates of return, with columns the asset symbols and indexed by the observation dates,
True : assumes mktdata contains closing prices only, with columns the asset symbols and indexed by the observation dates,
False : assumes mktdata is in the usual format returned by azapy.mktData function.
- Returns:
- `pandas.Series`portfolio weights per symbol.
- set_method(method)
Sets computation method.
- Parameters:
- methodstr;
Must be a valid method name. It will overwrite the value set by the constructor.
- Returns:
- None
- set_mktdata(mktdata, colname=None, freq=None, hlength=None, pclose=False)
Sets historical market data. It will overwrite the choice made in the constructor.
- Parameters:
- mktdatapandas.DataFrame
Historic daily market data for portfolio components in the format returned by azapy.mktData function.
- colnamestr, optional
Name of the price column from mktdata used in the weight’s calibration. The default is ‘adjusted’.
- freqstr, optional
Rate of return horizon. It could be ‘Q’ for a quarter or ‘M’ for a month. The default is ‘Q’.
- hlengthfloat, optional
History length in number of years used for calibration. A fractional number will be rounded to an integer number of months. The default is 3.25.
- pcloseBoolean, optional
True : assumes mktdata contains closing prices only, with columns the asset symbols and indexed by the observation dates,
False : assumes mktdata is in the usual format returned by azapy.mktData function.
- Returns:
- None
- set_random_seed(seed=42)
Sets the seed for Dirichlet random generator used in viewFrontiers to select the random inefficient portfolios.
- Parameters:
- seedint, optional
The random generator seed, in case you want to set it to a weird value other than 42 :). The default is 42.
- Returns:
- None
- set_rrate(rrate)
Sets portfolio components historical rates of return. It will overwrite the value computed by the constructor from mktdata.
- Parameters:
- rratepandas.DataFrame
Portfolio components historical rates of return. The columns are asset symbols and indexed by observation dates.
- Returns:
- None
- set_rtype(rtype=None, mu=None, d=1, mu0=0.0, aversion=None, ww0=None)
Sets the optimization type. It will overwrite the value set in the constructor.
- Parameters:
- rtypestr, optional
Optimization type. Possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
The default is ‘Sharpe’.
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- Returns:
- None
- viewFrontiers(minrisk=True, efficient=20, inefficient=20, sharpe=True, musharpe=0.0, maxdiverse=False, diverse_efficient=0, diverse_inefficient=0, invN=True, invNrisk=True, invNdiverse=False, invNdrr=False, component=True, randomport=20, addport=None, fig_type='RR_risk', **opt)
Computes the elements of the portfolio frontiers.
- Parameters:
- minriskBoolean, optional
If it is True then the minimum risk portfolio will be visible. The default is True.
- efficientint, optional
Number of points along the efficient risk frontier (equally spaced along the rate of return axis). The default is 20.
- inefficientint, optional
Number of points along the inefficient risk frontier (equally spaced along the rate of returns axis). The default is 20.
- sharpeBoolean, optional
If it is True then the maximum Sharpe portfolio will be visible. The default is True.
- musharpefloat, optional
Risk-free rate value used in the evaluation of generalized Sharpe ratio. The default is 0.
- maxdiverseBoolean, optional
If it is True then the maximum diversified portfolio will be visible. The default is True.
- diverse_efficientint, optional
Number of points along the efficient diversification frontier (equally spaced along the rate of return axis). The default is 20.
- diverse_inefficientint, optional
Number of points along the inefficient diversification frontier (equally spaced along the rate of return axis). The default is 20.
- invNBoolean, optional
If it is True, then the equal weighted portfolio and the optimal portfolio with the same risk value are added to the plot. The default is True.
- invNriskBoolean, optional
If it is True, then the efficient risk portfolio with same risk as equal weighted portfolio is added to the plot. The default is False.
- invNdiverseBoolean, optional
If it is True, then the efficient diversified portfolio with the same diversification factor as the equal weighted portfolio is added to the plot. The default is False.
- invNdrrBoolean, optional
If it is True, then the efficient diversified portfolio with the same expected rate of return as the equal weighted portfolio is added to the plot. The default value is False.
- componentBoolean, optional
If it is True, then the single component portfolios are added to the plot. The default is True.
- randomportint, optional
Number of portfolios with random weights (inefficient) to be added to the plot (for reference). The default is 20.
- addportdict or pandas.DataFrame, optional
The weights of additional portfolio to be added to the plot. If it is a dict then the keys are the labels, and the values are list of weights in the order of rrate.columns. If it is a pandas.DataFrame the index are the labels, and each row is a set of weights. The columns names should match the symbols names. The default is None.
- fig_typestr, optional
Graphical representation format.
‘RR_risk’ : expected rate of return vs risk
‘Sharpe_RR’ : sharpe vs expected rate of return
‘Diverse_RR’ : diversification vs expected rate of return
The default is ‘RR_risk’.
- **optoptional
Additional parameters:
- ‘title’str
The default is ‘Portfolio frontiers’.
- ‘xlabel’str
The default is
‘risk’ if fig_type=’RR_risk’,
‘rate of returns’ otherwise.
- ‘ylabel’str
The default is
‘rate of returns’ if fig_type=’RR_risk’
‘sharpe’ if fig_type=’Sharpe_RR’
‘diversification’ if fig_type=diverse_RR
- ‘tangent’Boolean
If set to True, then the tangent (to max sharpe point) is added. It has effect only if fig_type=’RR_risk’. The default is True.
- savetostr
File name to save the figure. The extension dictates the format: png, pdf, svg, etc. For more details see the mathplotlib documentation for savefig. The default is None.
- datadefaultdict
Numerical data to construct the plot. If it is not None, then it will take precedence and no other numerical evaluations will be performed. It is meant to produce different plot representations without reevaluations. The default is None.
- invN_labelstr
The label for equal weighted portfolio. The default is ‘1/N’.
- invNrisk_labelstr
The lable for efficient portfolio with same risk as equal weighted portfolio. The default is invNrisk.
- invNdiverse_labelstr
The label for diverse-efficient portfolio with the same diversificeation factor as equal weighted porfolio. The default is ‘invNdiv’.
- invNdrr_labelstr
The label of diverse-efficient portfolio with the same expected rate of return as equal weighted portolio. The defualt is ‘invNdrr’.
- maxdiverse_labelstr
The label of maximum diverified portfolio. The default is ‘MaxD’.
- minrisk_label‘str’
The label of minimum risk portfolio. The default is ‘MinR’.
- sharpe_labelstr
The label of maximum Sharpe portfolio. The default is ‘Sharpe’.
- Returns:
- `dict`Numerical data used to make the plots. It can be passed back
- to reconstruct the plots without reevaluations.
azapy.Analyzers.EVaRAnalyzer module¶
- class azapy.Analyzers.EVaRAnalyzer.EVaRAnalyzer(alpha=[0.65], coef=None, mktdata=None, colname='adjusted', freq='Q', hlength=3.25, name='EVaR', rtype='Sharpe', mu=None, d=1, mu0=0.0, aversion=None, ww0=None, method='ncp')
Bases:
_RiskAnalyzer
Mixture EVaR (Entropic Value at Risk) based optimal portfolio strategies.
- Attributes
status : int - the computation status (0 - success, any other value signifies an error)
ww : pandas.Series - the portfolio weights
RR : float - portfolio rate of return
risk : float - portfolio mEVaR risk
primary_risk_comp : list - EVaR components of portfolio mEVaR
secondary_risk_comp : list - effective confidence values associated with EVaR components.
sharpe : float - mEVaR-Sharpe ration if rtype is set to ‘Shapre’ or ‘Sharpe2’ otherwise None.
diverse : float - diversification factor if rtype is set to ‘Divers’ or ‘MaxDivers’ otherwise None.
name : str - portfolio name
- Note the following 2 important methods:
getWeights : Computes the optimal portfolio weights. During its computations the following class members are also set: risk, primery_risk_comp, secondary_risk_comp, sharpe, RR, divers.
getPositions : Provides practical information regarding the portfolio rebalancing delta positions and costs.
Methods
getDiversification
(ww[, rrate])Returns the value of the diversification factor for a give portfolio.
getPositions
([nshares, cash, ww, verbose])Computes the rebalanced number of shares.
getRisk
(ww[, rrate])Returns the value of the dispersion (risk) measure for a give portfolio.
Returns the risk of each portfolio component.
getWeights
([rtype, mu, d, mu0, aversion, ...])Computes the optimal portfolio weights.
set_method
(method)Sets computation method.
set_mktdata
(mktdata[, colname, freq, ...])Sets historical market data.
set_random_seed
([seed])Sets the seed for Dirichlet random generator used in viewFrontiers to select the random inefficient portfolios.
set_rrate
(rrate)Sets portfolio components historical rates of return.
set_rtype
([rtype, mu, d, mu0, aversion, ww0])Sets the optimization type.
viewFrontiers
([minrisk, efficient, ...])Computes the elements of the portfolio frontiers.
- __init__(alpha=[0.65], coef=None, mktdata=None, colname='adjusted', freq='Q', hlength=3.25, name='EVaR', rtype='Sharpe', mu=None, d=1, mu0=0.0, aversion=None, ww0=None, method='ncp')
Constructor
- Parameters:
- alphalist, optional
List of distinct confidence levels. The default is [0.65].
- coeflist, optional
List of positive mixture coefficients. Must be the same size as alpha. A None value assumes an equal weighted risk mixture. The vector of coefficients will be normalized to unit. The default is None.
- mktdatapandas.DataFrame, optional
Historic daily market data for portfolio components in the format returned by azapy.mktData function. The default is None.
- colnamestr, optional
Name of the price column from mktdata used in the weight’s calibration. The default is ‘adjusted’.
- freqstr, optional
Rate of return horizon. It could be ‘Q’ for a quarter or ‘M’ for a month. The default is ‘Q’.
- hlengthfloat, optional
History length in number of years used for calibration. A fractional number will be rounded to an integer number of months. The default is 3.25 years.
- namestr, optional
Portfolio name. The default is ‘EVaR’.
- rtypestr, optional
Optimization type. Possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
The default is ‘Sharpe’.
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- methodstr, optional
- Numerical optimization method:
‘ncp’ : nonlinear convex programming (using cvxopt).
‘ncp2’ : nonlinear convex programming (using cvxopt) alternative to ‘ncp’.
‘excp’ : exponential cone programming (using ecos).
The default is ‘ncp’.
- Returns:
- The object.
- getDiversification(ww, rrate=None)
Returns the value of the diversification factor for a give portfolio.
- Parameters:
- wwlist, numpy.array or pandas.Series;
Portfolio weights. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >=0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (not necessarily in the same order).
- rratepandas.DataFrame, optional
Contains the portfolio components historical rates of return. If it is not None then it will overwrite the rates of return computed in the constructor from mktdata. The default is None.
- Returns:
- `float`The diversification value.
- getPositions(nshares=None, cash=0, ww=None, verbose=True)
Computes the rebalanced number of shares.
- Parameters:
- nsharespanda.Series, optional
Initial number of shares per portfolio component. A missing component entry will be considered 0. A None value assumes that all components entries are 0. The name of the components must be present in the mrkdata. The default is None.
- cashfloat, optional
Additional cash to be added to the capital. A negative entry assumes a reduction in the total capital available for rebalance. The total capital cannot be < 0. The default is 0.
- wwpanda.Series, optional
External overwrite portfolio weights. If it not set to None these weights will overwrite the calibration results. The default is None.
- verboseBoolean, optional
Is it set to True the function prints the closing prices date. The default is True.
- Returns:
- `pandas.DataFrame`the rolling information.
- Columns:
- ‘old_nsh’ :
initial number of shares per portfolio component and the additional cash. These are input values.
- ‘new_nsh’ :
the new number of shares per component plus the residual cash (due to the rounding to an integer number of shares). A negative entry means that the investor needs to add more cash to cover for the roundup shortfall. It has a small value.
- ‘diff_nsh’ :
number of shares (buy/sale) needed to rebalance the portfolio.
- ‘weights’ :
portfolio weights used for rebalancing. The cash entry is the new portfolio value (invested capital).
- ‘prices’ :
the share prices used for rebalances evaluations.
Note: Since the prices are closing prices, the rebalance can be computed after the market close and before the trading execution (next day). Additional cash slippage may occur due to share price differential between the previous day closing and execution time.
- getRisk(ww, rrate=None)
Returns the value of the dispersion (risk) measure for a give portfolio.
- Parameters:
- wwlist, numpy.array or pandas.Series
Portfolio weights. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >=0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series than the index should be compatible with the rrate.columns or mktdata symbols (not necessarily in the same order).
- rratepandas.DataFrame, optional
Contains the portfolio components historical rates of return. If it is not None, it will overwrite the rates of return computed in the constructor from mktdata. The default is None.
- Returns:
- `float`The dispersion (risk) measure value.
- getRiskComp()
Returns the risk of each portfolio component.
- Returns:
- `pandas.Series`risk per symbol.
- getWeights(rtype=None, mu=None, d=1, mu0=0.0, aversion=None, ww0=None, mktdata=None, **params)
Computes the optimal portfolio weights.
- Parameters:
- rtypestr, optional
Optimization type. If is not None it will overwrite the value set by the constructor. The default is None. Other possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- mktdatapandas.DataFrame, optional
The portfolio components historical, prices or rates of return, see ‘pclose’ definition below. If it is not None, it will overwrite the set of historical rates of return computed in the constructor from ‘mktdata’. The default is None.
- **paramsother optional parameters
Most common:
- verboseBoolean, optional
If it set to True, then it will print a message when the optimal portfolio degenerates to a single asset. The default is False.
- pcloseBoolean, optional
If it is absent then the mktdata is considered to contain rates of return, with columns the asset symbols and indexed by the observation dates,
True : assumes mktdata contains closing prices only, with columns the asset symbols and indexed by the observation dates,
False : assumes mktdata is in the usual format returned by azapy.mktData function.
- Returns:
- `pandas.Series`portfolio weights per symbol.
- set_method(method)
Sets computation method.
- Parameters:
- methodstr;
Must be a valid method name. It will overwrite the value set by the constructor.
- Returns:
- None
- set_mktdata(mktdata, colname=None, freq=None, hlength=None, pclose=False)
Sets historical market data. It will overwrite the choice made in the constructor.
- Parameters:
- mktdatapandas.DataFrame
Historic daily market data for portfolio components in the format returned by azapy.mktData function.
- colnamestr, optional
Name of the price column from mktdata used in the weight’s calibration. The default is ‘adjusted’.
- freqstr, optional
Rate of return horizon. It could be ‘Q’ for a quarter or ‘M’ for a month. The default is ‘Q’.
- hlengthfloat, optional
History length in number of years used for calibration. A fractional number will be rounded to an integer number of months. The default is 3.25.
- pcloseBoolean, optional
True : assumes mktdata contains closing prices only, with columns the asset symbols and indexed by the observation dates,
False : assumes mktdata is in the usual format returned by azapy.mktData function.
- Returns:
- None
- set_random_seed(seed=42)
Sets the seed for Dirichlet random generator used in viewFrontiers to select the random inefficient portfolios.
- Parameters:
- seedint, optional
The random generator seed, in case you want to set it to a weird value other than 42 :). The default is 42.
- Returns:
- None
- set_rrate(rrate)
Sets portfolio components historical rates of return. It will overwrite the value computed by the constructor from mktdata.
- Parameters:
- rratepandas.DataFrame
Portfolio components historical rates of return. The columns are asset symbols and indexed by observation dates.
- Returns:
- None
- set_rtype(rtype=None, mu=None, d=1, mu0=0.0, aversion=None, ww0=None)
Sets the optimization type. It will overwrite the value set in the constructor.
- Parameters:
- rtypestr, optional
Optimization type. Possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
The default is ‘Sharpe’.
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- Returns:
- None
- viewFrontiers(minrisk=True, efficient=20, inefficient=20, sharpe=True, musharpe=0.0, maxdiverse=False, diverse_efficient=0, diverse_inefficient=0, invN=True, invNrisk=True, invNdiverse=False, invNdrr=False, component=True, randomport=20, addport=None, fig_type='RR_risk', **opt)
Computes the elements of the portfolio frontiers.
- Parameters:
- minriskBoolean, optional
If it is True then the minimum risk portfolio will be visible. The default is True.
- efficientint, optional
Number of points along the efficient risk frontier (equally spaced along the rate of return axis). The default is 20.
- inefficientint, optional
Number of points along the inefficient risk frontier (equally spaced along the rate of returns axis). The default is 20.
- sharpeBoolean, optional
If it is True then the maximum Sharpe portfolio will be visible. The default is True.
- musharpefloat, optional
Risk-free rate value used in the evaluation of generalized Sharpe ratio. The default is 0.
- maxdiverseBoolean, optional
If it is True then the maximum diversified portfolio will be visible. The default is True.
- diverse_efficientint, optional
Number of points along the efficient diversification frontier (equally spaced along the rate of return axis). The default is 20.
- diverse_inefficientint, optional
Number of points along the inefficient diversification frontier (equally spaced along the rate of return axis). The default is 20.
- invNBoolean, optional
If it is True, then the equal weighted portfolio and the optimal portfolio with the same risk value are added to the plot. The default is True.
- invNriskBoolean, optional
If it is True, then the efficient risk portfolio with same risk as equal weighted portfolio is added to the plot. The default is False.
- invNdiverseBoolean, optional
If it is True, then the efficient diversified portfolio with the same diversification factor as the equal weighted portfolio is added to the plot. The default is False.
- invNdrrBoolean, optional
If it is True, then the efficient diversified portfolio with the same expected rate of return as the equal weighted portfolio is added to the plot. The default value is False.
- componentBoolean, optional
If it is True, then the single component portfolios are added to the plot. The default is True.
- randomportint, optional
Number of portfolios with random weights (inefficient) to be added to the plot (for reference). The default is 20.
- addportdict or pandas.DataFrame, optional
The weights of additional portfolio to be added to the plot. If it is a dict then the keys are the labels, and the values are list of weights in the order of rrate.columns. If it is a pandas.DataFrame the index are the labels, and each row is a set of weights. The columns names should match the symbols names. The default is None.
- fig_typestr, optional
Graphical representation format.
‘RR_risk’ : expected rate of return vs risk
‘Sharpe_RR’ : sharpe vs expected rate of return
‘Diverse_RR’ : diversification vs expected rate of return
The default is ‘RR_risk’.
- **optoptional
Additional parameters:
- ‘title’str
The default is ‘Portfolio frontiers’.
- ‘xlabel’str
The default is
‘risk’ if fig_type=’RR_risk’,
‘rate of returns’ otherwise.
- ‘ylabel’str
The default is
‘rate of returns’ if fig_type=’RR_risk’
‘sharpe’ if fig_type=’Sharpe_RR’
‘diversification’ if fig_type=diverse_RR
- ‘tangent’Boolean
If set to True, then the tangent (to max sharpe point) is added. It has effect only if fig_type=’RR_risk’. The default is True.
- savetostr
File name to save the figure. The extension dictates the format: png, pdf, svg, etc. For more details see the mathplotlib documentation for savefig. The default is None.
- datadefaultdict
Numerical data to construct the plot. If it is not None, then it will take precedence and no other numerical evaluations will be performed. It is meant to produce different plot representations without reevaluations. The default is None.
- invN_labelstr
The label for equal weighted portfolio. The default is ‘1/N’.
- invNrisk_labelstr
The lable for efficient portfolio with same risk as equal weighted portfolio. The default is invNrisk.
- invNdiverse_labelstr
The label for diverse-efficient portfolio with the same diversificeation factor as equal weighted porfolio. The default is ‘invNdiv’.
- invNdrr_labelstr
The label of diverse-efficient portfolio with the same expected rate of return as equal weighted portolio. The defualt is ‘invNdrr’.
- maxdiverse_labelstr
The label of maximum diverified portfolio. The default is ‘MaxD’.
- minrisk_label‘str’
The label of minimum risk portfolio. The default is ‘MinR’.
- sharpe_labelstr
The label of maximum Sharpe portfolio. The default is ‘Sharpe’.
- Returns:
- `dict`Numerical data used to make the plots. It can be passed back
- to reconstruct the plots without reevaluations.
azapy.Analyzers.GINIAnalyzer module¶
- class azapy.Analyzers.GINIAnalyzer.GINIAnalyzer(mktdata=None, colname='adjusted', freq='Q', hlength=1.25, name='GINI', rtype='Sharpe', mu=None, d=1, mu0=0.0, aversion=None, ww0=None, method='ecos')
Bases:
_RiskAnalyzer
GINI based optimal portfolio strategies.
- Attributes
status : int - the computation status (0 - success, any other value signifies an error)
ww : pandas.Series - the portfolio weights
RR : float - portfolio rate of return
risk : float - portfolio GINI risk
primary_risk_comp : list - redundant (single element list containig GINI risk value)
secondary_risk_comp : list - redundant (same as primary_risk_comp)
sharpe : float - GINI-Sharpe ration if rtype is set to ‘Shapre’ or ‘Sharpe2’ otherwise None.
diverse : float - diversification factor if rtype is set to ‘Divers’ or ‘MaxDivers’ otherwise None.
name : str - portfolio name
- Note the following 2 important methods:
getWeights : Computes the optimal portfolio weights. During its computations the following class members are also set: risk, primery_risk_comp, secondary_risk_comp, sharpe, RR, divers.
getPositions : Provides practical information regarding the portfolio rebalancing delta positions and costs.
Methods
getDiversification
(ww[, rrate])Returns the value of the diversification factor for a give portfolio.
getPositions
([nshares, cash, ww, verbose])Computes the rebalanced number of shares.
getRisk
(ww[, rrate])Returns the value of the dispersion (risk) measure for a give portfolio.
Returns the risk of each portfolio component.
getWeights
([rtype, mu, d, mu0, aversion, ...])Computes the optimal portfolio weights.
set_method
(method)Sets computation method.
set_mktdata
(mktdata[, colname, freq, ...])Sets historical market data.
set_random_seed
([seed])Sets the seed for Dirichlet random generator used in viewFrontiers to select the random inefficient portfolios.
set_rrate
(rrate)Sets the MkT Data.
set_rtype
([rtype, mu, d, mu0, aversion, ww0])Sets the optimization type.
viewFrontiers
([minrisk, efficient, ...])Computes the elements of the portfolio frontiers.
- __init__(mktdata=None, colname='adjusted', freq='Q', hlength=1.25, name='GINI', rtype='Sharpe', mu=None, d=1, mu0=0.0, aversion=None, ww0=None, method='ecos')
Constructor
- Parameters:
- mktdatapandas.DataFrame, optional
Historic daily market data for portfolio components in the format returned by azapy.mktData function. The default is None.
- colnamestr, optional
Name of the price column from mktdata used in the weight’s calibration. The default is ‘adjusted’.
- freqstr, optional
Rate of return horizon. It could be ‘Q’ for a quarter or ‘M’ for a month. The default is ‘Q’.
- hlengthfloat, optional
History length in number of years used for calibration. A fractional number will be rounded to an integer number of months. The default is 3.25 years.
- namestr, optional
Portfolio name. The default is ‘GINI’.
- rtypestr, optional
Optimization type. Possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
The default is ‘Sharpe’.
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- methodstr, optional
Linear programming numerical method. Could be: ‘ecos’, ‘highs-ds’, ‘highs-ipm’, ‘highs’, ‘interior-point’, ‘glpk’ and ‘cvxopt’. The default is ‘ecos’.
- Returns:
- The object.
- getDiversification(ww, rrate=None)
Returns the value of the diversification factor for a give portfolio.
- Parameters:
- wwlist, numpy.array or pandas.Series;
Portfolio weights. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >=0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (not necessarily in the same order).
- rratepandas.DataFrame, optional
Contains the portfolio components historical rates of return. If it is not None then it will overwrite the rates of return computed in the constructor from mktdata. The default is None.
- Returns:
- `float`The diversification value.
- getPositions(nshares=None, cash=0, ww=None, verbose=True)
Computes the rebalanced number of shares.
- Parameters:
- nsharespanda.Series, optional
Initial number of shares per portfolio component. A missing component entry will be considered 0. A None value assumes that all components entries are 0. The name of the components must be present in the mrkdata. The default is None.
- cashfloat, optional
Additional cash to be added to the capital. A negative entry assumes a reduction in the total capital available for rebalance. The total capital cannot be < 0. The default is 0.
- wwpanda.Series, optional
External overwrite portfolio weights. If it not set to None these weights will overwrite the calibration results. The default is None.
- verboseBoolean, optional
Is it set to True the function prints the closing prices date. The default is True.
- Returns:
- `pandas.DataFrame`the rolling information.
- Columns:
- ‘old_nsh’ :
initial number of shares per portfolio component and the additional cash. These are input values.
- ‘new_nsh’ :
the new number of shares per component plus the residual cash (due to the rounding to an integer number of shares). A negative entry means that the investor needs to add more cash to cover for the roundup shortfall. It has a small value.
- ‘diff_nsh’ :
number of shares (buy/sale) needed to rebalance the portfolio.
- ‘weights’ :
portfolio weights used for rebalancing. The cash entry is the new portfolio value (invested capital).
- ‘prices’ :
the share prices used for rebalances evaluations.
Note: Since the prices are closing prices, the rebalance can be computed after the market close and before the trading execution (next day). Additional cash slippage may occur due to share price differential between the previous day closing and execution time.
- getRisk(ww, rrate=None)
Returns the value of the dispersion (risk) measure for a give portfolio.
- Parameters:
- wwlist, numpy.array or pandas.Series
Portfolio weights. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >=0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series than the index should be compatible with the rrate.columns or mktdata symbols (not necessarily in the same order).
- rratepandas.DataFrame, optional
Contains the portfolio components historical rates of return. If it is not None, it will overwrite the rates of return computed in the constructor from mktdata. The default is None.
- Returns:
- `float`The dispersion (risk) measure value.
- getRiskComp()
Returns the risk of each portfolio component.
- Returns:
- `pandas.Series`risk per symbol.
- getWeights(rtype=None, mu=None, d=1, mu0=0.0, aversion=None, ww0=None, mktdata=None, **params)
Computes the optimal portfolio weights.
- Parameters:
- rtypestr, optional
Optimization type. If is not None it will overwrite the value set by the constructor. The default is None. Other possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- mktdatapandas.DataFrame, optional
The portfolio components historical, prices or rates of return, see ‘pclose’ definition below. If it is not None, it will overwrite the set of historical rates of return computed in the constructor from ‘mktdata’. The default is None.
- **paramsother optional parameters
Most common:
- verboseBoolean, optional
If it set to True, then it will print a message when the optimal portfolio degenerates to a single asset. The default is False.
- pcloseBoolean, optional
If it is absent then the mktdata is considered to contain rates of return, with columns the asset symbols and indexed by the observation dates,
True : assumes mktdata contains closing prices only, with columns the asset symbols and indexed by the observation dates,
False : assumes mktdata is in the usual format returned by azapy.mktData function.
- Returns:
- `pandas.Series`portfolio weights per symbol.
- set_method(method)
Sets computation method.
- Parameters:
- methodstr;
Must be a valid method name. It will overwrite the value set by the constructor.
- Returns:
- None
- set_mktdata(mktdata, colname=None, freq=None, hlength=None, pclose=False)
Sets historical market data. It will overwrite the choice made in the constructor.
- Parameters:
- mktdatapandas.DataFrame
Historic daily market data for portfolio components in the format returned by azapy.mktData function.
- colnamestr, optional
Name of the price column from mktdata used in the weight’s calibration. The default is ‘adjusted’.
- freqstr, optional
Rate of return horizon. It could be ‘Q’ for a quarter or ‘M’ for a month. The default is ‘Q’.
- hlengthfloat, optional
History length in number of years used for calibration. A fractional number will be rounded to an integer number of months. The default is 3.25.
- pcloseBoolean, optional
True : assumes mktdata contains closing prices only, with columns the asset symbols and indexed by the observation dates,
False : assumes mktdata is in the usual format returned by azapy.mktData function.
- Returns:
- None
- set_random_seed(seed=42)
Sets the seed for Dirichlet random generator used in viewFrontiers to select the random inefficient portfolios.
- Parameters:
- seedint, optional
The random generator seed, in case you want to set it to a weird value other than 42 :). The default is 42.
- Returns:
- None
- set_rrate(rrate)
Sets the MkT Data.
- Parameters:
- rratepandas.DataFrame
Market data. It will overwrite the value set by the constructor.
- Returns
- ——-
- `None`
- set_rtype(rtype=None, mu=None, d=1, mu0=0.0, aversion=None, ww0=None)
Sets the optimization type. It will overwrite the value set in the constructor.
- Parameters:
- rtypestr, optional
Optimization type. Possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
The default is ‘Sharpe’.
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- Returns:
- None
- viewFrontiers(minrisk=True, efficient=20, inefficient=20, sharpe=True, musharpe=0.0, maxdiverse=False, diverse_efficient=0, diverse_inefficient=0, invN=True, invNrisk=True, invNdiverse=False, invNdrr=False, component=True, randomport=20, addport=None, fig_type='RR_risk', **opt)
Computes the elements of the portfolio frontiers.
- Parameters:
- minriskBoolean, optional
If it is True then the minimum risk portfolio will be visible. The default is True.
- efficientint, optional
Number of points along the efficient risk frontier (equally spaced along the rate of return axis). The default is 20.
- inefficientint, optional
Number of points along the inefficient risk frontier (equally spaced along the rate of returns axis). The default is 20.
- sharpeBoolean, optional
If it is True then the maximum Sharpe portfolio will be visible. The default is True.
- musharpefloat, optional
Risk-free rate value used in the evaluation of generalized Sharpe ratio. The default is 0.
- maxdiverseBoolean, optional
If it is True then the maximum diversified portfolio will be visible. The default is True.
- diverse_efficientint, optional
Number of points along the efficient diversification frontier (equally spaced along the rate of return axis). The default is 20.
- diverse_inefficientint, optional
Number of points along the inefficient diversification frontier (equally spaced along the rate of return axis). The default is 20.
- invNBoolean, optional
If it is True, then the equal weighted portfolio and the optimal portfolio with the same risk value are added to the plot. The default is True.
- invNriskBoolean, optional
If it is True, then the efficient risk portfolio with same risk as equal weighted portfolio is added to the plot. The default is False.
- invNdiverseBoolean, optional
If it is True, then the efficient diversified portfolio with the same diversification factor as the equal weighted portfolio is added to the plot. The default is False.
- invNdrrBoolean, optional
If it is True, then the efficient diversified portfolio with the same expected rate of return as the equal weighted portfolio is added to the plot. The default value is False.
- componentBoolean, optional
If it is True, then the single component portfolios are added to the plot. The default is True.
- randomportint, optional
Number of portfolios with random weights (inefficient) to be added to the plot (for reference). The default is 20.
- addportdict or pandas.DataFrame, optional
The weights of additional portfolio to be added to the plot. If it is a dict then the keys are the labels, and the values are list of weights in the order of rrate.columns. If it is a pandas.DataFrame the index are the labels, and each row is a set of weights. The columns names should match the symbols names. The default is None.
- fig_typestr, optional
Graphical representation format.
‘RR_risk’ : expected rate of return vs risk
‘Sharpe_RR’ : sharpe vs expected rate of return
‘Diverse_RR’ : diversification vs expected rate of return
The default is ‘RR_risk’.
- **optoptional
Additional parameters:
- ‘title’str
The default is ‘Portfolio frontiers’.
- ‘xlabel’str
The default is
‘risk’ if fig_type=’RR_risk’,
‘rate of returns’ otherwise.
- ‘ylabel’str
The default is
‘rate of returns’ if fig_type=’RR_risk’
‘sharpe’ if fig_type=’Sharpe_RR’
‘diversification’ if fig_type=diverse_RR
- ‘tangent’Boolean
If set to True, then the tangent (to max sharpe point) is added. It has effect only if fig_type=’RR_risk’. The default is True.
- savetostr
File name to save the figure. The extension dictates the format: png, pdf, svg, etc. For more details see the mathplotlib documentation for savefig. The default is None.
- datadefaultdict
Numerical data to construct the plot. If it is not None, then it will take precedence and no other numerical evaluations will be performed. It is meant to produce different plot representations without reevaluations. The default is None.
- invN_labelstr
The label for equal weighted portfolio. The default is ‘1/N’.
- invNrisk_labelstr
The lable for efficient portfolio with same risk as equal weighted portfolio. The default is invNrisk.
- invNdiverse_labelstr
The label for diverse-efficient portfolio with the same diversificeation factor as equal weighted porfolio. The default is ‘invNdiv’.
- invNdrr_labelstr
The label of diverse-efficient portfolio with the same expected rate of return as equal weighted portolio. The defualt is ‘invNdrr’.
- maxdiverse_labelstr
The label of maximum diverified portfolio. The default is ‘MaxD’.
- minrisk_label‘str’
The label of minimum risk portfolio. The default is ‘MinR’.
- sharpe_labelstr
The label of maximum Sharpe portfolio. The default is ‘Sharpe’.
- Returns:
- `dict`Numerical data used to make the plots. It can be passed back
- to reconstruct the plots without reevaluations.
azapy.Analyzers.LSDAnalyzer module¶
- class azapy.Analyzers.LSDAnalyzer.LSDAnalyzer(coef=[1.0], mktdata=None, colname='adjusted', freq='Q', hlength=3.25, name='LSD', rtype='Sharpe', mu=None, d=1, mu0=0.0, aversion=None, ww0=None, method='ecos')
Bases:
MADAnalyzer
m-level LSD (lower Standard Deviation) based optimal portfolio strategies.
- Attributes
status : int - the computation status (0 - success, any other value signifies an error)
ww : pandas.Series - the portfolio weights
RR : float - portfolio rate of return
risk : float - portfolio mLSD risk
primary_risk_comp : list - delta-risk components of portfolio mLSD
secondary_risk_comp : list - cumulative delta-risk components of mLSD
sharpe : float - mLSD-Sharpe ration if rtype is set to ‘Shapre’ or ‘Sharpe2’ otherwise None.
diverse : float - diversification factor if rtype is set to ‘Divers’ or ‘MaxDivers’ otherwise None.
name : str - portfolio name
- Note the following 2 important methods:
getWeights : Computes the optimal portfolio weights. During its computations the following class members are also set: risk, primery_risk_comp, secondary_risk_comp, sharpe, RR, divers.
getPositions : Provides practical information regarding the portfolio rebalancing delta positions and costs.
Methods
getDiversification
(ww[, rrate])Returns the value of the diversification factor for a give portfolio.
getPositions
([nshares, cash, ww, verbose])Computes the rebalanced number of shares.
getRisk
(ww[, rrate])Returns the value of MAD for a given portfolio.
Returns the risk of each portfolio component.
getWeights
([rtype, mu, d, mu0, aversion, ...])Computes the optimal portfolio weights.
set_method
(method)Sets computation method.
set_mktdata
(mktdata[, colname, freq, ...])Sets historical market data.
set_random_seed
([seed])Sets the seed for Dirichlet random generator used in viewFrontiers to select the random inefficient portfolios.
set_rrate
(rrate)Sets portfolio components historical rates of return.
set_rtype
([rtype, mu, d, mu0, aversion, ww0])Sets the optimization type.
viewFrontiers
([minrisk, efficient, ...])Computes the elements of the portfolio frontiers.
- __init__(coef=[1.0], mktdata=None, colname='adjusted', freq='Q', hlength=3.25, name='LSD', rtype='Sharpe', mu=None, d=1, mu0=0.0, aversion=None, ww0=None, method='ecos')
Constructor
- Parameters:
- coeflist, optional
Positive non-increasing list of mixture coefficients. The default is [1.].
- mktdatapandas.DataFrame, optional
Historic daily market data for portfolio components in the format returned by azapy.mktData function. The default is None.
- colnamestr, optional
Name of the price column from mktdata used in the weight’s calibration. The default is ‘adjusted’.
- freqstr, optional
Rate of return horizon. It could be ‘Q’ for a quarter or ‘M’ for a month. The default is ‘Q’.
- hlengthfloat, optional
History length in number of years used for calibration. A fractional number will be rounded to an integer number of months. The default is 3.25 years.
- namestr, optional
Portfolio name. The default is ‘LSD’.
- rtypestr, optional
Optimization type. Possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
The default is ‘Sharpe’.
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- methodstr, optional
SOCP numerical method. Could be: ‘ecos’ or ‘cvxopt’. The defualt is ‘ecos’.
- Returns:
- The object.
- getDiversification(ww, rrate=None)
Returns the value of the diversification factor for a give portfolio.
- Parameters:
- wwlist, numpy.array or pandas.Series;
Portfolio weights. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >=0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (not necessarily in the same order).
- rratepandas.DataFrame, optional
Contains the portfolio components historical rates of return. If it is not None then it will overwrite the rates of return computed in the constructor from mktdata. The default is None.
- Returns:
- `float`The diversification value.
- getPositions(nshares=None, cash=0, ww=None, verbose=True)
Computes the rebalanced number of shares.
- Parameters:
- nsharespanda.Series, optional
Initial number of shares per portfolio component. A missing component entry will be considered 0. A None value assumes that all components entries are 0. The name of the components must be present in the mrkdata. The default is None.
- cashfloat, optional
Additional cash to be added to the capital. A negative entry assumes a reduction in the total capital available for rebalance. The total capital cannot be < 0. The default is 0.
- wwpanda.Series, optional
External overwrite portfolio weights. If it not set to None these weights will overwrite the calibration results. The default is None.
- verboseBoolean, optional
Is it set to True the function prints the closing prices date. The default is True.
- Returns:
- `pandas.DataFrame`the rolling information.
- Columns:
- ‘old_nsh’ :
initial number of shares per portfolio component and the additional cash. These are input values.
- ‘new_nsh’ :
the new number of shares per component plus the residual cash (due to the rounding to an integer number of shares). A negative entry means that the investor needs to add more cash to cover for the roundup shortfall. It has a small value.
- ‘diff_nsh’ :
number of shares (buy/sale) needed to rebalance the portfolio.
- ‘weights’ :
portfolio weights used for rebalancing. The cash entry is the new portfolio value (invested capital).
- ‘prices’ :
the share prices used for rebalances evaluations.
Note: Since the prices are closing prices, the rebalance can be computed after the market close and before the trading execution (next day). Additional cash slippage may occur due to share price differential between the previous day closing and execution time.
- getRisk(ww, rrate=None)
Returns the value of MAD for a given portfolio.
- Parameters:
- wwlist (numpy.array or pandas.Series)
Portfolio weights.
- rratepandas.series, optional
The portfolio components historical rates of return. If it is not None, it will overwrite the rates of return computed in the constructor from mktdata. The default is None.
- Returns:
- float
- The value of mMAD
- getRiskComp()
Returns the risk of each portfolio component.
- Returns:
- `pandas.Series`risk per symbol.
- getWeights(rtype=None, mu=None, d=1, mu0=0.0, aversion=None, ww0=None, mktdata=None, **params)
Computes the optimal portfolio weights.
- Parameters:
- rtypestr, optional
Optimization type. If is not None it will overwrite the value set by the constructor. The default is None. Other possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- mktdatapandas.DataFrame, optional
The portfolio components historical, prices or rates of return, see ‘pclose’ definition below. If it is not None, it will overwrite the set of historical rates of return computed in the constructor from ‘mktdata’. The default is None.
- **paramsother optional parameters
Most common:
- verboseBoolean, optional
If it set to True, then it will print a message when the optimal portfolio degenerates to a single asset. The default is False.
- pcloseBoolean, optional
If it is absent then the mktdata is considered to contain rates of return, with columns the asset symbols and indexed by the observation dates,
True : assumes mktdata contains closing prices only, with columns the asset symbols and indexed by the observation dates,
False : assumes mktdata is in the usual format returned by azapy.mktData function.
- Returns:
- `pandas.Series`portfolio weights per symbol.
- set_method(method)
Sets computation method.
- Parameters:
- methodstr;
Must be a valid method name. It will overwrite the value set by the constructor.
- Returns:
- None
- set_mktdata(mktdata, colname=None, freq=None, hlength=None, pclose=False)
Sets historical market data. It will overwrite the choice made in the constructor.
- Parameters:
- mktdatapandas.DataFrame
Historic daily market data for portfolio components in the format returned by azapy.mktData function.
- colnamestr, optional
Name of the price column from mktdata used in the weight’s calibration. The default is ‘adjusted’.
- freqstr, optional
Rate of return horizon. It could be ‘Q’ for a quarter or ‘M’ for a month. The default is ‘Q’.
- hlengthfloat, optional
History length in number of years used for calibration. A fractional number will be rounded to an integer number of months. The default is 3.25.
- pcloseBoolean, optional
True : assumes mktdata contains closing prices only, with columns the asset symbols and indexed by the observation dates,
False : assumes mktdata is in the usual format returned by azapy.mktData function.
- Returns:
- None
- set_random_seed(seed=42)
Sets the seed for Dirichlet random generator used in viewFrontiers to select the random inefficient portfolios.
- Parameters:
- seedint, optional
The random generator seed, in case you want to set it to a weird value other than 42 :). The default is 42.
- Returns:
- None
- set_rrate(rrate)
Sets portfolio components historical rates of return. It will overwrite the value computed by the constructor from mktdata.
- Parameters:
- rratepandas.DataFrame
Portfolio components historical rates of return. The columns are asset symbols and indexed by observation dates.
- Returns:
- None
- set_rtype(rtype=None, mu=None, d=1, mu0=0.0, aversion=None, ww0=None)
Sets the optimization type. It will overwrite the value set in the constructor.
- Parameters:
- rtypestr, optional
Optimization type. Possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
The default is ‘Sharpe’.
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- Returns:
- None
- viewFrontiers(minrisk=True, efficient=20, inefficient=20, sharpe=True, musharpe=0.0, maxdiverse=False, diverse_efficient=0, diverse_inefficient=0, invN=True, invNrisk=True, invNdiverse=False, invNdrr=False, component=True, randomport=20, addport=None, fig_type='RR_risk', **opt)
Computes the elements of the portfolio frontiers.
- Parameters:
- minriskBoolean, optional
If it is True then the minimum risk portfolio will be visible. The default is True.
- efficientint, optional
Number of points along the efficient risk frontier (equally spaced along the rate of return axis). The default is 20.
- inefficientint, optional
Number of points along the inefficient risk frontier (equally spaced along the rate of returns axis). The default is 20.
- sharpeBoolean, optional
If it is True then the maximum Sharpe portfolio will be visible. The default is True.
- musharpefloat, optional
Risk-free rate value used in the evaluation of generalized Sharpe ratio. The default is 0.
- maxdiverseBoolean, optional
If it is True then the maximum diversified portfolio will be visible. The default is True.
- diverse_efficientint, optional
Number of points along the efficient diversification frontier (equally spaced along the rate of return axis). The default is 20.
- diverse_inefficientint, optional
Number of points along the inefficient diversification frontier (equally spaced along the rate of return axis). The default is 20.
- invNBoolean, optional
If it is True, then the equal weighted portfolio and the optimal portfolio with the same risk value are added to the plot. The default is True.
- invNriskBoolean, optional
If it is True, then the efficient risk portfolio with same risk as equal weighted portfolio is added to the plot. The default is False.
- invNdiverseBoolean, optional
If it is True, then the efficient diversified portfolio with the same diversification factor as the equal weighted portfolio is added to the plot. The default is False.
- invNdrrBoolean, optional
If it is True, then the efficient diversified portfolio with the same expected rate of return as the equal weighted portfolio is added to the plot. The default value is False.
- componentBoolean, optional
If it is True, then the single component portfolios are added to the plot. The default is True.
- randomportint, optional
Number of portfolios with random weights (inefficient) to be added to the plot (for reference). The default is 20.
- addportdict or pandas.DataFrame, optional
The weights of additional portfolio to be added to the plot. If it is a dict then the keys are the labels, and the values are list of weights in the order of rrate.columns. If it is a pandas.DataFrame the index are the labels, and each row is a set of weights. The columns names should match the symbols names. The default is None.
- fig_typestr, optional
Graphical representation format.
‘RR_risk’ : expected rate of return vs risk
‘Sharpe_RR’ : sharpe vs expected rate of return
‘Diverse_RR’ : diversification vs expected rate of return
The default is ‘RR_risk’.
- **optoptional
Additional parameters:
- ‘title’str
The default is ‘Portfolio frontiers’.
- ‘xlabel’str
The default is
‘risk’ if fig_type=’RR_risk’,
‘rate of returns’ otherwise.
- ‘ylabel’str
The default is
‘rate of returns’ if fig_type=’RR_risk’
‘sharpe’ if fig_type=’Sharpe_RR’
‘diversification’ if fig_type=diverse_RR
- ‘tangent’Boolean
If set to True, then the tangent (to max sharpe point) is added. It has effect only if fig_type=’RR_risk’. The default is True.
- savetostr
File name to save the figure. The extension dictates the format: png, pdf, svg, etc. For more details see the mathplotlib documentation for savefig. The default is None.
- datadefaultdict
Numerical data to construct the plot. If it is not None, then it will take precedence and no other numerical evaluations will be performed. It is meant to produce different plot representations without reevaluations. The default is None.
- invN_labelstr
The label for equal weighted portfolio. The default is ‘1/N’.
- invNrisk_labelstr
The lable for efficient portfolio with same risk as equal weighted portfolio. The default is invNrisk.
- invNdiverse_labelstr
The label for diverse-efficient portfolio with the same diversificeation factor as equal weighted porfolio. The default is ‘invNdiv’.
- invNdrr_labelstr
The label of diverse-efficient portfolio with the same expected rate of return as equal weighted portolio. The defualt is ‘invNdrr’.
- maxdiverse_labelstr
The label of maximum diverified portfolio. The default is ‘MaxD’.
- minrisk_label‘str’
The label of minimum risk portfolio. The default is ‘MinR’.
- sharpe_labelstr
The label of maximum Sharpe portfolio. The default is ‘Sharpe’.
- Returns:
- `dict`Numerical data used to make the plots. It can be passed back
- to reconstruct the plots without reevaluations.
azapy.Analyzers.MADAnalyzer module¶
- class azapy.Analyzers.MADAnalyzer.MADAnalyzer(coef=[1.0], mktdata=None, colname='adjusted', freq='Q', hlength=3.25, name='MAD', rtype='Sharpe', mu=None, d=1, mu0=0.0, aversion=None, ww0=None, method='ecos')
Bases:
_RiskAnalyzer
m-level MAD (Mean Absolute Deviation) based optimal portfolio strategies.
- Attributes
status : int - the computation status (0 - success, any other value signifies an error)
ww : pandas.Series - the portfolio weights
RR : float - portfolio rate of return
risk : float - portfolio mMAD risk
primary_risk_comp : list - delta-risk components of portfolio mMAD
secondary_risk_comp : list - cumulative delta-risk components of mMAD
sharpe : float - mMAD-Sharpe ration if rtype is set to ‘Shapre’ or ‘Sharpe2’ otherwise None.
diverse : float - diversification factor if rtype is set to ‘Divers’ or ‘MaxDivers’ otherwise None.
name : str - portfolio name
- Note the following 2 important methods:
getWeights : Computes the optimal portfolio weights. During its computations the following class members are also set: risk, primery_risk_comp, secondary_risk_comp, sharpe, RR, divers.
getPositions : Provides practical information regarding the portfolio rebalancing delta positions and costs.
Methods
getDiversification
(ww[, rrate])Returns the value of the diversification factor for a give portfolio.
getPositions
([nshares, cash, ww, verbose])Computes the rebalanced number of shares.
getRisk
(ww[, rrate])Returns the value of MAD for a given portfolio.
Returns the risk of each portfolio component.
getWeights
([rtype, mu, d, mu0, aversion, ...])Computes the optimal portfolio weights.
set_method
(method)Sets computation method.
set_mktdata
(mktdata[, colname, freq, ...])Sets historical market data.
set_random_seed
([seed])Sets the seed for Dirichlet random generator used in viewFrontiers to select the random inefficient portfolios.
set_rrate
(rrate)Sets portfolio components historical rates of return.
set_rtype
([rtype, mu, d, mu0, aversion, ww0])Sets the optimization type.
viewFrontiers
([minrisk, efficient, ...])Computes the elements of the portfolio frontiers.
- __init__(coef=[1.0], mktdata=None, colname='adjusted', freq='Q', hlength=3.25, name='MAD', rtype='Sharpe', mu=None, d=1, mu0=0.0, aversion=None, ww0=None, method='ecos')
Constructor
- Parameters:
- coeflist, optional
Positive non-increasing list of mixture coefficients. The default is [1.].
- mktdatapandas.DataFrame, optional
Historic daily market data for portfolio components in the format returned by azapy.mktData function. The default is None.
- colnamestr, optional
Name of the price column from mktdata used in the weight’s calibration. The default is ‘adjusted’.
- freqstr, optional
Rate of return horizon. It could be ‘Q’ for a quarter or ‘M’ for a month. The default is ‘Q’.
- hlengthfloat, optional
History length in number of years used for calibration. A fractional number will be rounded to an integer number of months. The default is 3.25 years.
- namestr, optional
Portfolio name. The default is ‘MAD’.
- rtypestr, optional
Optimization type. Possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
The default is ‘Sharpe’.
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- methodstr, optional
Linear programming numerical method. Could be: ‘ecos’, ‘highs-ds’, ‘highs-ipm’, ‘highs’, ‘interior-point’, ‘glpk’ and ‘cvxopt’. The default is ‘ecos’.
- Returns:
- The object.
- getDiversification(ww, rrate=None)
Returns the value of the diversification factor for a give portfolio.
- Parameters:
- wwlist, numpy.array or pandas.Series;
Portfolio weights. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >=0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (not necessarily in the same order).
- rratepandas.DataFrame, optional
Contains the portfolio components historical rates of return. If it is not None then it will overwrite the rates of return computed in the constructor from mktdata. The default is None.
- Returns:
- `float`The diversification value.
- getPositions(nshares=None, cash=0, ww=None, verbose=True)
Computes the rebalanced number of shares.
- Parameters:
- nsharespanda.Series, optional
Initial number of shares per portfolio component. A missing component entry will be considered 0. A None value assumes that all components entries are 0. The name of the components must be present in the mrkdata. The default is None.
- cashfloat, optional
Additional cash to be added to the capital. A negative entry assumes a reduction in the total capital available for rebalance. The total capital cannot be < 0. The default is 0.
- wwpanda.Series, optional
External overwrite portfolio weights. If it not set to None these weights will overwrite the calibration results. The default is None.
- verboseBoolean, optional
Is it set to True the function prints the closing prices date. The default is True.
- Returns:
- `pandas.DataFrame`the rolling information.
- Columns:
- ‘old_nsh’ :
initial number of shares per portfolio component and the additional cash. These are input values.
- ‘new_nsh’ :
the new number of shares per component plus the residual cash (due to the rounding to an integer number of shares). A negative entry means that the investor needs to add more cash to cover for the roundup shortfall. It has a small value.
- ‘diff_nsh’ :
number of shares (buy/sale) needed to rebalance the portfolio.
- ‘weights’ :
portfolio weights used for rebalancing. The cash entry is the new portfolio value (invested capital).
- ‘prices’ :
the share prices used for rebalances evaluations.
Note: Since the prices are closing prices, the rebalance can be computed after the market close and before the trading execution (next day). Additional cash slippage may occur due to share price differential between the previous day closing and execution time.
- getRisk(ww, rrate=None)
Returns the value of MAD for a given portfolio.
- Parameters:
- wwlist (numpy.array or pandas.Series)
Portfolio weights.
- rratepandas.series, optional
The portfolio components historical rates of return. If it is not None, it will overwrite the rates of return computed in the constructor from mktdata. The default is None.
- Returns:
- float
- The value of mMAD
- getRiskComp()
Returns the risk of each portfolio component.
- Returns:
- `pandas.Series`risk per symbol.
- getWeights(rtype=None, mu=None, d=1, mu0=0.0, aversion=None, ww0=None, mktdata=None, **params)
Computes the optimal portfolio weights.
- Parameters:
- rtypestr, optional
Optimization type. If is not None it will overwrite the value set by the constructor. The default is None. Other possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- mktdatapandas.DataFrame, optional
The portfolio components historical, prices or rates of return, see ‘pclose’ definition below. If it is not None, it will overwrite the set of historical rates of return computed in the constructor from ‘mktdata’. The default is None.
- **paramsother optional parameters
Most common:
- verboseBoolean, optional
If it set to True, then it will print a message when the optimal portfolio degenerates to a single asset. The default is False.
- pcloseBoolean, optional
If it is absent then the mktdata is considered to contain rates of return, with columns the asset symbols and indexed by the observation dates,
True : assumes mktdata contains closing prices only, with columns the asset symbols and indexed by the observation dates,
False : assumes mktdata is in the usual format returned by azapy.mktData function.
- Returns:
- `pandas.Series`portfolio weights per symbol.
- set_method(method)
Sets computation method.
- Parameters:
- methodstr;
Must be a valid method name. It will overwrite the value set by the constructor.
- Returns:
- None
- set_mktdata(mktdata, colname=None, freq=None, hlength=None, pclose=False)
Sets historical market data. It will overwrite the choice made in the constructor.
- Parameters:
- mktdatapandas.DataFrame
Historic daily market data for portfolio components in the format returned by azapy.mktData function.
- colnamestr, optional
Name of the price column from mktdata used in the weight’s calibration. The default is ‘adjusted’.
- freqstr, optional
Rate of return horizon. It could be ‘Q’ for a quarter or ‘M’ for a month. The default is ‘Q’.
- hlengthfloat, optional
History length in number of years used for calibration. A fractional number will be rounded to an integer number of months. The default is 3.25.
- pcloseBoolean, optional
True : assumes mktdata contains closing prices only, with columns the asset symbols and indexed by the observation dates,
False : assumes mktdata is in the usual format returned by azapy.mktData function.
- Returns:
- None
- set_random_seed(seed=42)
Sets the seed for Dirichlet random generator used in viewFrontiers to select the random inefficient portfolios.
- Parameters:
- seedint, optional
The random generator seed, in case you want to set it to a weird value other than 42 :). The default is 42.
- Returns:
- None
- set_rrate(rrate)
Sets portfolio components historical rates of return. It will overwrite the value computed by the constructor from mktdata.
- Parameters:
- rratepandas.DataFrame
Portfolio components historical rates of return. The columns are asset symbols and indexed by observation dates.
- Returns:
- None
- set_rtype(rtype=None, mu=None, d=1, mu0=0.0, aversion=None, ww0=None)
Sets the optimization type. It will overwrite the value set in the constructor.
- Parameters:
- rtypestr, optional
Optimization type. Possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
The default is ‘Sharpe’.
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- Returns:
- None
- viewFrontiers(minrisk=True, efficient=20, inefficient=20, sharpe=True, musharpe=0.0, maxdiverse=False, diverse_efficient=0, diverse_inefficient=0, invN=True, invNrisk=True, invNdiverse=False, invNdrr=False, component=True, randomport=20, addport=None, fig_type='RR_risk', **opt)
Computes the elements of the portfolio frontiers.
- Parameters:
- minriskBoolean, optional
If it is True then the minimum risk portfolio will be visible. The default is True.
- efficientint, optional
Number of points along the efficient risk frontier (equally spaced along the rate of return axis). The default is 20.
- inefficientint, optional
Number of points along the inefficient risk frontier (equally spaced along the rate of returns axis). The default is 20.
- sharpeBoolean, optional
If it is True then the maximum Sharpe portfolio will be visible. The default is True.
- musharpefloat, optional
Risk-free rate value used in the evaluation of generalized Sharpe ratio. The default is 0.
- maxdiverseBoolean, optional
If it is True then the maximum diversified portfolio will be visible. The default is True.
- diverse_efficientint, optional
Number of points along the efficient diversification frontier (equally spaced along the rate of return axis). The default is 20.
- diverse_inefficientint, optional
Number of points along the inefficient diversification frontier (equally spaced along the rate of return axis). The default is 20.
- invNBoolean, optional
If it is True, then the equal weighted portfolio and the optimal portfolio with the same risk value are added to the plot. The default is True.
- invNriskBoolean, optional
If it is True, then the efficient risk portfolio with same risk as equal weighted portfolio is added to the plot. The default is False.
- invNdiverseBoolean, optional
If it is True, then the efficient diversified portfolio with the same diversification factor as the equal weighted portfolio is added to the plot. The default is False.
- invNdrrBoolean, optional
If it is True, then the efficient diversified portfolio with the same expected rate of return as the equal weighted portfolio is added to the plot. The default value is False.
- componentBoolean, optional
If it is True, then the single component portfolios are added to the plot. The default is True.
- randomportint, optional
Number of portfolios with random weights (inefficient) to be added to the plot (for reference). The default is 20.
- addportdict or pandas.DataFrame, optional
The weights of additional portfolio to be added to the plot. If it is a dict then the keys are the labels, and the values are list of weights in the order of rrate.columns. If it is a pandas.DataFrame the index are the labels, and each row is a set of weights. The columns names should match the symbols names. The default is None.
- fig_typestr, optional
Graphical representation format.
‘RR_risk’ : expected rate of return vs risk
‘Sharpe_RR’ : sharpe vs expected rate of return
‘Diverse_RR’ : diversification vs expected rate of return
The default is ‘RR_risk’.
- **optoptional
Additional parameters:
- ‘title’str
The default is ‘Portfolio frontiers’.
- ‘xlabel’str
The default is
‘risk’ if fig_type=’RR_risk’,
‘rate of returns’ otherwise.
- ‘ylabel’str
The default is
‘rate of returns’ if fig_type=’RR_risk’
‘sharpe’ if fig_type=’Sharpe_RR’
‘diversification’ if fig_type=diverse_RR
- ‘tangent’Boolean
If set to True, then the tangent (to max sharpe point) is added. It has effect only if fig_type=’RR_risk’. The default is True.
- savetostr
File name to save the figure. The extension dictates the format: png, pdf, svg, etc. For more details see the mathplotlib documentation for savefig. The default is None.
- datadefaultdict
Numerical data to construct the plot. If it is not None, then it will take precedence and no other numerical evaluations will be performed. It is meant to produce different plot representations without reevaluations. The default is None.
- invN_labelstr
The label for equal weighted portfolio. The default is ‘1/N’.
- invNrisk_labelstr
The lable for efficient portfolio with same risk as equal weighted portfolio. The default is invNrisk.
- invNdiverse_labelstr
The label for diverse-efficient portfolio with the same diversificeation factor as equal weighted porfolio. The default is ‘invNdiv’.
- invNdrr_labelstr
The label of diverse-efficient portfolio with the same expected rate of return as equal weighted portolio. The defualt is ‘invNdrr’.
- maxdiverse_labelstr
The label of maximum diverified portfolio. The default is ‘MaxD’.
- minrisk_label‘str’
The label of minimum risk portfolio. The default is ‘MinR’.
- sharpe_labelstr
The label of maximum Sharpe portfolio. The default is ‘Sharpe’.
- Returns:
- `dict`Numerical data used to make the plots. It can be passed back
- to reconstruct the plots without reevaluations.
azapy.Analyzers.MVAnalyzer module¶
- class azapy.Analyzers.MVAnalyzer.MVAnalyzer(mktdata=None, colname='adjusted', freq='Q', hlength=3.25, name='MV', rtype='Sharpe', mu=None, d=1, mu0=0, aversion=None, ww0=None, method='ecos')
Bases:
_RiskAnalyzer
MV (Mean-Variance) - Variance based optimal portfolio strategies.
- Attributes
status : int - the computation status (0 - success, any other value signifies an error)
ww : pandas.Series - the portfolio weights
RR : float - portfolio rate of return
risk : float - portfolio MV risk
primary_risk_comp : list - redundant (single element list containing MV risk value)
secondary_risk_comp : list - redundant (same as primary_risk_comp)
sharpe : float - MV-Sharpe ration if rtype is set to ‘Shapre’ or ‘Sharpe2’ otherwise None.
diverse : float - diversification factor if rtype is set to ‘Divers’ or ‘MaxDivers’ otherwise None.
name : str - portfolio name
- Note the following 2 important methods:
getWeights : Computes the optimal portfolio weights. During its computations the following class members are also set: risk, primery_risk_comp, secondary_risk_comp, sharpe, RR, divers.
getPositions : Provides practical information regarding the portfolio rebalancing delta positions and costs.
Methods
getDiversification
(ww[, rrate])Returns the value of the diversification factor for a give portfolio.
getPositions
([nshares, cash, ww, verbose])Computes the rebalanced number of shares.
getRisk
(ww[, rrate])Returns the value of the dispersion (risk) measure for a give portfolio.
Returns the risk of each portfolio component.
getWeights
([rtype, mu, d, mu0, aversion, ...])Computes the optimal portfolio weights.
set_method
(method)Sets computation method.
set_mktdata
(mktdata[, colname, freq, ...])Sets historical market data.
set_random_seed
([seed])Sets the seed for Dirichlet random generator used in viewFrontiers to select the random inefficient portfolios.
set_rrate
(rrate)Sets portfolio components historical rates of return.
set_rtype
([rtype, mu, d, mu0, aversion, ww0])Sets the optimization type.
viewFrontiers
([minrisk, efficient, ...])Computes the elements of the portfolio frontiers.
- __init__(mktdata=None, colname='adjusted', freq='Q', hlength=3.25, name='MV', rtype='Sharpe', mu=None, d=1, mu0=0, aversion=None, ww0=None, method='ecos')
Constructor
- Parameters:
- mktdatapandas.DataFrame, optional
Historic daily market data for portfolio components in the format returned by azapy.mktData function. The default is None.
- colnamestr, optional
Name of the price column from mktdata used in the weight’s calibration. The default is ‘adjusted’.
- freqstr, optional
Rate of return horizon. It could be ‘Q’ for a quarter or ‘M’ for a month. The default is ‘Q’.
- hlengthfloat, optional
History length in number of years used for calibration. A fractional number will be rounded to an integer number of months. The default is 3.25 years.
- namestr, optional
Portfolio name. The default is ‘MV’.
- rtypestr, optional
Optimization type. Possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
The default is ‘Sharpe’.
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- methodstr, optional
Quadratic programming numerical method. Could be ‘ecos’ or ‘cvxopt’. The default is ‘ecos’.
- Returns:
- The object.
- getDiversification(ww, rrate=None)
Returns the value of the diversification factor for a give portfolio.
- Parameters:
- wwlist, numpy.array or pandas.Series;
Portfolio weights. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >=0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (not necessarily in the same order).
- rratepandas.DataFrame, optional
Contains the portfolio components historical rates of return. If it is not None then it will overwrite the rates of return computed in the constructor from mktdata. The default is None.
- Returns:
- `float`The diversification value.
- getPositions(nshares=None, cash=0, ww=None, verbose=True)
Computes the rebalanced number of shares.
- Parameters:
- nsharespanda.Series, optional
Initial number of shares per portfolio component. A missing component entry will be considered 0. A None value assumes that all components entries are 0. The name of the components must be present in the mrkdata. The default is None.
- cashfloat, optional
Additional cash to be added to the capital. A negative entry assumes a reduction in the total capital available for rebalance. The total capital cannot be < 0. The default is 0.
- wwpanda.Series, optional
External overwrite portfolio weights. If it not set to None these weights will overwrite the calibration results. The default is None.
- verboseBoolean, optional
Is it set to True the function prints the closing prices date. The default is True.
- Returns:
- `pandas.DataFrame`the rolling information.
- Columns:
- ‘old_nsh’ :
initial number of shares per portfolio component and the additional cash. These are input values.
- ‘new_nsh’ :
the new number of shares per component plus the residual cash (due to the rounding to an integer number of shares). A negative entry means that the investor needs to add more cash to cover for the roundup shortfall. It has a small value.
- ‘diff_nsh’ :
number of shares (buy/sale) needed to rebalance the portfolio.
- ‘weights’ :
portfolio weights used for rebalancing. The cash entry is the new portfolio value (invested capital).
- ‘prices’ :
the share prices used for rebalances evaluations.
Note: Since the prices are closing prices, the rebalance can be computed after the market close and before the trading execution (next day). Additional cash slippage may occur due to share price differential between the previous day closing and execution time.
- getRisk(ww, rrate=None)
Returns the value of the dispersion (risk) measure for a give portfolio.
- Parameters:
- wwlist, numpy.array or pandas.Series
Portfolio weights. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >=0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series than the index should be compatible with the rrate.columns or mktdata symbols (not necessarily in the same order).
- rratepandas.DataFrame, optional
Contains the portfolio components historical rates of return. If it is not None, it will overwrite the rates of return computed in the constructor from mktdata. The default is None.
- Returns:
- `float`The dispersion (risk) measure value.
- getRiskComp()
Returns the risk of each portfolio component.
- Returns:
- `pandas.Series`risk per symbol.
- getWeights(rtype=None, mu=None, d=1, mu0=0.0, aversion=None, ww0=None, mktdata=None, **params)
Computes the optimal portfolio weights.
- Parameters:
- rtypestr, optional
Optimization type. If is not None it will overwrite the value set by the constructor. The default is None. Other possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- mktdatapandas.DataFrame, optional
The portfolio components historical, prices or rates of return, see ‘pclose’ definition below. If it is not None, it will overwrite the set of historical rates of return computed in the constructor from ‘mktdata’. The default is None.
- **paramsother optional parameters
Most common:
- verboseBoolean, optional
If it set to True, then it will print a message when the optimal portfolio degenerates to a single asset. The default is False.
- pcloseBoolean, optional
If it is absent then the mktdata is considered to contain rates of return, with columns the asset symbols and indexed by the observation dates,
True : assumes mktdata contains closing prices only, with columns the asset symbols and indexed by the observation dates,
False : assumes mktdata is in the usual format returned by azapy.mktData function.
- Returns:
- `pandas.Series`portfolio weights per symbol.
- set_method(method)
Sets computation method.
- Parameters:
- methodstr;
Must be a valid method name. It will overwrite the value set by the constructor.
- Returns:
- None
- set_mktdata(mktdata, colname=None, freq=None, hlength=None, pclose=False)
Sets historical market data. It will overwrite the choice made in the constructor.
- Parameters:
- mktdatapandas.DataFrame
Historic daily market data for portfolio components in the format returned by azapy.mktData function.
- colnamestr, optional
Name of the price column from mktdata used in the weight’s calibration. The default is ‘adjusted’.
- freqstr, optional
Rate of return horizon. It could be ‘Q’ for a quarter or ‘M’ for a month. The default is ‘Q’.
- hlengthfloat, optional
History length in number of years used for calibration. A fractional number will be rounded to an integer number of months. The default is 3.25.
- pcloseBoolean, optional
True : assumes mktdata contains closing prices only, with columns the asset symbols and indexed by the observation dates,
False : assumes mktdata is in the usual format returned by azapy.mktData function.
- Returns:
- None
- set_random_seed(seed=42)
Sets the seed for Dirichlet random generator used in viewFrontiers to select the random inefficient portfolios.
- Parameters:
- seedint, optional
The random generator seed, in case you want to set it to a weird value other than 42 :). The default is 42.
- Returns:
- None
- set_rrate(rrate)
Sets portfolio components historical rates of return. It will overwrite the value computed by the constructor from mktdata.
- Parameters:
- rratepandas.DataFrame
Portfolio components historical rates of return. The columns are asset symbols and indexed by observation dates.
- Returns:
- None
- set_rtype(rtype=None, mu=None, d=1, mu0=0.0, aversion=None, ww0=None)
Sets the optimization type. It will overwrite the value set in the constructor.
- Parameters:
- rtypestr, optional
Optimization type. Possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
The default is ‘Sharpe’.
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- Returns:
- None
- viewFrontiers(minrisk=True, efficient=20, inefficient=20, sharpe=True, musharpe=0.0, maxdiverse=False, diverse_efficient=0, diverse_inefficient=0, invN=True, invNrisk=True, invNdiverse=False, invNdrr=False, component=True, randomport=20, addport=None, fig_type='RR_risk', **opt)
Computes the elements of the portfolio frontiers.
- Parameters:
- minriskBoolean, optional
If it is True then the minimum risk portfolio will be visible. The default is True.
- efficientint, optional
Number of points along the efficient risk frontier (equally spaced along the rate of return axis). The default is 20.
- inefficientint, optional
Number of points along the inefficient risk frontier (equally spaced along the rate of returns axis). The default is 20.
- sharpeBoolean, optional
If it is True then the maximum Sharpe portfolio will be visible. The default is True.
- musharpefloat, optional
Risk-free rate value used in the evaluation of generalized Sharpe ratio. The default is 0.
- maxdiverseBoolean, optional
If it is True then the maximum diversified portfolio will be visible. The default is True.
- diverse_efficientint, optional
Number of points along the efficient diversification frontier (equally spaced along the rate of return axis). The default is 20.
- diverse_inefficientint, optional
Number of points along the inefficient diversification frontier (equally spaced along the rate of return axis). The default is 20.
- invNBoolean, optional
If it is True, then the equal weighted portfolio and the optimal portfolio with the same risk value are added to the plot. The default is True.
- invNriskBoolean, optional
If it is True, then the efficient risk portfolio with same risk as equal weighted portfolio is added to the plot. The default is False.
- invNdiverseBoolean, optional
If it is True, then the efficient diversified portfolio with the same diversification factor as the equal weighted portfolio is added to the plot. The default is False.
- invNdrrBoolean, optional
If it is True, then the efficient diversified portfolio with the same expected rate of return as the equal weighted portfolio is added to the plot. The default value is False.
- componentBoolean, optional
If it is True, then the single component portfolios are added to the plot. The default is True.
- randomportint, optional
Number of portfolios with random weights (inefficient) to be added to the plot (for reference). The default is 20.
- addportdict or pandas.DataFrame, optional
The weights of additional portfolio to be added to the plot. If it is a dict then the keys are the labels, and the values are list of weights in the order of rrate.columns. If it is a pandas.DataFrame the index are the labels, and each row is a set of weights. The columns names should match the symbols names. The default is None.
- fig_typestr, optional
Graphical representation format.
‘RR_risk’ : expected rate of return vs risk
‘Sharpe_RR’ : sharpe vs expected rate of return
‘Diverse_RR’ : diversification vs expected rate of return
The default is ‘RR_risk’.
- **optoptional
Additional parameters:
- ‘title’str
The default is ‘Portfolio frontiers’.
- ‘xlabel’str
The default is
‘risk’ if fig_type=’RR_risk’,
‘rate of returns’ otherwise.
- ‘ylabel’str
The default is
‘rate of returns’ if fig_type=’RR_risk’
‘sharpe’ if fig_type=’Sharpe_RR’
‘diversification’ if fig_type=diverse_RR
- ‘tangent’Boolean
If set to True, then the tangent (to max sharpe point) is added. It has effect only if fig_type=’RR_risk’. The default is True.
- savetostr
File name to save the figure. The extension dictates the format: png, pdf, svg, etc. For more details see the mathplotlib documentation for savefig. The default is None.
- datadefaultdict
Numerical data to construct the plot. If it is not None, then it will take precedence and no other numerical evaluations will be performed. It is meant to produce different plot representations without reevaluations. The default is None.
- invN_labelstr
The label for equal weighted portfolio. The default is ‘1/N’.
- invNrisk_labelstr
The lable for efficient portfolio with same risk as equal weighted portfolio. The default is invNrisk.
- invNdiverse_labelstr
The label for diverse-efficient portfolio with the same diversificeation factor as equal weighted porfolio. The default is ‘invNdiv’.
- invNdrr_labelstr
The label of diverse-efficient portfolio with the same expected rate of return as equal weighted portolio. The defualt is ‘invNdrr’.
- maxdiverse_labelstr
The label of maximum diverified portfolio. The default is ‘MaxD’.
- minrisk_label‘str’
The label of minimum risk portfolio. The default is ‘MinR’.
- sharpe_labelstr
The label of maximum Sharpe portfolio. The default is ‘Sharpe’.
- Returns:
- `dict`Numerical data used to make the plots. It can be passed back
- to reconstruct the plots without reevaluations.
azapy.Analyzers.SDAnalyzer module¶
- class azapy.Analyzers.SDAnalyzer.SDAnalyzer(mktdata=None, colname='adjusted', freq='Q', hlength=3.25, name='SD', rtype='Sharpe', mu=None, d=1, mu0=0.0, aversion=None, ww0=None, method='ecos')
Bases:
_RiskAnalyzer
SD (Standard Deviation) based optimal portfolio strategies.
- Attributes
status : int - the computation status (0 - success, any other value signifies an error)
ww : pandas.Series - the portfolio weights
RR : float - portfolio rate of return
risk : float - portfolio SD risk
primary_risk_comp : list - redundant (single element list containing SD risk value)
secondary_risk_comp : list - redundant (same as primary_risk_comp)
sharpe : float - Sharpe ration if rtype is set to ‘Shapre’ or ‘Sharpe2’ otherwise None.
diverse : float - diversification factor if rtype is set to ‘Divers’ or ‘MaxDivers’ otherwise None.
name : str - portfolio name
- Note the following 2 important methods:
getWeights : Computes the optimal portfolio weights. During its computations the following class members are also set: risk, primery_risk_comp, secondary_risk_comp, sharpe, RR, divers.
getPositions : Provides practical information regarding the portfolio rebalancing delta positions and costs.
Methods
getDiversification
(ww[, rrate])Returns the value of the diversification factor for a give portfolio.
getPositions
([nshares, cash, ww, verbose])Computes the rebalanced number of shares.
getRisk
(ww[, rrate])Returns the value of the dispersion (risk) measure for a give portfolio.
Returns the risk of each portfolio component.
getWeights
([rtype, mu, d, mu0, aversion, ...])Computes the optimal portfolio weights.
set_method
(method)Sets computation method.
set_mktdata
(mktdata[, colname, freq, ...])Sets historical market data.
set_random_seed
([seed])Sets the seed for Dirichlet random generator used in viewFrontiers to select the random inefficient portfolios.
set_rrate
(rrate)Sets portfolio components historical rates of return.
set_rtype
([rtype, mu, d, mu0, aversion, ww0])Sets the optimization type.
viewFrontiers
([minrisk, efficient, ...])Computes the elements of the portfolio frontiers.
- __init__(mktdata=None, colname='adjusted', freq='Q', hlength=3.25, name='SD', rtype='Sharpe', mu=None, d=1, mu0=0.0, aversion=None, ww0=None, method='ecos')
Constructor
- Parameters:
- mktdatapandas.DataFrame, optional
Historic daily market data for portfolio components in the format returned by azapy.mktData function. The default is None.
- colnamestr, optional
Name of the price column from mktdata used in the weight’s calibration. The default is ‘adjusted’.
- freqstr, optional
Rate of return horizon. It could be ‘Q’ for a quarter or ‘M’ for a month. The default is ‘Q’.
- hlengthfloat, optional
History length in number of years used for calibration. A fractional number will be rounded to an integer number of months. The default is 3.25 years.
- namestr, optional
Portfolio name. The default is ‘SD’.
- rtypestr, optional
Optimization type. Possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
The default is ‘Sharpe’.
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- methodstr, optional
Quadratic programming numerical method. Could be ‘ecos’ or ‘cvxopt’. The default is ‘ecos’.
- Returns:
- The object.
- getDiversification(ww, rrate=None)
Returns the value of the diversification factor for a give portfolio.
- Parameters:
- wwlist, numpy.array or pandas.Series;
Portfolio weights. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >=0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (not necessarily in the same order).
- rratepandas.DataFrame, optional
Contains the portfolio components historical rates of return. If it is not None then it will overwrite the rates of return computed in the constructor from mktdata. The default is None.
- Returns:
- `float`The diversification value.
- getPositions(nshares=None, cash=0, ww=None, verbose=True)
Computes the rebalanced number of shares.
- Parameters:
- nsharespanda.Series, optional
Initial number of shares per portfolio component. A missing component entry will be considered 0. A None value assumes that all components entries are 0. The name of the components must be present in the mrkdata. The default is None.
- cashfloat, optional
Additional cash to be added to the capital. A negative entry assumes a reduction in the total capital available for rebalance. The total capital cannot be < 0. The default is 0.
- wwpanda.Series, optional
External overwrite portfolio weights. If it not set to None these weights will overwrite the calibration results. The default is None.
- verboseBoolean, optional
Is it set to True the function prints the closing prices date. The default is True.
- Returns:
- `pandas.DataFrame`the rolling information.
- Columns:
- ‘old_nsh’ :
initial number of shares per portfolio component and the additional cash. These are input values.
- ‘new_nsh’ :
the new number of shares per component plus the residual cash (due to the rounding to an integer number of shares). A negative entry means that the investor needs to add more cash to cover for the roundup shortfall. It has a small value.
- ‘diff_nsh’ :
number of shares (buy/sale) needed to rebalance the portfolio.
- ‘weights’ :
portfolio weights used for rebalancing. The cash entry is the new portfolio value (invested capital).
- ‘prices’ :
the share prices used for rebalances evaluations.
Note: Since the prices are closing prices, the rebalance can be computed after the market close and before the trading execution (next day). Additional cash slippage may occur due to share price differential between the previous day closing and execution time.
- getRisk(ww, rrate=None)
Returns the value of the dispersion (risk) measure for a give portfolio.
- Parameters:
- wwlist, numpy.array or pandas.Series
Portfolio weights. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >=0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series than the index should be compatible with the rrate.columns or mktdata symbols (not necessarily in the same order).
- rratepandas.DataFrame, optional
Contains the portfolio components historical rates of return. If it is not None, it will overwrite the rates of return computed in the constructor from mktdata. The default is None.
- Returns:
- `float`The dispersion (risk) measure value.
- getRiskComp()
Returns the risk of each portfolio component.
- Returns:
- `pandas.Series`risk per symbol.
- getWeights(rtype=None, mu=None, d=1, mu0=0.0, aversion=None, ww0=None, mktdata=None, **params)
Computes the optimal portfolio weights.
- Parameters:
- rtypestr, optional
Optimization type. If is not None it will overwrite the value set by the constructor. The default is None. Other possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- mktdatapandas.DataFrame, optional
The portfolio components historical, prices or rates of return, see ‘pclose’ definition below. If it is not None, it will overwrite the set of historical rates of return computed in the constructor from ‘mktdata’. The default is None.
- **paramsother optional parameters
Most common:
- verboseBoolean, optional
If it set to True, then it will print a message when the optimal portfolio degenerates to a single asset. The default is False.
- pcloseBoolean, optional
If it is absent then the mktdata is considered to contain rates of return, with columns the asset symbols and indexed by the observation dates,
True : assumes mktdata contains closing prices only, with columns the asset symbols and indexed by the observation dates,
False : assumes mktdata is in the usual format returned by azapy.mktData function.
- Returns:
- `pandas.Series`portfolio weights per symbol.
- set_method(method)
Sets computation method.
- Parameters:
- methodstr;
Must be a valid method name. It will overwrite the value set by the constructor.
- Returns:
- None
- set_mktdata(mktdata, colname=None, freq=None, hlength=None, pclose=False)
Sets historical market data. It will overwrite the choice made in the constructor.
- Parameters:
- mktdatapandas.DataFrame
Historic daily market data for portfolio components in the format returned by azapy.mktData function.
- colnamestr, optional
Name of the price column from mktdata used in the weight’s calibration. The default is ‘adjusted’.
- freqstr, optional
Rate of return horizon. It could be ‘Q’ for a quarter or ‘M’ for a month. The default is ‘Q’.
- hlengthfloat, optional
History length in number of years used for calibration. A fractional number will be rounded to an integer number of months. The default is 3.25.
- pcloseBoolean, optional
True : assumes mktdata contains closing prices only, with columns the asset symbols and indexed by the observation dates,
False : assumes mktdata is in the usual format returned by azapy.mktData function.
- Returns:
- None
- set_random_seed(seed=42)
Sets the seed for Dirichlet random generator used in viewFrontiers to select the random inefficient portfolios.
- Parameters:
- seedint, optional
The random generator seed, in case you want to set it to a weird value other than 42 :). The default is 42.
- Returns:
- None
- set_rrate(rrate)
Sets portfolio components historical rates of return. It will overwrite the value computed by the constructor from mktdata.
- Parameters:
- rratepandas.DataFrame
Portfolio components historical rates of return. The columns are asset symbols and indexed by observation dates.
- Returns:
- None
- set_rtype(rtype=None, mu=None, d=1, mu0=0.0, aversion=None, ww0=None)
Sets the optimization type. It will overwrite the value set in the constructor.
- Parameters:
- rtypestr, optional
Optimization type. Possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
The default is ‘Sharpe’.
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- Returns:
- None
- viewFrontiers(minrisk=True, efficient=20, inefficient=20, sharpe=True, musharpe=0.0, maxdiverse=False, diverse_efficient=0, diverse_inefficient=0, invN=True, invNrisk=True, invNdiverse=False, invNdrr=False, component=True, randomport=20, addport=None, fig_type='RR_risk', **opt)
Computes the elements of the portfolio frontiers.
- Parameters:
- minriskBoolean, optional
If it is True then the minimum risk portfolio will be visible. The default is True.
- efficientint, optional
Number of points along the efficient risk frontier (equally spaced along the rate of return axis). The default is 20.
- inefficientint, optional
Number of points along the inefficient risk frontier (equally spaced along the rate of returns axis). The default is 20.
- sharpeBoolean, optional
If it is True then the maximum Sharpe portfolio will be visible. The default is True.
- musharpefloat, optional
Risk-free rate value used in the evaluation of generalized Sharpe ratio. The default is 0.
- maxdiverseBoolean, optional
If it is True then the maximum diversified portfolio will be visible. The default is True.
- diverse_efficientint, optional
Number of points along the efficient diversification frontier (equally spaced along the rate of return axis). The default is 20.
- diverse_inefficientint, optional
Number of points along the inefficient diversification frontier (equally spaced along the rate of return axis). The default is 20.
- invNBoolean, optional
If it is True, then the equal weighted portfolio and the optimal portfolio with the same risk value are added to the plot. The default is True.
- invNriskBoolean, optional
If it is True, then the efficient risk portfolio with same risk as equal weighted portfolio is added to the plot. The default is False.
- invNdiverseBoolean, optional
If it is True, then the efficient diversified portfolio with the same diversification factor as the equal weighted portfolio is added to the plot. The default is False.
- invNdrrBoolean, optional
If it is True, then the efficient diversified portfolio with the same expected rate of return as the equal weighted portfolio is added to the plot. The default value is False.
- componentBoolean, optional
If it is True, then the single component portfolios are added to the plot. The default is True.
- randomportint, optional
Number of portfolios with random weights (inefficient) to be added to the plot (for reference). The default is 20.
- addportdict or pandas.DataFrame, optional
The weights of additional portfolio to be added to the plot. If it is a dict then the keys are the labels, and the values are list of weights in the order of rrate.columns. If it is a pandas.DataFrame the index are the labels, and each row is a set of weights. The columns names should match the symbols names. The default is None.
- fig_typestr, optional
Graphical representation format.
‘RR_risk’ : expected rate of return vs risk
‘Sharpe_RR’ : sharpe vs expected rate of return
‘Diverse_RR’ : diversification vs expected rate of return
The default is ‘RR_risk’.
- **optoptional
Additional parameters:
- ‘title’str
The default is ‘Portfolio frontiers’.
- ‘xlabel’str
The default is
‘risk’ if fig_type=’RR_risk’,
‘rate of returns’ otherwise.
- ‘ylabel’str
The default is
‘rate of returns’ if fig_type=’RR_risk’
‘sharpe’ if fig_type=’Sharpe_RR’
‘diversification’ if fig_type=diverse_RR
- ‘tangent’Boolean
If set to True, then the tangent (to max sharpe point) is added. It has effect only if fig_type=’RR_risk’. The default is True.
- savetostr
File name to save the figure. The extension dictates the format: png, pdf, svg, etc. For more details see the mathplotlib documentation for savefig. The default is None.
- datadefaultdict
Numerical data to construct the plot. If it is not None, then it will take precedence and no other numerical evaluations will be performed. It is meant to produce different plot representations without reevaluations. The default is None.
- invN_labelstr
The label for equal weighted portfolio. The default is ‘1/N’.
- invNrisk_labelstr
The lable for efficient portfolio with same risk as equal weighted portfolio. The default is invNrisk.
- invNdiverse_labelstr
The label for diverse-efficient portfolio with the same diversificeation factor as equal weighted porfolio. The default is ‘invNdiv’.
- invNdrr_labelstr
The label of diverse-efficient portfolio with the same expected rate of return as equal weighted portolio. The defualt is ‘invNdrr’.
- maxdiverse_labelstr
The label of maximum diverified portfolio. The default is ‘MaxD’.
- minrisk_label‘str’
The label of minimum risk portfolio. The default is ‘MinR’.
- sharpe_labelstr
The label of maximum Sharpe portfolio. The default is ‘Sharpe’.
- Returns:
- `dict`Numerical data used to make the plots. It can be passed back
- to reconstruct the plots without reevaluations.
azapy.Analyzers.SMCRAnalyzer module¶
- class azapy.Analyzers.SMCRAnalyzer.SMCRAnalyzer(alpha=[0.9], coef=None, mktdata=None, colname='adjusted', freq='Q', hlength=3.25, name='SMCR', rtype='Sharpe', mu=None, d=1, mu0=0.0, aversion=None, ww0=None, method='ecos')
Bases:
CVaRAnalyzer
Mixture SMCR (Second Momentum Coherent Risk) based optimal portfolio strategies.
- Attributes
status : int - the computation status (0 - success, any other value signifies an error)
ww : pandas.Series - the portfolio weights
RR : float - portfolio rate of return
risk : float - portfolio mSMCR risk
primary_risk_comp : list - SMCR components of portfolio mSMCR
secondary_risk_comp : list - SMVaR values associated with SMCR components
sharpe : float - mSMCR-Sharpe ration if rtype is set to ‘Shapre’ or ‘Sharpe2’ otherwise None.
diverse : float - diversification factor if rtype is set to ‘Divers’ or ‘MaxDivers’ otherwise None.
name : str - portfolio name
- Note the following 2 important methods:
getWeights : Computes the optimal portfolio weights. During its computations the following class members are also set: risk, primery_risk_comp, secondary_risk_comp, sharpe, RR, divers.
getPositions : Provides practical information regarding the portfolio rebalancing delta positions and costs.
Methods
getDiversification
(ww[, rrate])Returns the value of the diversification factor for a give portfolio.
getPositions
([nshares, cash, ww, verbose])Computes the rebalanced number of shares.
getRisk
(ww[, rrate])Returns the value of the dispersion (risk) measure for a give portfolio.
Returns the risk of each portfolio component.
getWeights
([rtype, mu, d, mu0, aversion, ...])Computes the optimal portfolio weights.
set_method
(method)Sets computation method.
set_mktdata
(mktdata[, colname, freq, ...])Sets historical market data.
set_random_seed
([seed])Sets the seed for Dirichlet random generator used in viewFrontiers to select the random inefficient portfolios.
set_rrate
(rrate)Sets portfolio components historical rates of return.
set_rtype
([rtype, mu, d, mu0, aversion, ww0])Sets the optimization type.
viewFrontiers
([minrisk, efficient, ...])Computes the elements of the portfolio frontiers.
- __init__(alpha=[0.9], coef=None, mktdata=None, colname='adjusted', freq='Q', hlength=3.25, name='SMCR', rtype='Sharpe', mu=None, d=1, mu0=0.0, aversion=None, ww0=None, method='ecos')
Constructor
- Parameters:
- alphalist, optional
List of distinct confidence levels. The default is [0.975].
- coeflist, optional
List of positive mixture coefficients. Must be the same size as alpha. A None value assumes an equal weighted risk mixture. The vector of coefficients will be normalized to unit. The default is None.
- mktdatapandas.DataFrame, optional
Historic daily market data for portfolio components in the format returned by azapy.mktData function. The default is None.
- colnamestr, optional
Name of the price column from mktdata used in the weight’s calibration. The default is ‘adjusted’.
- freqstr, optional
Rate of return horizon. It could be ‘Q’ for a quarter or ‘M’ for a month. The default is ‘Q’.
- hlengthfloat, optional
History length in number of years used for calibration. A fractional number will be rounded to an integer number of months. The default is 3.25 years.
- namestr, optional
Portfolio name. The default is ‘SMCR’.
- rtypestr, optional
Optimization type. Possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
The default is ‘Sharpe’.
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- methodstr, optional
SOCP numerical method. Could be: ‘ecos’ or ‘cvxopt’. The defualt is ‘ecos’.
- Returns:
- The object.
- getDiversification(ww, rrate=None)
Returns the value of the diversification factor for a give portfolio.
- Parameters:
- wwlist, numpy.array or pandas.Series;
Portfolio weights. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >=0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (not necessarily in the same order).
- rratepandas.DataFrame, optional
Contains the portfolio components historical rates of return. If it is not None then it will overwrite the rates of return computed in the constructor from mktdata. The default is None.
- Returns:
- `float`The diversification value.
- getPositions(nshares=None, cash=0, ww=None, verbose=True)
Computes the rebalanced number of shares.
- Parameters:
- nsharespanda.Series, optional
Initial number of shares per portfolio component. A missing component entry will be considered 0. A None value assumes that all components entries are 0. The name of the components must be present in the mrkdata. The default is None.
- cashfloat, optional
Additional cash to be added to the capital. A negative entry assumes a reduction in the total capital available for rebalance. The total capital cannot be < 0. The default is 0.
- wwpanda.Series, optional
External overwrite portfolio weights. If it not set to None these weights will overwrite the calibration results. The default is None.
- verboseBoolean, optional
Is it set to True the function prints the closing prices date. The default is True.
- Returns:
- `pandas.DataFrame`the rolling information.
- Columns:
- ‘old_nsh’ :
initial number of shares per portfolio component and the additional cash. These are input values.
- ‘new_nsh’ :
the new number of shares per component plus the residual cash (due to the rounding to an integer number of shares). A negative entry means that the investor needs to add more cash to cover for the roundup shortfall. It has a small value.
- ‘diff_nsh’ :
number of shares (buy/sale) needed to rebalance the portfolio.
- ‘weights’ :
portfolio weights used for rebalancing. The cash entry is the new portfolio value (invested capital).
- ‘prices’ :
the share prices used for rebalances evaluations.
Note: Since the prices are closing prices, the rebalance can be computed after the market close and before the trading execution (next day). Additional cash slippage may occur due to share price differential between the previous day closing and execution time.
- getRisk(ww, rrate=None)
Returns the value of the dispersion (risk) measure for a give portfolio.
- Parameters:
- wwlist, numpy.array or pandas.Series
Portfolio weights. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >=0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series than the index should be compatible with the rrate.columns or mktdata symbols (not necessarily in the same order).
- rratepandas.DataFrame, optional
Contains the portfolio components historical rates of return. If it is not None, it will overwrite the rates of return computed in the constructor from mktdata. The default is None.
- Returns:
- `float`The dispersion (risk) measure value.
- getRiskComp()
Returns the risk of each portfolio component.
- Returns:
- `pandas.Series`risk per symbol.
- getWeights(rtype=None, mu=None, d=1, mu0=0.0, aversion=None, ww0=None, mktdata=None, **params)
Computes the optimal portfolio weights.
- Parameters:
- rtypestr, optional
Optimization type. If is not None it will overwrite the value set by the constructor. The default is None. Other possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- mktdatapandas.DataFrame, optional
The portfolio components historical, prices or rates of return, see ‘pclose’ definition below. If it is not None, it will overwrite the set of historical rates of return computed in the constructor from ‘mktdata’. The default is None.
- **paramsother optional parameters
Most common:
- verboseBoolean, optional
If it set to True, then it will print a message when the optimal portfolio degenerates to a single asset. The default is False.
- pcloseBoolean, optional
If it is absent then the mktdata is considered to contain rates of return, with columns the asset symbols and indexed by the observation dates,
True : assumes mktdata contains closing prices only, with columns the asset symbols and indexed by the observation dates,
False : assumes mktdata is in the usual format returned by azapy.mktData function.
- Returns:
- `pandas.Series`portfolio weights per symbol.
- set_method(method)
Sets computation method.
- Parameters:
- methodstr;
Must be a valid method name. It will overwrite the value set by the constructor.
- Returns:
- None
- set_mktdata(mktdata, colname=None, freq=None, hlength=None, pclose=False)
Sets historical market data. It will overwrite the choice made in the constructor.
- Parameters:
- mktdatapandas.DataFrame
Historic daily market data for portfolio components in the format returned by azapy.mktData function.
- colnamestr, optional
Name of the price column from mktdata used in the weight’s calibration. The default is ‘adjusted’.
- freqstr, optional
Rate of return horizon. It could be ‘Q’ for a quarter or ‘M’ for a month. The default is ‘Q’.
- hlengthfloat, optional
History length in number of years used for calibration. A fractional number will be rounded to an integer number of months. The default is 3.25.
- pcloseBoolean, optional
True : assumes mktdata contains closing prices only, with columns the asset symbols and indexed by the observation dates,
False : assumes mktdata is in the usual format returned by azapy.mktData function.
- Returns:
- None
- set_random_seed(seed=42)
Sets the seed for Dirichlet random generator used in viewFrontiers to select the random inefficient portfolios.
- Parameters:
- seedint, optional
The random generator seed, in case you want to set it to a weird value other than 42 :). The default is 42.
- Returns:
- None
- set_rrate(rrate)
Sets portfolio components historical rates of return. It will overwrite the value computed by the constructor from mktdata.
- Parameters:
- rratepandas.DataFrame
Portfolio components historical rates of return. The columns are asset symbols and indexed by observation dates.
- Returns:
- None
- set_rtype(rtype=None, mu=None, d=1, mu0=0.0, aversion=None, ww0=None)
Sets the optimization type. It will overwrite the value set in the constructor.
- Parameters:
- rtypestr, optional
Optimization type. Possible values:
‘Risk’ : optimal risk portfolio for targeted expected rate of return.
‘Sharpe’ : optimal Sharpe portfolio - maximization solution.
‘Sharpe2’ : optimal Sharpe portfolio - minimization solution.
‘MinRisk’ : minimum risk portfolio.
‘RiskAverse’ : optimal risk portfolio for a fixed risk-aversion factor.
‘InvNrisk’ : optimal risk portfolio with the same risk value as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘Diverse’ : optimal diversified portfolio for targeted expected rate of return (max of inverse 1-Diverse).
‘Diverse2’ : optimal diversified portfolio for targeted expected rate of return (min of 1-Diverse).
‘MaxDiverse’ : maximum diversified portfolio.
‘InvNdiverse’ : optimal diversified portfolio with the same diversification factor as a benchmark portfolio (e.g., same as equal weighted portfolio).
‘InvNdrr’ : optimal diversified portfolio with the same expected rate of return as a benchmark portfolio (e.g., same as equal weighted portfolio).
The default is ‘Sharpe’.
- mufloat, optional
Targeted portfolio expected rate of return. Relevant only if rtype=’Risk’ or rtype=’Divers’. The default is None.
- dint, optional
Frontier type. Active only if rtype=’Risk’. A value of 1 will trigger the evaluation of optimal portfolio along the efficient frontier. Otherwise, it will find the portfolio with the lowest rate of return along the inefficient portfolio frontier. The default is 1.
- mu0float, optional
Risk-free rate accessible to the investor. Relevant only if rtype=’Sharpe’ or rtype=’Sharpe2’. The default is 0.
- aversionfloat, optional
The value of the risk-aversion coefficient. Must be positive. Relevant only if rtype=’RiskAverse’. The default is None.
- ww0list, numpy.array or pandas.Series, optional
Targeted portfolio weights. Relevant only if rtype=’InvNrisk’. Its length must be equal to the number of symbols in rrate (mktdata). All weights must be >= 0 with sum > 0. If it is a list or a numpy.array then the weights are assumed to be in order of rrate.columns. If it is a pandas.Series then the index should be compatible with the rrate.columns or mktdata symbols (same symbols, not necessarily in the same order). If it is None then it will be set to equal weights. The default is None.
- Returns:
- None
- viewFrontiers(minrisk=True, efficient=20, inefficient=20, sharpe=True, musharpe=0.0, maxdiverse=False, diverse_efficient=0, diverse_inefficient=0, invN=True, invNrisk=True, invNdiverse=False, invNdrr=False, component=True, randomport=20, addport=None, fig_type='RR_risk', **opt)
Computes the elements of the portfolio frontiers.
- Parameters:
- minriskBoolean, optional
If it is True then the minimum risk portfolio will be visible. The default is True.
- efficientint, optional
Number of points along the efficient risk frontier (equally spaced along the rate of return axis). The default is 20.
- inefficientint, optional
Number of points along the inefficient risk frontier (equally spaced along the rate of returns axis). The default is 20.
- sharpeBoolean, optional
If it is True then the maximum Sharpe portfolio will be visible. The default is True.
- musharpefloat, optional
Risk-free rate value used in the evaluation of generalized Sharpe ratio. The default is 0.
- maxdiverseBoolean, optional
If it is True then the maximum diversified portfolio will be visible. The default is True.
- diverse_efficientint, optional
Number of points along the efficient diversification frontier (equally spaced along the rate of return axis). The default is 20.
- diverse_inefficientint, optional
Number of points along the inefficient diversification frontier (equally spaced along the rate of return axis). The default is 20.
- invNBoolean, optional
If it is True, then the equal weighted portfolio and the optimal portfolio with the same risk value are added to the plot. The default is True.
- invNriskBoolean, optional
If it is True, then the efficient risk portfolio with same risk as equal weighted portfolio is added to the plot. The default is False.
- invNdiverseBoolean, optional
If it is True, then the efficient diversified portfolio with the same diversification factor as the equal weighted portfolio is added to the plot. The default is False.
- invNdrrBoolean, optional
If it is True, then the efficient diversified portfolio with the same expected rate of return as the equal weighted portfolio is added to the plot. The default value is False.
- componentBoolean, optional
If it is True, then the single component portfolios are added to the plot. The default is True.
- randomportint, optional
Number of portfolios with random weights (inefficient) to be added to the plot (for reference). The default is 20.
- addportdict or pandas.DataFrame, optional
The weights of additional portfolio to be added to the plot. If it is a dict then the keys are the labels, and the values are list of weights in the order of rrate.columns. If it is a pandas.DataFrame the index are the labels, and each row is a set of weights. The columns names should match the symbols names. The default is None.
- fig_typestr, optional
Graphical representation format.
‘RR_risk’ : expected rate of return vs risk
‘Sharpe_RR’ : sharpe vs expected rate of return
‘Diverse_RR’ : diversification vs expected rate of return
The default is ‘RR_risk’.
- **optoptional
Additional parameters:
- ‘title’str
The default is ‘Portfolio frontiers’.
- ‘xlabel’str
The default is
‘risk’ if fig_type=’RR_risk’,
‘rate of returns’ otherwise.
- ‘ylabel’str
The default is
‘rate of returns’ if fig_type=’RR_risk’
‘sharpe’ if fig_type=’Sharpe_RR’
‘diversification’ if fig_type=diverse_RR
- ‘tangent’Boolean
If set to True, then the tangent (to max sharpe point) is added. It has effect only if fig_type=’RR_risk’. The default is True.
- savetostr
File name to save the figure. The extension dictates the format: png, pdf, svg, etc. For more details see the mathplotlib documentation for savefig. The default is None.
- datadefaultdict
Numerical data to construct the plot. If it is not None, then it will take precedence and no other numerical evaluations will be performed. It is meant to produce different plot representations without reevaluations. The default is None.
- invN_labelstr
The label for equal weighted portfolio. The default is ‘1/N’.
- invNrisk_labelstr
The lable for efficient portfolio with same risk as equal weighted portfolio. The default is invNrisk.
- invNdiverse_labelstr
The label for diverse-efficient portfolio with the same diversificeation factor as equal weighted porfolio. The default is ‘invNdiv’.
- invNdrr_labelstr
The label of diverse-efficient portfolio with the same expected rate of return as equal weighted portolio. The defualt is ‘invNdrr’.
- maxdiverse_labelstr
The label of maximum diverified portfolio. The default is ‘MaxD’.
- minrisk_label‘str’
The label of minimum risk portfolio. The default is ‘MinR’.
- sharpe_labelstr
The label of maximum Sharpe portfolio. The default is ‘Sharpe’.
- Returns:
- `dict`Numerical data used to make the plots. It can be passed back
- to reconstruct the plots without reevaluations.