azapy.Engines package¶
Submodules¶
azapy.Engines.ConstWEngine module¶
- class azapy.Engines.ConstWEngine.ConstWEngine(ww=None, name=None)
Bases:
object
Constant weighted portfolio.
- Attributes
status : int - computation status (0 - success, any other value indicates an error)
ww : pandas.Series - portfolio weights
name : str - portfolio name
Methods
getWeights
(mktdata, **params)Returns the portfolio weights adjusted to mktdata.
set_mktdata
(*dummy1, **dummy2)Dummy function provided for compatibility with other weights generating (optimizer) classes.
- __init__(ww=None, name=None)
Constant Weighted Portfolio.
- Parameters:
- wwpandas.Series
Portfolio weights (per symbol). If it is None the Equal Weighted Portfolio (EWP) will be considered. The default is None.
- namestr, optional
Portfolio name. The default value is None.
- Returns:
- The object.
- getWeights(mktdata, **params)
Returns the portfolio weights adjusted to mktdata.
Note: the symbols from mktdata take precedents. If ww was set to None (i.e., EWP) then the weights will be set to 1/n, where n is the number symbols in the mktdata. Otherwise, ww will be reduced to the symbols included in mktdata and normalized to unit.
- Parameters:
- mktdatapandas.DataFrame, optional
The portfolio components historical, prices or rates of return, see`’pclose’` definition below. The default is None.
Note: in this call only the values of the symbols are relevant.
- **params: other optional parameters
- 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`with portfolio weights.
- set_mktdata(*dummy1, **dummy2)
Dummy function provided for compatibility with other weights generating (optimizer) classes.
- Returns:
- 0
azapy.Engines.InvDDEngine module¶
- class azapy.Engines.InvDDEngine.InvDDEngine(mktdata=None, colname='adjusted', freq='Q', hlength=3.25, name=None, verbose=False)
Bases:
InvVolEngine
Inverse maximum drawdown portfolio.
- Attributes
status : int - computation status (0 - success, any other value indicates an error)
ww : pandas.Series - portfolio weights
name : str - portfolio name
Methods
getPositions
([nshares, cash, ww, nsh_round, ...])Computes the rebalanced number of shares.
getWeights
([mktdata])Computes the optimal portfolio weights.
set_mktdata
(mktdata[, colname, freq, ...])Sets historical market data.
set_rrate
(rrate)Sets portfolio components historical rates of return in the format "date", "symbol1", "symbol2", etc.
- __init__(mktdata=None, colname='adjusted', freq='Q', hlength=3.25, name=None, verbose=False)
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 weights 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. Default value is None
- verboseBoolean, optional
If it is set to True, then computational info (meant as warnings) are printed. The default is False.
- Returns:
- The object.
- getPositions(nshares=None, cash=0.0, ww=None, nsh_round=True, 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.
- nsh_roundBoolean, optional
If it is True the invested numbers of shares are round to the nearest integer and the residual cash capital (positive or negative) is carried to the next reinvestment cycle. A value of False assumes investments with fractional number of shares (no rounding). The default is True.
- 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 rebalance 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.
- getWeights(mktdata=None, **params)
Computes the optimal portfolio weights.
- Parameters:
- 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 is set to True, then it will print a computation messages. 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.
- set_mktdata(mktdata, colname='adjusted', 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_rrate(rrate)
Sets portfolio components historical rates of return in the format “date”, “symbol1”, “symbol2”, etc.
- Parameters:
- rratepandas.DataFrame
The portfolio components historical rates of return. If it is not None, it will overwrite the rrate computed in the constructor from mktdata. The default is None.
- Returns:
- None
azapy.Engines.InvVarEngine module¶
- class azapy.Engines.InvVarEngine.InvVarEngine(mktdata=None, colname='adjusted', freq='Q', hlength=3.25, name=None, verbose=False)
Bases:
InvVolEngine
Inverse variance portfolio.
- Attributes
status : int - computation status (0 - success, any other value indicates an error)
ww : pandas.Series - portfolio weights
name : str - portfolio name
Methods
getPositions
([nshares, cash, ww, nsh_round, ...])Computes the rebalanced number of shares.
getWeights
([mktdata])Computes the optimal portfolio weights.
set_mktdata
(mktdata[, colname, freq, ...])Sets historical market data.
set_rrate
(rrate)Sets portfolio components historical rates of return in the format "date", "symbol1", "symbol2", etc.
- __init__(mktdata=None, colname='adjusted', freq='Q', hlength=3.25, name=None, verbose=False)
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 weights 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. Default value is None
- verboseBoolean, optional
If it is set to True, then computational info (meant as warnings) are printed. The default is False.
- Returns:
- The object.
- getPositions(nshares=None, cash=0.0, ww=None, nsh_round=True, 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.
- nsh_roundBoolean, optional
If it is True the invested numbers of shares are round to the nearest integer and the residual cash capital (positive or negative) is carried to the next reinvestment cycle. A value of False assumes investments with fractional number of shares (no rounding). The default is True.
- 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 rebalance 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.
- getWeights(mktdata=None, **params)
Computes the optimal portfolio weights.
- Parameters:
- 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 is set to True, then it will print a computation messages. 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.
- set_mktdata(mktdata, colname='adjusted', 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_rrate(rrate)
Sets portfolio components historical rates of return in the format “date”, “symbol1”, “symbol2”, etc.
- Parameters:
- rratepandas.DataFrame
The portfolio components historical rates of return. If it is not None, it will overwrite the rrate computed in the constructor from mktdata. The default is None.
- Returns:
- None
azapy.Engines.InvVolEngine module¶
- class azapy.Engines.InvVolEngine.InvVolEngine(mktdata=None, colname='adjusted', freq='Q', hlength=3.25, name=None, verbose=False)
Bases:
_RiskEngine
Inverse volatility portfolio.
- Attributes
status : int - computation status (0 - success, any other value indicates an error)
ww : pandas.Series - portfolio weights
name : str - portfolio name
Methods
getPositions
([nshares, cash, ww, nsh_round, ...])Computes the rebalanced number of shares.
getWeights
([mktdata])Computes the optimal portfolio weights.
set_mktdata
(mktdata[, colname, freq, ...])Sets historical market data.
set_rrate
(rrate)Sets portfolio components historical rates of return in the format "date", "symbol1", "symbol2", etc.
- __init__(mktdata=None, colname='adjusted', freq='Q', hlength=3.25, name=None, verbose=False)
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 weights 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. Default value is None
- verboseBoolean, optional
If it is set to True, then computational info (meant as warnings) are printed. The default is False.
- Returns:
- The object.
- getPositions(nshares=None, cash=0.0, ww=None, nsh_round=True, 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.
- nsh_roundBoolean, optional
If it is True the invested numbers of shares are round to the nearest integer and the residual cash capital (positive or negative) is carried to the next reinvestment cycle. A value of False assumes investments with fractional number of shares (no rounding). The default is True.
- 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 rebalance 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.
- getWeights(mktdata=None, **params)
Computes the optimal portfolio weights.
- Parameters:
- 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 is set to True, then it will print a computation messages. 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.
- set_mktdata(mktdata, colname='adjusted', 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_rrate(rrate)
Sets portfolio components historical rates of return in the format “date”, “symbol1”, “symbol2”, etc.
- Parameters:
- rratepandas.DataFrame
The portfolio components historical rates of return. If it is not None, it will overwrite the rrate computed in the constructor from mktdata. The default is None.
- Returns:
- None
azapy.Engines.KellyEngine module¶
- class azapy.Engines.KellyEngine.KellyEngine(mktdata=None, colname='adjusted', freq='Q', hlength=3.25, name='Kelly', rtype='ExpCone', method='ecos', verbose=False)
Bases:
_RiskEngine
Kelly optimal portfolio.
- Attributes
status : int - computation status (0 - success, any other value indicates an error)
ww : pandas.Series - portfolio weights
name : str - portfolio name
Methods
getPositions
([nshares, cash, ww, nsh_round, ...])Computes the rebalanced number of shares.
getWeights
([rtype, method, mktdata])Computes the Kelly optimal weights.
set_mktdata
(mktdata[, colname, freq, ...])Sets historical market data.
set_rrate
(rrate)Sets portfolio components historical rates of return in the format "date", "symbol1", "symbol2", etc.
set_rtype
(rtype)Sets the model approximation level.
- __init__(mktdata=None, colname='adjusted', freq='Q', hlength=3.25, name='Kelly', rtype='ExpCone', method='ecos', verbose=False)
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. Default value is ‘Kelly’.
- rtypestr, optional
Optimization approximation. It can be:
‘ExpCone’ - exponential cone constraint programming solver for original Kelly problem.
‘Full’ - non-linear solver for original Kelly problem.
‘Order2’ - second order Taylor approximation of original Kelly problem. It is a QP problem.
The default is ‘ecos’.
- methodstr, optional
The QP solver class. It is relevant only if rtype=’Order2’. It takes 2 values: ‘ecos’ or ‘cvxopt’. The default is ‘ecos’.
- verboseBoolean, optional
If it is set to True, then various computation messages (meant as warnings) will be printed. The default is False.
- Returns:
- The object.
- getPositions(nshares=None, cash=0.0, ww=None, nsh_round=True, 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.
- nsh_roundBoolean, optional
If it is True the invested numbers of shares are round to the nearest integer and the residual cash capital (positive or negative) is carried to the next reinvestment cycle. A value of False assumes investments with fractional number of shares (no rounding). The default is True.
- 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 rebalance 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.
- getWeights(rtype=None, method=None, mktdata=None, **params)
Computes the Kelly optimal weights.
- Parameters:
- rtypestr, optional
Optimization approximation. It can be:
‘ExpCone’ - exponential cone constraint programming solver for original Kelly problem.
‘Full’ - non-linear solver for original Kelly problem.
‘Order2’ - second order Taylor approximation of original Kelly problem. It is a QP problem.
A value different than None will overwrite the value for rtype set in the constructor.
The default is None.
- methodstr, optional
The QP solver class. It is relevant only if rtype=’Order2’. It takes 2 values: ‘ecos’ or ‘cvxopt’. A value different than None will overwrite the value set in the constructor. 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.readMkT function.
- Returns:
- `pandas.Series`Portfolio weights per symbol.
- set_mktdata(mktdata, colname='adjusted', 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_rrate(rrate)
Sets portfolio components historical rates of return in the format “date”, “symbol1”, “symbol2”, etc.
- Parameters:
- rratepandas.DataFrame
The portfolio components historical rates of return. If it is not None, it will overwrite the rrate computed in the constructor from mktdata. The default is None.
- Returns:
- None
- set_rtype(rtype)
Sets the model approximation level.
- Parameters:
- rtypestr
It could be:
‘Full’ for a non-linear (no approximation) model,
‘ExpCone’ for exponential cone constraint programming solver,
‘Order2’ for a second order Taylor approximation (a QP problem).
It will overwrite the value set by the constructor.
- Returns:
- None
azapy.Engines.UniveralEngine module¶
- class azapy.Engines.UniversalEngine.UniversalEngine(mktdata=None, colname='adjusted', freq='M', name='Universal', schedule=None, sdate=None, edate='today', noffset=0, fixoffset=0, hlength=12, dirichlet_alpha=None, variance_reduction=True, nr_batches=16, mc_paths=100, mc_seed=42, verbose=False)
Bases:
_RiskEngine
Cover’s (1996) Universal Portfolio
- Attributes
status : int - computation status (0 - success, any other value indicates an error)
ww : pandas.DataFrame - portfolio weights at each rebalancing date
name : str - portfolio name
Methods
Returns the BCWP (Best Constant Weighted Portfolio) weights.
getPositions
([nshares, cash, ww, nsh_round, ...])Computes the rebalanced number of shares.
getWeights
([mktdata, dirichlet_alpha, ...])Computes the portfolio weights for each fixing date.
set_mktdata
(mktdata[, colname, schedule, ...])Sets historical market data.
set_rrate
(rrate)Sets portfolio components historical rates of return in the format "date", "symbol1", "symbol2", etc.
- __init__(mktdata=None, colname='adjusted', freq='M', name='Universal', schedule=None, sdate=None, edate='today', noffset=0, fixoffset=0, hlength=12, dirichlet_alpha=None, variance_reduction=True, nr_batches=16, mc_paths=100, mc_seed=42, verbose=False)
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 ‘M’.
- namestr, optional
Portfolio name. The default value is ‘Universal’.
- scheduleazapy.schedule_simple, optional
External schedule of fixing dates. If it is None then the fixing schedule will be generated internally. The default is None.
- fixoffsetint, optional
Fixing date as number of business days offset relative to the rebalance date. Must be <=0. It is relevant only is schedule`=`None. The default is -1.
- hlengthfloat, optional
History length in number of years used for calibration. A fractional number will be rounded to an integer number of months. For this model, the value of hlength must be as large is possible given the market data length and computational resources. The default is 12 years.
- dirichlet_alphalist, optional
List of Dirichlet alpha coefficients (to be used by the Dirichlet random number generator). The length must be the same with the number of symbols in the portfolio. A possible example is alpha = [0.5] * n where n is the number of symbols in the portfolio. If alpha is set to None then a uniform generator in the n-simplex sum_{k=1}^n x_k = 1 with x_k >= 0 is assumed (it is equivalent to Dirichlet for alpha=[1] * n). The default is None.
- variance_reductionBoolean, optional
If it is set to True, then the antithetic variance reduction generated by the permutations of the portfolio components is deployed. The effective number of Monte Carlo simulations will be multiplied by the factorial of the number of symbols in the portfolio. The default is True.
- nr_batchespositive int, optional
The number of a Monte Carlo batches. Since the computation is multithreaded, a good value could be a multiple of the number of cores. The default is 16.
- mc_pathspositive int, optional
Number of simulations per Monte Carlo batch. If variance_reduction is set to True then the total number of simulation will be multiplied by M! where M is the number of portfolio components. For example, 7 assets (7! = 5040), 16 baches, of 100 paths will lead to 5040 * 16 * 100 = 8,064,000 numbers of MC simulation paths . The default is 100.
- mc_seednon negative int, optional
Random number generator seed. If it has a value other than None the random generator will be reseeded. The default value is 42.
- verboseBoolean, optional
If it is set to True, then various computation messages (meant as warnings) will be printed. The default is False.
- mc_seedint, optional
Random number generator seed. The default is 42.
- Returns:
- The object.
- benchmark()
Returns the BCWP (Best Constant Weighted Portfolio) weights.
- Returns:
- pandas.DataFrame
The BCWP weights. Each row represents the weights of a BCWP with maturity given by the index value.
- getPositions(nshares=None, cash=0.0, ww=None, nsh_round=True, 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.
- nsh_roundBoolean, optional
If it is True the invested numbers of shares are round to the nearest integer and the residual cash capital (positive or negative) is carried to the next reinvestment cycle. A value of False assumes investments with fractional number of shares (no rounding). The default is True.
- 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 rebalance 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.
- getWeights(mktdata=None, dirichlet_alpha=None, variance_reduction=None, nr_batches=None, mc_paths=None, mc_seed=None, finalonly=True, verbose=False)
Computes the portfolio weights for each fixing date. In the last entry (row) are the portfolio weights corresponding to the fixing_date.
- Parameters:
- 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.
- dirichlet_alphalist, optional
List of Dirichlet alpha coefficients (to be used by the Dirichlet random number generator). The length must be the same with the number of symbols in the portfolio. A possible example is alpha = [0.5] * n where n is the number of symbols in the portfolio. If alpha is set to None then a uniform generator in the n-simplex sum_{k=1}^n x_k = 1 with x_k >= 0 is assumed (it is equivalent to Dirichlet for alpha=[1] * n). The default is None.
- variance_reductionBoolean, optional
If it is set to True, then the antithetic variance reduction generated by the permutations of the portfolio components is deployed. The effective number of Monte Carlo simulations will be multiplied by the factorial of the number of symbols in the portfolio. The default is True.
- nr_batchespositive int, optional
The number of a Monte Carlo batches. Since the computation is multithreaded, a good value could be a multiple of the number of cores. The default is 16.
- mc_pathspositive int, optional
Number of simulations per Monte Carlo batch. If variance_reduction is set to True then the total number of simulation will be multiplied by M! where M is the number of portfolio components. For example, 7 assets (7! = 5040), 16 baches, of 100 paths will lead to 5040 * 16 * 100 = 8,064,000 numbers of MC simulation paths . The default is 100.
- mc_seednon negative int, optional
Random number generator seed. If it has a value other than None the random generator will be reseeded. The default value is None.
- finalonlyBoolean, optional
If it is False, the full schedule of weights is returned. Otherwise, only the prevailing weights are returned. The default is True.
- verboseBoolean, optional
If it is set to True, then various computation messages (meant as warnings) will be printed. The default is False.
- Returns:
- pandas.DataFrame
Portfolio weights for each fixing date. In the last row are the values corresponding to fixing_date.
Notes
If variance_reduction=True the total number of Monte Carlo simulations is mc_paths * nr_batches * M! where M is the number of portfolio components (symbols). For example, if mc_paths=10, mc_batches=16, and M=7 the total number of Monte Carlo simulations is 806,400. This feature should be used with care for portfolios with a relatively small number of component.
- set_mktdata(mktdata, colname=None, schedule=None, freq=None, sdate=None, edate=None, noffset=None, fixoffset=None, hlength=None)
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’.
- scheduleazapy.schedule_simple, optional
External schedule of fixing dates. If it is None then the schedule of fixing dates will be generated internally. The default is None.
- fixing_datestr date-like, optional
Most recent fixing date used as reference for building the schedule of fixing dates. Must be a valid past business day present in the mktdata. It is relevant only if schedule is not Nona. The default is None.
- freqstr, optional
Rate of return horizon. It could be ‘Q’ for a quarter or ‘M’ for a month. The default is ‘M’.
- Returns:
- None
- set_rrate(rrate)
Sets portfolio components historical rates of return in the format “date”, “symbol1”, “symbol2”, etc.
- Parameters:
- rratepandas.DataFrame
The portfolio components historical rates of return. If it is not None, it will overwrite the rrate computed in the constructor from mktdata. The default is None.
- Returns:
- None