diff -Nru fportfolio-3011.81/ChangeLog fportfolio-3042.83/ChangeLog --- fportfolio-3011.81/ChangeLog 2014-10-30 14:13:56.000000000 +0000 +++ fportfolio-3042.83/ChangeLog 2017-11-13 20:38:27.000000000 +0000 @@ -2,6 +2,11 @@ ChangeLog Package fPortfolio +2015-05-13 wuertz + + * New function pfolioCVaRoptim added. Computes CVaR along + mean-CVaR optimization approach. + 2014-09-30 tsetz * Final version compatible to books and other packages. @@ -9,7 +14,7 @@ 2014-09-22 tsetz * ChangeLog, DESCRIPTION: Updated ChangeLog and DESCRIPTION files - after submission to CRAN + after submission to CRAN. 2014-03-26 wuertz diff -Nru fportfolio-3011.81/debian/changelog fportfolio-3042.83/debian/changelog --- fportfolio-3011.81/debian/changelog 2017-11-23 01:09:39.000000000 +0000 +++ fportfolio-3042.83/debian/changelog 2017-11-23 01:09:39.000000000 +0000 @@ -1,8 +1,14 @@ -fportfolio (3011.81-2build1) artful; urgency=medium +fportfolio (3042.83-1) unstable; urgency=medium - * No-change rebuild to pick up r-api-3.4 + * New upstream release + + * debian/control: Set Standards-Version: to current version + * debian/control: Set Build-Depends: to current R version + * debianb/control: Add Depends: on ${misc:Depends} + * debian/compat: Set level to 9 + * debian/README.source: Added - -- Graham Inggs Thu, 28 Sep 2017 12:42:07 +0000 + -- Dirk Eddelbuettel Thu, 16 Nov 2017 21:21:14 -0600 fportfolio (3011.81-2) unstable; urgency=medium diff -Nru fportfolio-3011.81/debian/compat fportfolio-3042.83/debian/compat --- fportfolio-3011.81/debian/compat 2017-11-23 01:09:39.000000000 +0000 +++ fportfolio-3042.83/debian/compat 2017-11-23 01:09:39.000000000 +0000 @@ -1 +1 @@ -7 +9 diff -Nru fportfolio-3011.81/debian/control fportfolio-3042.83/debian/control --- fportfolio-3011.81/debian/control 2017-11-23 01:09:39.000000000 +0000 +++ fportfolio-3042.83/debian/control 2017-11-23 01:09:39.000000000 +0000 @@ -2,13 +2,13 @@ Section: gnu-r Priority: optional Maintainer: Dirk Eddelbuettel -Build-Depends: debhelper, r-base-dev (>= 3.3.1), cdbs, r-cran-mass, r-cran-timedate, r-cran-timeseries, r-cran-fbasics, r-cran-fassets (>= 2100.78), r-cran-quadprog, r-cran-rglpk, r-cran-rneos, r-cran-fcopulae, r-cran-rsymphony, r-cran-rsolnp, r-cran-kernlab, xvfb, xauth, xfonts-base -Standards-Version: 3.9.7 +Build-Depends: debhelper, r-base-dev (>= 3.4.2), cdbs, r-cran-mass, r-cran-timedate, r-cran-timeseries, r-cran-fbasics, r-cran-fassets (>= 2100.78), r-cran-quadprog, r-cran-rglpk, r-cran-rneos, r-cran-fcopulae, r-cran-rsymphony, r-cran-rsolnp, r-cran-kernlab, xvfb, xauth, xfonts-base +Standards-Version: 4.1.1 Homepage: http://www.Rmetrics.org Package: r-cran-fportfolio Architecture: any -Depends: ${shlibs:Depends}, ${R:Depends}, r-cran-mass, r-cran-timedate, r-cran-timeseries, r-cran-fbasics, r-cran-fassets (>= 2100.78), r-cran-quadprog, r-cran-rglpk, r-cran-rneos, r-cran-fcopulae, r-cran-rsymphony, r-cran-rsolnp, r-cran-kernlab +Depends: ${shlibs:Depends}, ${R:Depends}, ${misc:Depends}, r-cran-mass, r-cran-timedate, r-cran-timeseries, r-cran-fbasics, r-cran-fassets (>= 2100.78), r-cran-quadprog, r-cran-rglpk, r-cran-rneos, r-cran-fcopulae, r-cran-rsymphony, r-cran-rsolnp, r-cran-kernlab Suggests: r-cran-runit Description: GNU R package for financial engineering -- fPortfolio This package of functions for financial engineering and computational diff -Nru fportfolio-3011.81/debian/README.source fportfolio-3042.83/debian/README.source --- fportfolio-3011.81/debian/README.source 1970-01-01 00:00:00.000000000 +0000 +++ fportfolio-3042.83/debian/README.source 2017-11-23 01:09:39.000000000 +0000 @@ -0,0 +1,21 @@ + +Explanation for binary files inside source package according to + + http://lists.debian.org/debian-devel/2013/09/msg00332.html + +Files: data/SMALLCAP.RET.rda + data/SPISECTOR.RET.rda + data/GCCINDEX.rda + data/SMALLCAP.rda + data/LPP2005.RET.rda + data/GCCINDEX.RET.rda + data/SPISECTOR.rda + data/SWX.rda + data/LPP2005.rda + data/SWX.RET.rda +Documentation: man/data-sets.Rd + + -> Examples data sets for portfolio optimization from the book by Wuertz, Chalabi, Chen + Ellis (2009), "Portfolio Optimization with R/Rmetrics", Zuerich + + -- Dirk Eddelbuettel , Thu, 16 Nov 2017 21:33:08 -0600 diff -Nru fportfolio-3011.81/DESCRIPTION fportfolio-3042.83/DESCRIPTION --- fportfolio-3011.81/DESCRIPTION 2014-10-30 14:54:08.000000000 +0000 +++ fportfolio-3042.83/DESCRIPTION 2017-11-16 21:54:59.000000000 +0000 @@ -1,26 +1,25 @@ Package: fPortfolio Title: Rmetrics - Portfolio Selection and Optimization -Date: 2014-10-30 -Version: 3011.81 -Author: Rmetrics Core Team, - Diethelm Wuertz [aut], +Date: 2017-11-12 +Version: 3042.83 +Author: Diethelm Wuertz [aut], Tobias Setz [cre], - Yohan Chalabi [ctb] -Maintainer: Tobias Setz -Description: Environment for teaching - "Financial Engineering and Computational Finance". -Depends: R (>= 2.15.1), methods, timeDate, timeSeries, fBasics, fAssets -Imports: fCopulae, robustbase, MASS, Rglpk, slam, Rsymphony, Rsolnp, - kernlab, quadprog, rneos -Suggests: Rsocp, Rnlminb2, Rdonlp2, dplR, bcp, fGarch, mvoutlier + Yohan Chalabi [ctb], + William Chen [ctb] +Maintainer: Tobias Setz +Description: Provides a collection + of functions to optimize portfolios and to analyze them from + different points of view. +Depends: R (>= 2.15.1), timeDate, timeSeries, fBasics, fAssets +Imports: fCopulae, robustbase, MASS, Rglpk, slam, Rsolnp, quadprog, + kernlab, rneos, methods, grDevices, graphics, stats, utils +Suggests: Rsocp, Rnlminb2, Rdonlp2, Rsymphony, dplR, bcp, fGarch, + mvoutlier Additional_repositories: http://r-forge.r-project.org/ -Note: SEVERAL PARTS ARE STILL PRELIMINARY AND MAY BE CHANGED IN THE - FUTURE. THIS TYPICALLY INCLUDES FUNCTION AND ARGUMENT NAMES, AS - WELL AS DEFAULTS FOR ARGUMENTS AND RETURN VALUES. LazyData: yes License: GPL (>= 2) URL: https://www.rmetrics.org -Packaged: 2014-10-30 14:13:59 UTC; Tobi NeedsCompilation: no +Packaged: 2017-11-16 17:28:41 UTC; Tobias Setz Repository: CRAN -Date/Publication: 2014-10-30 15:54:08 +Date/Publication: 2017-11-16 21:54:59 UTC diff -Nru fportfolio-3011.81/man/00fPortfolio-package.Rd fportfolio-3042.83/man/00fPortfolio-package.Rd --- fportfolio-3011.81/man/00fPortfolio-package.Rd 2014-10-30 14:13:57.000000000 +0000 +++ fportfolio-3042.83/man/00fPortfolio-package.Rd 2017-11-16 16:50:29.000000000 +0000 @@ -1,46 +1,46 @@ -\name{fPortfolio-package} - - -\alias{fPortfolio} - - -\docType{package} - - -\title{Portfolio Design, Optimization and Backtesting} - - -\description{ - - The Rmetrics "fPortfolio" package is a very powerful collection - of functions to optimize portfolios and to analyze them from - different points ov view. - -} - - -\details{ - - \tabular{ll}{ - Package: \tab fPortfolio\cr - Type: \tab Package\cr - Date: \tab 2011\cr - License: \tab GPL Version 2 or later\cr - Copyright: \tab (c) 1999-2011 Diethelm Wuertz and Rmetrics Association\cr - URL: \tab \url{http://www.rmetrics.org} - } - -} - - -\references{ - -Wuertz, D., Chalabi, Y., Chen W., Ellis A. (2009); - \emph{Portfolio Optimization with R/Rmetrics}, - Rmetrics eBook, Rmetrics Association and Finance Online, Zurich. - -} - - -\keyword{models} - +\name{fPortfolio-package} + + +\alias{fPortfolio} + + +\docType{package} + + +\title{Portfolio Design, Optimization and Backtesting} + + +\description{ + + The Rmetrics "fPortfolio" package is a very powerful collection + of functions to optimize portfolios and to analyze them from + different points of view. + +} + + +\details{ + + \tabular{ll}{ + Package: \tab fPortfolio\cr + Type: \tab Package\cr + Date: \tab 2011\cr + License: \tab GPL Version 2 or later\cr + Copyright: \tab (c) 1999-2011 Diethelm Wuertz and Rmetrics Association\cr + URL: \tab \url{http://www.rmetrics.org} + } + +} + + +\references{ + +Wuertz, D., Chalabi, Y., Chen W., Ellis A. (2009); + \emph{Portfolio Optimization with R/Rmetrics}, + Rmetrics eBook, Rmetrics Association and Finance Online, Zurich. + +} + + +\keyword{models} + diff -Nru fportfolio-3011.81/man/portfolio-portfolioSpec.Rd fportfolio-3042.83/man/portfolio-portfolioSpec.Rd --- fportfolio-3011.81/man/portfolio-portfolioSpec.Rd 2014-10-30 14:13:57.000000000 +0000 +++ fportfolio-3042.83/man/portfolio-portfolioSpec.Rd 2017-11-13 15:27:54.000000000 +0000 @@ -1,375 +1,375 @@ -\name{portfolio-portfolioSpec} - - -\alias{portfolioSpec} - - -\title{Specification of Portfolios} - - -\description{ - - Specifies a portfolio from scratch. - -} - - -\usage{ -portfolioSpec( - model = list( - type = "MV", optimize = "minRisk", - estimator = "covEstimator", tailRisk = list(), - params = list(alpha = 0.05, a = 1)), - portfolio = list( - weights = NULL, targetReturn = NULL, - targetRisk = NULL, riskFreeRate = 0, nFrontierPoints = 50, - status = NA), - optim = list( - solver = "solveRquadprog", - objective = c("portfolioObjective", "portfolioReturn", "portfolioRisk"), - options = list(meq = 2), control = list(), trace = FALSE), - messages = list( - messages = FALSE, note = ""), - ampl = list( - ampl = FALSE, project = "ampl", solver = "ipopt", - protocol = FALSE, trace = FALSE) - ) -} - - - -\arguments{ - - - \item{model}{ - a list, containing different arguments: type, estimator, params. - See these arguments for further explanation. - } - \item{portfolio}{ - a list, containing different arguments: weights, targetReturn, - riskFreeRate, nFrontierPoints. See these - arguments for further explanation. - } - \item{optim}{ - a list with four entries, a character string \code{solver} denoting - the type of the solver to be used, a \code{params} list to pass further - arguments to the objective function to optimize, a \code{control} list - for all control settings of the solver, and a logical flag, \code{trace} - denoting if the optimization should be traced. - } - \item{messages}{ - a list, for optional messages. - } - \item{ampl}{ - a list, controls settings for the R/AMPL interface. - } -} - - -\details{ - - To optimize a portfolio of assets we first have to specify it. All - settings which specify a portfolio of assets are respresented by a - S4 class named \code{fPFOLIOSPEC}. - - \preformatted{ - setClass("fPFOLIOSPEC", - representation( - model = "list", - portfolio = "list", - optim = "list") ) - } - - An object of class \code{fPFOLIOSPEC} has three slots, named - \code{@model}, \code{@portfolio}, and \code{@optim}. The first - slot \code{@model} holds the model information, the second - slot \code{@portfolio} the portfolio information, and the last - slot \code{@optim} the information about the solver used for - optimization. - - The default settings are as follows: - - \preformatted{ - model = list( - type = "MV", - optimize = "minRisk", - estimator = "covEstimator", - tailRisk = list(), - params = list(alpha = 0.05, a = 2)), - portfolio = list( - weights = NULL, - targetReturn = NULL, - targetRisk = NULL, - riskFreeRate = 0, - nFrontierPoints = 50, - status = NA), - optim = list( - solver = "solveRquadprog", - objective = NULL, - parames = list(), - control = list(meq = 2), - trace = FALSE) - } - - - \bold{Model Slot:} - - - \emph{Type of Model:}\cr - The list entry \code{type} from the \code{@model} slot describes - the type of the desired portfolio. The current implementation - supports three types of portfolios. This may be - a Markowitz mean -- variance portfolio named \code{"MV"}, - a mean -- lower partial moment portfolio named \code{"LPM"}, or - a mean -- CVaR condititional value-at-risk portfolio named \code{"CVaR"}. - One can use the function \code{getType} to retrieve the current - setting and the function \code{setType} to modify this selection. - - - \emph{What to optimize?}\cr - The list entry \code{optimize} from the \code{@model} slot describes - what should be optimized. Two choices are psssible. Either - - \preformatted{ - \code{"minRisk"} - } - - which minimizes the risk if the target returns is given, or - - \preformatted{ - \code{"maxReturn"} - } - - which maximizes the return if the target risk is given. - One can use the function \code{getOptimize} to retrieve the current - setting and the function \code{setOptimize} to modify this selection. - - - \emph{How to estimate mean and covariance?}\cr - The list entry \code{estimator} from the \code{@model} slot requests - for a string that denotes the function name of the covariance - estimator which should be used for the estimation of risk. - - In Markowitz' mean-variance portfolio model, \code{type="MV"}, the - default function - - \preformatted{ - \code{"covEstimator"} - } - - is used which computes the standard column means - of the multivariate assets data series and the standard covariance - matrix. Alternative robust estimators include - - \preformatted{ - \code{"covMcdEstimator"} - \code{"covOGKEstimator"} - \code{"mveEstimator"} - \code{"nnveEstimator"} - \code{"mcdEstimator"} - } - - In addition a shrinkage covariance estimator named - - \preformatted{ - \code{"shrinkEstimator"}, - } - - and a bagged covariance estimator named - - \preformatted{ - \code{"baggedEstimator"} - } - - are also available. - Note, the experienced user can add his own function to estimate in any - alternative way the mean and the covariance of the multivariate assets - data series. In this case (s)he has to write a function, e.g. named - - \preformatted{ - \code{myEstimator=function(x,spec=NULL,...)} - } - - where \code{x} is a multivariate time series, \code{spec} optionally - the portfolio specification, if rquired, and \code{...} additional - arguments passed to the users code. Note, \code{myEstimator} must - a return a named list, with at least the following two entries - \code{\$mu} and \code{\$Sigma}, which represent estimators for the - mean and covariance, respectively. - - In the case of the Mean -- Lower-Partial-Moment portfolio, - \code{type="LPM"} we make use of the equivalence to Markowitz' - mean-variance portfolio with a modified covariance estimator, i.e. - - \preformatted{ - \code{"lpmEstimator"}, - } - - Note, in this case the setting of \code{type="LPM"} - changes the covariance estimator function name - from any selection previously made to the function automatically - to \code{"lpmEstimator"} which returns the LPM mean and covariance - estimates. - - One can use the function \code{getEstimator} to retrieve the current - setting and the function \code{setEstimator} to modify this selection. - - - \emph{Tail Risk List:}\cr - The list entry \code{tailRisk} from the \code{@model} slot is an empty - list. It can be used to add tail risk budget constrains to the - optimization. In this case a square matrix of the size of the - number of assets is expected as list entry, which contains bivariate - tail risk measures, i.e. the tail dependence coefficients estaimated - via a copulae approach. - Use the function \code{setType} to modify this selection. - - - The list entry \code{parameters} from the \code{@model} slot is a - list with additional parameters used in different situations. It can - be ebhanced by the user if needed. - By default it contains the exponent \code{a=2}, the parameter needed - for "LPM" portfolio optimization, - and it contains the \code{targetAlpha=0.05}, the confidence level - for "CVaR" portfolio optimization. - Use the function \code{setParams} to modify this selection. - - - \bold{Portfolio Slot:} - - - The values \code{weights}, \code{targetReturn}, and \code{targetRisk} - from the \code{portfolio} slot have to be considered in common. By - default all three are set to \code{NULL}. If this is the case, then - it is assumed that an equal weight portfolio should be calculated. - If only one of the three values is different from \code{NULL} then - the following procedure will be startet. - If the weights are specified then it is assumed that a feasible - portfolio should be considered. - If the target return is fixed then it is assumed that the efficient - portfolio with the minimal risk will be considered. - And finally if the risk is fixed, then the return should be maximized. - Use the functions \code{setWeights}, \code{setTargetReturn}, and - \code{setTargetRisk} to modify this selection.Note, the change in of - the three functions will influence the settings of the other two. - - - The \code{riskFreeRate=0} is also stored in the \code{portfolio} slot. - Its value defaults to zero. It can be changed by the user. - Use the function \code{setRiskFreeRate} to modify this selection. - - - The number of frontier points reqauired by the calculation of - the \code{portfolioFrontier} is obtained from the value of - \code{nFrontierPoints=50} hold in the \code{portfolio} slot. - Its value defaults to 50. It can be changed by the user. - Use the function \code{setNFrontierPoints} to modify this selection. - - - The final \code{status} of portfolio optimization is returned - and stored in the \code{portfolio} slot. Before optimization the - value is unset to \code{NA}, after optimization a value of - \code{status=0} means a successful termination. For other - values we recommend to inspect the help page of the selected - solver, the name of the solver can be returned by the function - \code{getSolver}. - Use the function \code{setSolver} to reset the value to \code{NA} - if it should be required. - - - \bold{Optim Slot:} - - - The name of the default solver used for optimization can be retrieved - calling the function \code{getSolver}. The default value for the - value \code{solver} in the specification is set to \code{NULL} - which means that the best solver availalbe will be autoselected - and used. Before optimization the user can change the setting - to another solver. Be aware, that a possible personal change will - be overwritten by the function \code{setType}, so call - \code{setSolver} after setting the type of the portfolio. - - - The logical flag \code{trace} in the slot \code{optim} allows - to trace optionally the portfolio optimization process. By - default this will not be the case since the default value is - \code{trace=FALSE}. Use the fanction \code{setTrace} to modify - the selection. - - - \bold{Retrieving and Modifying Specification Settings:} - - - Information about the current portfolio specification can be retrieved - by \code{"get"} functions. These include: - - \tabular{ll}{ - \code{getType} \tab Extracts portfolio type from specification, \cr - \code{getOptimize} \tab Extracts what to optimize from specification, \cr - \code{getEstimator} \tab Extracts type of covariance estimator, \cr - \code{getTailRisk} \tab Extracts list of tail dependency risk matrixes, \cr - \code{getParams} \tab Extracts parameters from specification, \cr - \code{getWeights} \tab Extracts weights from a portfolio object, \cr - \code{getTargetReturn} \tab Extracts target return from specification, \cr - \code{getTargetRisk} \tab Extracts target riks from specification, \cr - \code{getAlpha} \tab Extracts target VaR-alpha specification, \cr - \code{getRiskFreeRate} \tab Extracts risk free rate from specification, \cr - \code{getNFrontierPoints} \tab Extracts number of frontier points, \cr - \code{getStatus} \tab Extracts the status of optimization, \cr - \code{getSolver} \tab Extracts solver from specification, \cr - \code{getTrace} \tab Extracts solver's trace flag. } - - For details we refer to \code{link{getSpec}}. - - To modify the setting from a portfolio specification use the - \code{"set"} functions: - - \tabular{ll}{ - \code{setType} \tab Sets type of portfolio optimization, \cr - \code{setOptimize} \tab Sets what to optimize, min risk or max return, \cr - \code{setEstimator} \tab Sets names of mean and covariance estimators, \cr - \code{setParams} \tab Sets optional model parameters, \cr - \code{setWeights} \tab Sets weights vector, \cr - \code{setTargetReturn} \tab Sets target return value, \cr - \code{setTargetRisk} \tab Sets target risk value, \cr - \code{setTargetAlpha} \tab Sets CVaR target alpha value, \cr - \code{setRiskFreeRate} \tab Sets risk-free rate value, \cr - \code{setNFrontierPoints} \tab Sets number of frontier points, \cr - \code{setStatus} \tab Sets status value, \cr - \code{setSolver} \tab Sets the type of solver to be used, \cr - \code{setTrace} \tab Sets the logical trace flag. } - - - For details we refer to \code{link{setSpec}}. - - \bold{Printing Specification Settings:} - - There is a generic print function to print information from - specification. What is printed depends on the values of the - settings. For example \code{print(portfolioSpec())} returns - the type of portfolio, the name of the covariance estimator, - the portfolios risk free rate, and the desired solver. - -} - - -\value{ - - \code{portfolioSpec}\cr - \cr - returns an S4 object of class \code{"fPFOLIOSPEC"}. - -} - - -\references{ - -Wuertz, D., Chalabi, Y., Chen W., Ellis A. (2009); - \emph{Portfolio Optimization with R/Rmetrics}, - Rmetrics eBook, Rmetrics Association and Finance Online, Zurich. - -} - - -\keyword{models} - +\name{portfolio-portfolioSpec} + + +\alias{portfolioSpec} + + +\title{Specification of Portfolios} + + +\description{ + + Specifies a portfolio from scratch. + +} + + +\usage{ +portfolioSpec( + model = list( + type = "MV", optimize = "minRisk", + estimator = "covEstimator", tailRisk = list(), + params = list(alpha = 0.05)), + portfolio = list( + weights = NULL, targetReturn = NULL, + targetRisk = NULL, riskFreeRate = 0, nFrontierPoints = 50, + status = NA), + optim = list( + solver = "solveRquadprog", + objective = c("portfolioObjective", "portfolioReturn", "portfolioRisk"), + options = list(meq = 2), control = list(), trace = FALSE), + messages = list( + messages = FALSE, note = ""), + ampl = list( + ampl = FALSE, project = "ampl", solver = "ipopt", + protocol = FALSE, trace = FALSE) + ) +} + + + +\arguments{ + + + \item{model}{ + a list, containing different arguments: type, estimator, params. + See these arguments for further explanation. + } + \item{portfolio}{ + a list, containing different arguments: weights, targetReturn, + riskFreeRate, nFrontierPoints. See these + arguments for further explanation. + } + \item{optim}{ + a list with four entries, a character string \code{solver} denoting + the type of the solver to be used, a \code{params} list to pass further + arguments to the objective function to optimize, a \code{control} list + for all control settings of the solver, and a logical flag, \code{trace} + denoting if the optimization should be traced. + } + \item{messages}{ + a list, for optional messages. + } + \item{ampl}{ + a list, controls settings for the R/AMPL interface. + } +} + + +\details{ + + To optimize a portfolio of assets we first have to specify it. All + settings which specify a portfolio of assets are respresented by a + S4 class named \code{fPFOLIOSPEC}. + + \preformatted{ + setClass("fPFOLIOSPEC", + representation( + model = "list", + portfolio = "list", + optim = "list") ) + } + + An object of class \code{fPFOLIOSPEC} has three slots, named + \code{@model}, \code{@portfolio}, and \code{@optim}. The first + slot \code{@model} holds the model information, the second + slot \code{@portfolio} the portfolio information, and the last + slot \code{@optim} the information about the solver used for + optimization. + + The default settings are as follows: + + \preformatted{ + model = list( + type = "MV", + optimize = "minRisk", + estimator = "covEstimator", + tailRisk = list(), + params = list(alpha = 0.05, a = 2)), + portfolio = list( + weights = NULL, + targetReturn = NULL, + targetRisk = NULL, + riskFreeRate = 0, + nFrontierPoints = 50, + status = NA), + optim = list( + solver = "solveRquadprog", + objective = NULL, + parames = list(), + control = list(meq = 2), + trace = FALSE) + } + + + \bold{Model Slot:} + + + \emph{Type of Model:}\cr + The list entry \code{type} from the \code{@model} slot describes + the type of the desired portfolio. The current implementation + supports three types of portfolios. This may be + a Markowitz mean -- variance portfolio named \code{"MV"}, + a mean -- lower partial moment portfolio named \code{"LPM"}, or + a mean -- CVaR condititional value-at-risk portfolio named \code{"CVaR"}. + One can use the function \code{getType} to retrieve the current + setting and the function \code{setType} to modify this selection. + + + \emph{What to optimize?}\cr + The list entry \code{optimize} from the \code{@model} slot describes + what should be optimized. Two choices are psssible. Either + + \preformatted{ + \code{"minRisk"} + } + + which minimizes the risk if the target returns is given, or + + \preformatted{ + \code{"maxReturn"} + } + + which maximizes the return if the target risk is given. + One can use the function \code{getOptimize} to retrieve the current + setting and the function \code{setOptimize} to modify this selection. + + + \emph{How to estimate mean and covariance?}\cr + The list entry \code{estimator} from the \code{@model} slot requests + for a string that denotes the function name of the covariance + estimator which should be used for the estimation of risk. + + In Markowitz' mean-variance portfolio model, \code{type="MV"}, the + default function + + \preformatted{ + \code{"covEstimator"} + } + + is used which computes the standard column means + of the multivariate assets data series and the standard covariance + matrix. Alternative robust estimators include + + \preformatted{ + \code{"covMcdEstimator"} + \code{"covOGKEstimator"} + \code{"mveEstimator"} + \code{"nnveEstimator"} + \code{"mcdEstimator"} + } + + In addition a shrinkage covariance estimator named + + \preformatted{ + \code{"shrinkEstimator"}, + } + + and a bagged covariance estimator named + + \preformatted{ + \code{"baggedEstimator"} + } + + are also available. + Note, the experienced user can add his own function to estimate in any + alternative way the mean and the covariance of the multivariate assets + data series. In this case (s)he has to write a function, e.g. named + + \preformatted{ + \code{myEstimator=function(x,spec=NULL,...)} + } + + where \code{x} is a multivariate time series, \code{spec} optionally + the portfolio specification, if rquired, and \code{...} additional + arguments passed to the users code. Note, \code{myEstimator} must + a return a named list, with at least the following two entries + \code{\$mu} and \code{\$Sigma}, which represent estimators for the + mean and covariance, respectively. + + In the case of the Mean -- Lower-Partial-Moment portfolio, + \code{type="LPM"} we make use of the equivalence to Markowitz' + mean-variance portfolio with a modified covariance estimator, i.e. + + \preformatted{ + \code{"lpmEstimator"}, + } + + Note, in this case the setting of \code{type="LPM"} + changes the covariance estimator function name + from any selection previously made to the function automatically + to \code{"lpmEstimator"} which returns the LPM mean and covariance + estimates. + + One can use the function \code{getEstimator} to retrieve the current + setting and the function \code{setEstimator} to modify this selection. + + + \emph{Tail Risk List:}\cr + The list entry \code{tailRisk} from the \code{@model} slot is an empty + list. It can be used to add tail risk budget constrains to the + optimization. In this case a square matrix of the size of the + number of assets is expected as list entry, which contains bivariate + tail risk measures, i.e. the tail dependence coefficients estaimated + via a copulae approach. + Use the function \code{setType} to modify this selection. + + + The list entry \code{parameters} from the \code{@model} slot is a + list with additional parameters used in different situations. It can + be ebhanced by the user if needed. + By default it contains the exponent \code{a=2}, the parameter needed + for "LPM" portfolio optimization, + and it contains the \code{targetAlpha=0.05}, the confidence level + for "CVaR" portfolio optimization. + Use the function \code{setParams} to modify this selection. + + + \bold{Portfolio Slot:} + + + The values \code{weights}, \code{targetReturn}, and \code{targetRisk} + from the \code{portfolio} slot have to be considered in common. By + default all three are set to \code{NULL}. If this is the case, then + it is assumed that an equal weight portfolio should be calculated. + If only one of the three values is different from \code{NULL} then + the following procedure will be startet. + If the weights are specified then it is assumed that a feasible + portfolio should be considered. + If the target return is fixed then it is assumed that the efficient + portfolio with the minimal risk will be considered. + And finally if the risk is fixed, then the return should be maximized. + Use the functions \code{setWeights}, \code{setTargetReturn}, and + \code{setTargetRisk} to modify this selection.Note, the change in of + the three functions will influence the settings of the other two. + + + The \code{riskFreeRate=0} is also stored in the \code{portfolio} slot. + Its value defaults to zero. It can be changed by the user. + Use the function \code{setRiskFreeRate} to modify this selection. + + + The number of frontier points reqauired by the calculation of + the \code{portfolioFrontier} is obtained from the value of + \code{nFrontierPoints=50} hold in the \code{portfolio} slot. + Its value defaults to 50. It can be changed by the user. + Use the function \code{setNFrontierPoints} to modify this selection. + + + The final \code{status} of portfolio optimization is returned + and stored in the \code{portfolio} slot. Before optimization the + value is unset to \code{NA}, after optimization a value of + \code{status=0} means a successful termination. For other + values we recommend to inspect the help page of the selected + solver, the name of the solver can be returned by the function + \code{getSolver}. + Use the function \code{setSolver} to reset the value to \code{NA} + if it should be required. + + + \bold{Optim Slot:} + + + The name of the default solver used for optimization can be retrieved + calling the function \code{getSolver}. The default value for the + value \code{solver} in the specification is set to \code{NULL} + which means that the best solver availalbe will be autoselected + and used. Before optimization the user can change the setting + to another solver. Be aware, that a possible personal change will + be overwritten by the function \code{setType}, so call + \code{setSolver} after setting the type of the portfolio. + + + The logical flag \code{trace} in the slot \code{optim} allows + to trace optionally the portfolio optimization process. By + default this will not be the case since the default value is + \code{trace=FALSE}. Use the fanction \code{setTrace} to modify + the selection. + + + \bold{Retrieving and Modifying Specification Settings:} + + + Information about the current portfolio specification can be retrieved + by \code{"get"} functions. These include: + + \tabular{ll}{ + \code{getType} \tab Extracts portfolio type from specification, \cr + \code{getOptimize} \tab Extracts what to optimize from specification, \cr + \code{getEstimator} \tab Extracts type of covariance estimator, \cr + \code{getTailRisk} \tab Extracts list of tail dependency risk matrixes, \cr + \code{getParams} \tab Extracts parameters from specification, \cr + \code{getWeights} \tab Extracts weights from a portfolio object, \cr + \code{getTargetReturn} \tab Extracts target return from specification, \cr + \code{getTargetRisk} \tab Extracts target riks from specification, \cr + \code{getAlpha} \tab Extracts target VaR-alpha specification, \cr + \code{getRiskFreeRate} \tab Extracts risk free rate from specification, \cr + \code{getNFrontierPoints} \tab Extracts number of frontier points, \cr + \code{getStatus} \tab Extracts the status of optimization, \cr + \code{getSolver} \tab Extracts solver from specification, \cr + \code{getTrace} \tab Extracts solver's trace flag. } + + For details we refer to \code{link{getSpec}}. + + To modify the setting from a portfolio specification use the + \code{"set"} functions: + + \tabular{ll}{ + \code{setType} \tab Sets type of portfolio optimization, \cr + \code{setOptimize} \tab Sets what to optimize, min risk or max return, \cr + \code{setEstimator} \tab Sets names of mean and covariance estimators, \cr + \code{setParams} \tab Sets optional model parameters, \cr + \code{setWeights} \tab Sets weights vector, \cr + \code{setTargetReturn} \tab Sets target return value, \cr + \code{setTargetRisk} \tab Sets target risk value, \cr + \code{setTargetAlpha} \tab Sets CVaR target alpha value, \cr + \code{setRiskFreeRate} \tab Sets risk-free rate value, \cr + \code{setNFrontierPoints} \tab Sets number of frontier points, \cr + \code{setStatus} \tab Sets status value, \cr + \code{setSolver} \tab Sets the type of solver to be used, \cr + \code{setTrace} \tab Sets the logical trace flag. } + + + For details we refer to \code{link{setSpec}}. + + \bold{Printing Specification Settings:} + + There is a generic print function to print information from + specification. What is printed depends on the values of the + settings. For example \code{print(portfolioSpec())} returns + the type of portfolio, the name of the covariance estimator, + the portfolios risk free rate, and the desired solver. + +} + + +\value{ + + \code{portfolioSpec}\cr + \cr + returns an S4 object of class \code{"fPFOLIOSPEC"}. + +} + + +\references{ + +Wuertz, D., Chalabi, Y., Chen W., Ellis A. (2009); + \emph{Portfolio Optimization with R/Rmetrics}, + Rmetrics eBook, Rmetrics Association and Finance Online, Zurich. + +} + + +\keyword{models} + diff -Nru fportfolio-3011.81/man/portfolio-riskPfolio.Rd fportfolio-3042.83/man/portfolio-riskPfolio.Rd --- fportfolio-3011.81/man/portfolio-riskPfolio.Rd 2014-10-30 14:13:57.000000000 +0000 +++ fportfolio-3042.83/man/portfolio-riskPfolio.Rd 2015-11-09 15:03:22.000000000 +0000 @@ -7,6 +7,7 @@ \alias{pfolioCVaR} \alias{pfolioCVaRplus} \alias{lambdaCVaR} +\alias{pfolioCVaRoptim} \alias{pfolioMaxLoss} \alias{pfolioReturn} @@ -31,6 +32,7 @@ \code{pfolioCVaRplus} \tab computes Value-at-Risk+ for a portfolio of assets, \cr \code{pfolioCVaR} \tab computes Conditional Value-at-Risk for a PF of assets, \cr \code{lambdaCVaR} \tab computes CVaR's atomic split value lambda, \cr + \code{pfolioCVaRoptim} \tab computes Conditional VaR from mean-CVaR optimization, \cr \code{pfolioMaxLoss} \tab computes Maximum Loss for a portfolio of assets, \cr \code{pfolioReturn} \tab computes return values of a portfolio, \cr \code{pfolioTargetReturn} \tab computes the target return of a portfolio, \cr @@ -45,6 +47,7 @@ pfolioCVaRplus(x, weights = NULL, alpha = 0.05) pfolioCVaR(x, weights = NULL, alpha = 0.05) lambdaCVaR(n, alpha = 0.05) +pfolioCVaRoptim(x, weights = NULL, alpha = 0.05) pfolioMaxLoss(x, weights = NULL) pfolioReturn(x, weights = NULL, geometric = FALSE) diff -Nru fportfolio-3011.81/MD5 fportfolio-3042.83/MD5 --- fportfolio-3011.81/MD5 2014-10-30 14:54:08.000000000 +0000 +++ fportfolio-3042.83/MD5 2017-11-16 21:54:59.000000000 +0000 @@ -1,6 +1,6 @@ -236a475e2cfd6927566ea82b26728536 *ChangeLog -9ce77cd4a3453cd9357fbede6924dc8b *DESCRIPTION -97c78787fc513bd3b7f7b028a36b1aa1 *NAMESPACE +84e94ae8a4e32c30936996f9f0cef576 *ChangeLog +8d0707a2291550aad8c5b35d53ac71d4 *DESCRIPTION +c045c3292c2769af9e17c8535cf01b40 *NAMESPACE 9c61ea20343e8315109a8c6047bb8866 *R/00RmetricsPortfolio-package.R 6861674434ab48aaa7269a75d6f6c912 *R/a-class-fPFOLIOBACKTEST.R 80a747f51860402e2e5588831c5bf406 *R/a-class-fPFOLIOCON.R @@ -24,13 +24,13 @@ 12da752939eaf2aad6c4025c97e12f18 *R/mathprogLP-ampl.R 02bcd48cafdc16bfea96dfbccbdf0195 *R/mathprogLP-glpk.R cdf8bf7e85786ae2a36cbdae098753c5 *R/mathprogLP-neos.R -175a99d7a50cec26b9fd49b8acc53d67 *R/mathprogLP-symphony.R +1b8e3d0145709b556260d19c11a291c5 *R/mathprogLP-symphony.R fdd5a777f1e76fdee002a8d4aa020493 *R/mathprogLP.R 4428e534ff8c53da0fba84bb22f4213f *R/mathprogNLP-ampl.R be7f8d410b2967e5080069e89b2b3343 *R/mathprogNLP-donlp2.R 22461097a1bbf8860ff9e001307830ce *R/mathprogNLP-nlminb2.R 163951e5af04a0f23a8d5296bfdf69bb *R/mathprogNLP-solnp.R -c09c08f62b186532a0238d5b6654bb61 *R/mathprogNLP.R +8e8b410b008799f7cca382c874b69ac0 *R/mathprogNLP.R bd42c6082a0f05a2beb1958bfab836ba *R/mathprogQP-ampl.R 1e3471c95a8bb7c5949de1469b52ad3e *R/mathprogQP-ipop.R d353b2e6375377e596b31dfe61b23104 *R/mathprogQP-kestrel.R @@ -39,10 +39,10 @@ 9177cb5c5f4a5d5e06482d465f3b5677 *R/mathprogQP.R 8c559056911428893b70d9d12b07089b *R/methods-mathprog.R 8368a5d4d5e77b328c842bb36fdbaba3 *R/methods-plot.R -bb93e104843a733804b3d6b602a640fe *R/methods-show.R +f729fe56a411603a3f3a2714e8383d56 *R/methods-show.R 749a323db19bfe4cae10fc1727d06f1a *R/methods-summary.R de25c1eaa2f5f9b0e3bbc30f90d314be *R/monitor-indicators.R -ba149f2c34e60cfa48b41fb9d0ebbcb9 *R/monitor-stability.R +e8ed773f017fe1f4602726d72358c85d *R/monitor-stability.R b674387d5606178afb6623527d0c87b3 *R/object-getData.R 2752da6015144a4701a51c8a91ad4aa2 *R/object-getPortfolio.R ba4b9d8a140e4ffdafe6653528833c4d *R/object-getPortfolioVal.R @@ -50,8 +50,8 @@ 80d1e9dd9cb59786a803cc0284b5b7ad *R/object-getUseMethods.R 3f06ddd58d065b784b7e3ee38967cc55 *R/object-portfolioConstraints.R e07080e8276aed3a72121cec4f9a07af *R/object-portfolioData.R -954aae840a4302c1dacf7d128939a2b4 *R/object-portfolioSpec.R -f20ff6a2c1cae6d049b4c913432f88cf *R/object-setSpec.R +0e6af119d9a9bda8c0302be6c4cddcb6 *R/object-portfolioSpec.R +4c8694c99a3c7a9f0348c2a9fb2a241d *R/object-setSpec.R b3c00ece0c3bea0e950c563fa15eaea2 *R/plot-vaniniFig.R 2816d5409df473091a3126c24ca55145 *R/plot-weightsLines.R 8a7362f95d75d86de9251f99f42250ad *R/plot-weightsPies.R @@ -60,13 +60,13 @@ 4ca48732f888a29777f356a5ecc8256b *R/portfolio-efficientFrontier.R 760d0e43bc1ea0e0e3754069d1926780 *R/portfolio-efficientPfolio.R bd2ad7d2136f7da491ae64e2cdbda3d5 *R/portfolio-feasiblePfolio.R -96f23326787683e4ebad0fd1e61cf483 *R/portfolio-riskPfolio.R +4ca83d7b214c3826ff6b4c09dcdbd852 *R/portfolio-riskPfolio.R 46a83e737d99e7e5bd84af5ce7c08192 *R/portfolio-rollingPfolio.R 3ab6aa74ee174cbe753eb858410232a9 *R/risk-budgeting.R 63dc17c6e14016c69a206babbd7d3869 *R/risk-covEstimator.R 381f99e393a11577ccbe7d279486143c *R/risk-pfolioMeasures.R b53df020921f9816a5f0de25c2c68f18 *R/risk-surfaceRisk.R -6e9489b48a0042607dc81bf1f770e977 *R/risk-tailBudgets.R +1f66b7bae522ee57658524c5449224d8 *R/risk-tailBudgets.R 9c39859563c928ef4ac367130d52d8fe *R/risk-ternaryMap.R 460497d2d16d2d9e53a4c964d67a3844 *R/solve-Rampl.R f6399901056b542dbf818249bb7c46cd *R/solve-Rdonlp2.R @@ -88,7 +88,7 @@ 37757850b5e7f57851a86974bf2a41b4 *R/utils-exampleData.R ea143f9154560dd70050bbc2a60326ab *R/utils-methods.R e93dd92f5dbe044868304d1319a0ed93 *R/utils-specs.R -76dcef95641d69c5c957d99aea458fa8 *R/zzz.R +53208dc3190d0a1c729f80ce8767dea9 *R/zzz.R 624342bcb232ecd30748f650c9d108b1 *data/ECON85.csv 91f6ea4ee14073dbe9a9eb231ec45214 *data/ECON85LONG.csv 84e46cd7f37a1ef23e2af3cec871175f *data/GCCINDEX.RET.rda @@ -109,7 +109,7 @@ fb62e6486baa854b494dbdc570262dd0 *inst/LICENSE_SOLNP bdb660a470a12c8332b05451868092f6 *inst/ReferenceCard.txt 445ae4c3417aa210e78a7cd3783db23c *inst/obsolete/zzz.Deprecated.R -9b9d77f60decc9c8ae9781577ec2a4bc *man/00fPortfolio-package.Rd +8aa7b8e28557f52d9142b7ffcc710c42 *man/00fPortfolio-package.Rd 8068833535e7a78e2b56b37d738c9a10 *man/a-class-fPFOLIOBACKTEST.Rd 4630021f7d22f8343efb110ab9413224 *man/a-class-fPFOLIOCON.Rd 0146be7c56345243b568c06ed733cf34 *man/a-class-fPFOLIODATA.Rd @@ -149,8 +149,8 @@ dd865180d9ec78f73d60750258cbf1a0 *man/portfolio-getSpec.Rd 25397871d135713996abcb4a397855db *man/portfolio-getVal.Rd 589dcec5f66f04b214d03fec6fed306d *man/portfolio-pfolioRisk.Rd -631afc15ad781fb5cbf1f3ad37bb84de *man/portfolio-portfolioSpec.Rd -ee39d461fc6ccb85f1c70e867e4ebc13 *man/portfolio-riskPfolio.Rd +f3e52157e95c2b3904c535388f906bc5 *man/portfolio-portfolioSpec.Rd +ae191a5b5dc3db2e2a6e84bbd8a4a6ef *man/portfolio-riskPfolio.Rd 7d6ab136392d6a25f11911b6b29fe34d *man/portfolio-setSpec.Rd 3364c894fba153f2a2053cb9e8f69c5c *man/risk-budgeting.Rd a054ee1b376736078ebcbf230a5664ac *man/risk-surfaceRisk.Rd diff -Nru fportfolio-3011.81/NAMESPACE fportfolio-3042.83/NAMESPACE --- fportfolio-3011.81/NAMESPACE 2014-10-30 14:13:57.000000000 +0000 +++ fportfolio-3042.83/NAMESPACE 2017-11-13 16:13:43.000000000 +0000 @@ -27,8 +27,132 @@ import(MASS) import(Rglpk) import(slam) -import(Rsymphony) import(Rsolnp) -import(kernlab) import(quadprog) +import(kernlab) import(rneos) + +importFrom("grDevices", heat.colors, rainbow, topo.colors) +importFrom("graphics", axis, barplot, box, contour, grid, hist, image, layout, lcm, + legend, mtext, par, pie, plot.new, plot.window, polygon, rect, text, title) +importFrom("stats", approx, cov, density, dnorm, nlminb, optim, optimize, pnorm, + qnorm, rcauchy, rnorm, runif, sd, ts.plot, var, weights) +importFrom("utils", capture.output, data, packageDescription) + +################################################################################ +## S3 Exports +################################################################################ +S3method("print", "solver") + + +S3method("getData", "fPFOLIODATA") +S3method("getSeries", "fPFOLIODATA") +S3method("getNAssets", "fPFOLIODATA") +S3method("getUnits", "fPFOLIODATA") + +S3method("getStatistics", "fPFOLIODATA") +S3method("getMean", "fPFOLIODATA") +S3method("getCov", "fPFOLIODATA") +S3method("getEstimator", "fPFOLIODATA") +S3method("getMu", "fPFOLIODATA") +S3method("getSigma", "fPFOLIODATA") +S3method("getTailRisk", "fPFOLIODATA") + + +S3method("plot", "fPORTFOLIO") +S3method("summary", "fPORTFOLIO") + +S3method("getData", "fPORTFOLIO") +S3method("getSeries", "fPORTFOLIO") +S3method("getNAssets", "fPORTFOLIO") +S3method("getUnits", "fPORTFOLIO") + +S3method("getStatistics", "fPORTFOLIO") +S3method("getMean", "fPORTFOLIO") +S3method("getCov", "fPORTFOLIO") +S3method("getEstimator", "fPORTFOLIO") +S3method("getMu", "fPORTFOLIO") +S3method("getSigma", "fPORTFOLIO") + +S3method("getSpec", "fPORTFOLIO") +S3method("getModel", "fPORTFOLIO") +S3method("getType", "fPORTFOLIO") +S3method("getOptimize", "fPORTFOLIO") +S3method("getEstimator", "fPORTFOLIO") +S3method("getTailRisk", "fPORTFOLIO") +S3method("getParams", "fPORTFOLIO") +S3method("getAlpha", "fPORTFOLIO") +S3method("getA", "fPORTFOLIO") + +S3method("getPortfolio", "fPORTFOLIO") +S3method("getWeights", "fPORTFOLIO") +S3method("getTargetReturn", "fPORTFOLIO") +S3method("getTargetRisk", "fPORTFOLIO") +S3method("getRiskFreeRate", "fPORTFOLIO") +S3method("getNFrontierPoints", "fPORTFOLIO") +S3method("getStatus", "fPORTFOLIO") + +S3method("getOptim", "fPORTFOLIO") +S3method("getSolver", "fPORTFOLIO") +S3method("getObjective", "fPORTFOLIO") +S3method("getOptions", "fPORTFOLIO") +S3method("getControl", "fPORTFOLIO") +S3method("getTrace", "fPORTFOLIO") +S3method("getCovRiskBudgets", "fPORTFOLIO") + +S3method("getConstraints", "fPORTFOLIO") +S3method("getTailRiskBudgets", "fPORTFOLIO") + + +S3method("getPortfolio", "fPFOLIOVAL") +S3method("getWeights", "fPFOLIOVAL") +S3method("getCovRiskBudgets", "fPFOLIOVAL") +S3method("getTargetReturn", "fPFOLIOVAL") +S3method("getTargetRisk", "fPFOLIOVAL") +S3method("getAlpha", "fPFOLIOVAL") +S3method("getRiskFreeRate", "fPFOLIOVAL") +S3method("getNFrontierPoints", "fPFOLIOVAL") +S3method("getStatus", "fPFOLIOVAL") + + +S3method("getModel", "fPFOLIOSPEC") +S3method("getType", "fPFOLIOSPEC") +S3method("getOptimize", "fPFOLIOSPEC") +S3method("getEstimator", "fPFOLIOSPEC") +S3method("getTailRisk", "fPFOLIOSPEC") +S3method("getParams", "fPFOLIOSPEC") +S3method("getAlpha", "fPFOLIOSPEC") +S3method("getA", "fPFOLIOSPEC") + +S3method("getPortfolio", "fPFOLIOSPEC") +S3method("getWeights", "fPFOLIOSPEC") +S3method("getTargetReturn", "fPFOLIOSPEC") +S3method("getTargetRisk", "fPFOLIOSPEC") +S3method("getRiskFreeRate", "fPFOLIOSPEC") +S3method("getNFrontierPoints", "fPFOLIOSPEC") +S3method("getStatus", "fPFOLIOSPEC") + +S3method("getOptim", "fPFOLIOSPEC") +S3method("getSolver", "fPFOLIOSPEC") +S3method("getObjective", "fPFOLIOSPEC") +S3method("getOptions", "fPFOLIOSPEC") +S3method("getControl", "fPFOLIOSPEC") +S3method("getTrace", "fPFOLIOSPEC") +S3method("getMessages", "fPFOLIOSPEC") + + +S3method("getWindows", "fPFOLIOBACKTEST") +S3method("getWindowsFun", "fPFOLIOBACKTEST") +S3method("getWindowsParams", "fPFOLIOBACKTEST") +S3method("getWindowsHorizon", "fPFOLIOBACKTEST") +S3method("getSmoother", "fPFOLIOBACKTEST") +S3method("getSmootherFun", "fPFOLIOBACKTEST") +S3method("getSmootherParams", "fPFOLIOBACKTEST") +S3method("getSmootherLambda", "fPFOLIOBACKTEST") +S3method("getSmootherDoubleSmoothing", "fPFOLIOBACKTEST") +S3method("getSmootherInitialWeights", "fPFOLIOBACKTEST") +S3method("getSmootherSkip", "fPFOLIOBACKTEST") +S3method("getStrategy", "fPFOLIOBACKTEST") +S3method("getStrategyFun", "fPFOLIOBACKTEST") +S3method("getStrategyParams", "fPFOLIOBACKTEST") +S3method("getMessages", "fPFOLIOBACKTEST") diff -Nru fportfolio-3011.81/R/mathprogLP-symphony.R fportfolio-3042.83/R/mathprogLP-symphony.R --- fportfolio-3011.81/R/mathprogLP-symphony.R 2014-10-30 14:13:57.000000000 +0000 +++ fportfolio-3042.83/R/mathprogLP-symphony.R 2015-11-10 13:43:32.000000000 +0000 @@ -120,8 +120,9 @@ # ----------------------------------------------------------------------------- -symphonyLP <- Rsymphony::Rsymphony_solve_LP - +symphonyLP <- function(...) { + Rsymphony::Rsymphony_solve_LP(...) +} # ----------------------------------------------------------------------------- diff -Nru fportfolio-3011.81/R/mathprogNLP.R fportfolio-3042.83/R/mathprogNLP.R --- fportfolio-3011.81/R/mathprogNLP.R 2014-10-30 14:13:57.000000000 +0000 +++ fportfolio-3042.83/R/mathprogNLP.R 2017-11-13 15:38:56.000000000 +0000 @@ -52,7 +52,7 @@ control <- list() # donlp2 Solver: - require(Rdonlp2) + # require(Rdonlp2) ans <- rdonlp2NLP(start, objective, lower, upper, linCons) ans @@ -62,7 +62,7 @@ ans # nlminb2 Solver: - require(Rnlminb2) + # require(Rnlminb2) ans <- rnlminb2NLP(start, objective, lower, upper, linCons) ans } diff -Nru fportfolio-3011.81/R/methods-show.R fportfolio-3042.83/R/methods-show.R --- fportfolio-3011.81/R/methods-show.R 2014-10-30 14:13:57.000000000 +0000 +++ fportfolio-3042.83/R/methods-show.R 2015-11-09 15:03:22.000000000 +0000 @@ -230,8 +230,9 @@ as.character(object@portfolio$nFrontierPoints)) } - cat("\n Status: ", - as.character(object@portfolio$status)) + if (!is.na(object@portfolio$status)) { + cat("\n Status: ", + as.character(object@portfolio$status)) } # Optimization: diff -Nru fportfolio-3011.81/R/monitor-stability.R fportfolio-3042.83/R/monitor-stability.R --- fportfolio-3011.81/R/monitor-stability.R 2014-10-30 14:13:57.000000000 +0000 +++ fportfolio-3042.83/R/monitor-stability.R 2017-11-13 15:40:52.000000000 +0000 @@ -243,7 +243,7 @@ # FUNCTION: # Load Library: - require(fGarch) + # require(fGarch) # Settings: stopifnot(isUnivariate(index)) @@ -397,7 +397,7 @@ # FUNCTION: # Load Library: - require(bcp) + # require(bcp) # Settings: stopifnot(isUnivariate(index)) @@ -486,7 +486,7 @@ # FUNCTION: # Load Library: - require(mvoutlier) + # require(mvoutlier) # Settings: stopifnot(isUnivariate(index)) @@ -653,7 +653,7 @@ # FUNCTION: # Load Library: - require(dplR) + # require(dplR) # Settings: stopifnot(isUnivariate(index)) @@ -726,8 +726,9 @@ coi2.yy <- c(coi2, rep(max(period2, na.rm=TRUE), length(coi2))) coi2.yy[is.na(coi2.yy)] <- coi[2] yr.vec.xx <- c(x, rev(x)) - par.orig <- par(c("mar", "las", "mfrow")) - on.exit(par(par.orig)) + # DW + # par.orig <- par(c("mar", "las", "mfrow")) + # on.exit(par(par.orig)) nlevels <- length(wavelet.levels) key.labs <- formatC(wavelet.levels, digits=4, format="f") asp <- NA @@ -737,15 +738,19 @@ ylim[2] <- ylim[2] * 1.1 # Image Plot: - plot.new() - plot.window(xlim, ylim, xaxs="r", yaxs="r") + # DW + # ... now you can create more than one plot on one page + # plot.new() + # plot.window(xlim, ylim, xaxs="r", yaxs="r") + # Use instead: + plot(xlim, ylim, xaxs = "r", yaxs = "r", + col = "white", axes=FALSE, frame=FALSE, ann=FALSE) # DW # .Internal(filledcontour()) no longer works on 3.0. # .Internal(filledcontour( - # as.double(x), as.double(period2), Power, - # as.double(wavelet.levels), col=key.cols)) - + # as.double(x), as.double(period2), Power, + # as.double(wavelet.levels), col=key.cols)) # Use instead: graphics::.filled.contour( x = as.double(x), @@ -760,12 +765,12 @@ # Add Contours: contour(x, period2, Signif, levels=1, labels=siglvl, - drawlabels=FALSE, axes=FALSE, frame.plot=FALSE, - add=TRUE, lwd=2, col="black") + drawlabels=FALSE, axes=FALSE, frame.plot=FALSE, + add=TRUE, lwd=2, col="black") # Add Coin of Influence: polygon(yr.vec.xx, coi2.yy, density=c(10, 20), - angle=c(-45, 45), col="black") + angle=c(-45, 45), col="black") # Add Axis Labels: xtick <- NULL diff -Nru fportfolio-3011.81/R/object-portfolioSpec.R fportfolio-3042.83/R/object-portfolioSpec.R --- fportfolio-3011.81/R/object-portfolioSpec.R 2014-10-30 14:13:57.000000000 +0000 +++ fportfolio-3042.83/R/object-portfolioSpec.R 2015-11-09 15:03:22.000000000 +0000 @@ -12,32 +12,42 @@ portfolioSpec <- function( model = list( - type = "MV", # Alt: "LPM", "CVaR" + type = "MV", # Alt: "LPM", "CVaR", "LPM" optimize = "minRisk", # Alt: "maxReturn" estimator = "covEstimator", # Alt: "shrinkEstimator", - # "lpmEstimator" tailRisk = list(), - params = list(alpha = 0.05, a = 1)), + ## I think the LPM a=1 we don't need. + ## params = list(alpha = 0.05, a = 1)), + ## This is CVaR's alpha it should not be removed here, it is + ## ... required in any situation when it comes to the calculation + ## ... of VaR and CVaR Risk + params = list(alpha = 0.05)), portfolio = list( + ## What is the here the meaning of NULL and what makes the + ## difference here between NULL and NA? + ## ... NULL means, None of the three weights = NULL, targetReturn = NULL, targetRisk = NULL, + # Risk Free rate ... riskFreeRate = 0, nFrontierPoints = 50, + ## Should not be prined if NA status = NA), optim = list( - solver = "solveRquadprog", # Alt: "solveRdonlp2" - # "solveRsolnp" - # "solveRglpk", - # "solveRsymphony" - # "solveRsocp" ... - objective = c( + solver = "solveRquadprog", # Alt: "solveRdonlp2" + # "solveRsolnp" + # "solveRglpk", + # "solveRsymphony" + # "solveRsocp" ... + objective = c( "portfolioObjective", "portfolioReturn", "portfolioRisk"), - options = list(meq = 2), - control = list(), - trace = FALSE), + ## Should not be printed if type != MV and solver != quadprog + options = list(meq = 2), + control = list(), + trace = FALSE), messages = list( messages = FALSE, note = ""), diff -Nru fportfolio-3011.81/R/object-setSpec.R fportfolio-3042.83/R/object-setSpec.R --- fportfolio-3011.81/R/object-setSpec.R 2014-10-30 14:13:57.000000000 +0000 +++ fportfolio-3042.83/R/object-setSpec.R 2015-11-09 15:03:22.000000000 +0000 @@ -43,15 +43,34 @@ # Description: # Sets the portfolio type for a portfolio structure - + + # Notes: + # What types are valid? + # MV Standard Mean-Variance Portfolio + # Objective = Covariance Risk + # Constraints = Budget 1'*W = 1 + # Allowed Constraints: Box + Group + # CVaR Standard Mean-CVaR portfolio + # Objective = Linearized CVaR Risk + # Constraints = Budget 1'*W = 1 + # Allowed Constraints: Box + Group + # Arguments: # FUNCTION: # Type ? - spec@model$type = value - if (value == "CVaR") setSolver(spec) <- "solveRglpk" - + spec@model$type <- value + message("Solver set to solveRquadprog") + + # Set Solver: + if (value == "MV") { + setSolver(spec) <- "solveRquadprog" + message("setSolver: solveRquadprog") } + if (value == "CVaR") { + setSolver(spec) <- "solveRglpk" + message("setSolver: solveRglpk") } + # Return Value: spec } @@ -73,7 +92,7 @@ # FUNCTION: # Type ? - spec@model$optimize = value + spec@model$optimize <- value # Return Value: spec @@ -96,7 +115,7 @@ # FUNCTION: # Estimator ? - spec@model$estimator = value + spec@model$estimator <- value # Return Value: spec @@ -142,9 +161,9 @@ # FUNCTION: # Weights ? - spec@portfolio$weights = value - spec@portfolio$targetReturn = NA - spec@portfolio$targetRisk = NA + spec@portfolio$weights <- value + spec@portfolio$targetReturn <- NA + spec@portfolio$targetRisk <- NA # Return Value: spec @@ -167,12 +186,12 @@ # FUNCTION: # Target Return ? - spec@portfolio$targetReturn = value - spec@portfolio$weights = NA - spec@portfolio$targetRisk = NA + spec@portfolio$targetReturn <- value + spec@portfolio$weights <- NA + spec@portfolio$targetRisk <- NA # What to optimize ? - spec@model$optimize = "minRisk" + spec@model$optimize <- "minRisk" # Return Value: spec @@ -194,13 +213,13 @@ # FUNCTION: - # Target Return ? - spec@portfolio$targetRisk = value - spec@portfolio$weights = NA - spec@portfolio$targetReturn = NA + # Target Risk ? + spec@portfolio$targetRisk <- value + spec@portfolio$weights <- NA + spec@portfolio$targetReturn <- NA # What to optimize ? - spec@model$optimize = "maxReturn" + spec@model$optimize <- "maxReturn" # Return Value: spec @@ -223,7 +242,7 @@ # FUNCTION: # Estimator ? - spec@model$params$alpha = value + spec@model$params$alpha <- value # Return Value: spec @@ -250,7 +269,7 @@ stopifnot(length(value) == 1) # Risk-Free Rate ? - spec@portfolio$riskFreeRate = value + spec@portfolio$riskFreeRate <- value # Return Value: spec @@ -278,7 +297,7 @@ stopifnot(value > 0) # Risk-Free Rate ? - spec@portfolio$nFrontierPoints = value + spec@portfolio$nFrontierPoints <- value # Return Value: spec @@ -305,7 +324,7 @@ stopifnot(length(value) == 1) # Risk-Free Rate ? - spec@portfolio$status = value + spec@portfolio$status <- value # Return Value: spec @@ -336,7 +355,7 @@ # FUNCTION: # Tail Risk ? - spec@model$tailRisk = value + spec@model$tailRisk <- value # Return Value: spec @@ -359,7 +378,7 @@ # FUNCTION: # Set Solver: - spec@optim$solver = value + spec@optim$solver <- value # Return Value: spec @@ -382,7 +401,7 @@ # FUNCTION: # Set Solver: - spec@optim$objective = value + spec@optim$objective <- value # Return Value: spec @@ -405,7 +424,7 @@ # FUNCTION: # Set Trace: - spec@optim$trace = value + spec@optim$trace <- value # Return Value: spec diff -Nru fportfolio-3011.81/R/portfolio-riskPfolio.R fportfolio-3042.83/R/portfolio-riskPfolio.R --- fportfolio-3011.81/R/portfolio-riskPfolio.R 2014-10-30 14:13:58.000000000 +0000 +++ fportfolio-3042.83/R/portfolio-riskPfolio.R 2015-11-09 15:03:22.000000000 +0000 @@ -16,50 +16,50 @@ ################################################################################ -# FUNCTION: DESCRIPTION: -# pfolioVaR Computes VaR for a portfolio of assets -# pfolioCVaR Computes CVaR for a portfoluio of assets -# pfolioCVaRplus Computes CVaR-Plus for a portfolio of assets -# lambdaCVaR Computes CVaR's atomic split value lambda -# FUNCTION: DESCRIPTION: -# pfolioMaxLoss Computes maximum loss for a portfolio -# pfolioReturn Computes return series for a portfolio -# pfolioTargetReturn Computes target return for a portfolio -# pfolioTargetRisk Computes target risk for a portfolio -# pfolioHist Plots a histogram of portfolio returns +# FUNCTION: DESCRIPTION: +# pfolioVaR Computes VaR for a portfolio of assets +# pfolioCVaR Computes CVaR for a portfoluio of assets +# pfolioCVaRplus Computes CVaR-Plus for a portfolio of assets +# lambdaCVaR Computes CVaR's atomic split value lambda +# pfolioCVaRoptim Computes CVaR from mean-CVaR portfolio optimization +# FUNCTION: DESCRIPTION: +# pfolioMaxLoss Computes maximum loss for a portfolio +# pfolioReturn Computes return series for a portfolio +# pfolioTargetReturn Computes target return for a portfolio +# pfolioTargetRisk Computes target risk for a portfolio +# pfolioHist Plots a histogram of portfolio returns ################################################################################ pfolioVaR <- -function(x, weights = NULL, alpha = 0.05) + function(x, weights = NULL, alpha = 0.05) { - # A function implemented by Diethelm Wuertz + # A function implemented by Diethelm Wuertz + + # Description: + # Compute Value-at-Risk for a portfolio of assets + + # Arguments: + # x - a time series, data.frame or any other rectangular object + # of assets which can be written as a matrix object + # weights - a numeric vector of weights + # alpha - the confidence level - # Description: - # Compute Value-at-Risk for a portfolio of assets + # FUNCTION: + + # Transform: + x <- as.matrix(x) - # Arguments: - # x - a time series, data.frame or any other rectangular object - # of assets which can be written as a matrix object - # weights - a numeric vector of weights - # alpha - the confidence level - - # FUNCTION: - - # Transform: - x <- as.matrix(x) - - # Compute Portfolio VaR: - if (is.null(weights)) - weights <- rep(1/dim(x)[[2]], dim(x)[[2]]) - n <- dim(x)[1] - x <- apply(t(t(x) * weights), 1, sum) - n.alpha <- max(floor(n * alpha)) - ans <- as.vector(sort(x)[n.alpha]) - names(ans) <- "VaR" + # Compute Portfolio VaR: + if (is.null(weights)) weights <- rep(1/dim(x)[[2]], dim(x)[[2]]) + n <- dim(x)[1] + x <- apply(t(t(x) * weights), 1, sum) + n.alpha <- max(floor(n * alpha)) + ans <- as.vector(sort(x)[n.alpha]) + names(ans) <- "VaR" - # Return Value: - ans + # Return Value: + ans } @@ -67,36 +67,34 @@ pfolioCVaRplus <- -function(x, weights = NULL, alpha = 0.05) + function(x, weights = NULL, alpha = 0.05) { - # A function implemented by Diethelm Wuertz + # A function implemented by Diethelm Wuertz + + # Description: + # Compute Value-at-Risk Plus for a portfolio of assets + + # Arguments: + # x - a time series, data.frame or any other rectangular object + # of assets which can be written as a matrix object + # weights - a numeric vector of weights + # alpha - the confidence level + + # FUNCTION: - # Description: - # Compute Value-at-Risk Plus for a portfolio of assets + # Transform: + x <- as.matrix(x) - # Arguments: - # x - a time series, data.frame or any other rectangular object - # of assets which can be written as a matrix object - # weights - a numeric vector of weights - # alpha - the confidence level - - # FUNCTION: - - # Transform: - x = as.matrix(x) - - # Compute Portfolio CVaRplus: - if (is.null(weights)) { - weights = rep(1/dim(x)[[2]], dim(x)[[2]]) - } - n = dim(x)[1] - x = apply(t(t(x) * weights), 1, sum) - n.alpha = max(1, floor(n * alpha)-1) - ans = as.vector(mean(sort(x)[1:n.alpha])) - names(ans) = "CVaRplus" + # Compute Portfolio CVaRplus: + if (is.null(weights)) weights = rep(1/dim(x)[[2]], dim(x)[[2]]) + n <- dim(x)[1] + x <- apply(t(t(x) * weights), 1, sum) + n.alpha <- max(1, floor(n * alpha)-1) + ans <- as.vector(mean(sort(x)[1:n.alpha])) + names(ans) <- "CVaRplus" - # Return Value: - ans + # Return Value: + ans } @@ -104,51 +102,49 @@ pfolioCVaR <- -function(x, weights = NULL, alpha = 0.05) + function(x, weights = NULL, alpha = 0.05) { - # A function implemented by Diethelm Wuertz + # A function implemented by Diethelm Wuertz + + # Description: + # Compute Conditional Value-at-risk for a portfolio of assets + + # Arguments: + # x - a time series, data.frame or any other rectangular object + # of assets which can be written as a matrix object + # weights - a numeric vector of weights + # alpha - the confidence level + # lambda - split value + + # FUNCTION: - # Description: - # Compute Conditional Value-at-risk for a portfolio of assets + # Transform: + data <- as.matrix(x) - # Arguments: - # x - a time series, data.frame or any other rectangular object - # of assets which can be written as a matrix object - # weights - a numeric vector of weights - # alpha - the confidence level - # lambda - split value - - # FUNCTION: - - # Transform: - data = as.matrix(x) - - # Input Data: - if (is.null(weights)) { - weights = rep(1/dim(data)[[2]], dim(data)[[2]]) - } - n = dim(data)[1] - Rp = apply(t(t(data)*weights), 1, sum) - - # Sort the Portfolio returns Y - sorted = sort(Rp) - - # Compute Portfolio VaR: - n.alpha = floor(n*alpha) - VaR = sorted[n.alpha] - - # Compute Portfolio CVaRplus: - n.alpha = max(1, floor(n*alpha)-1) - CVaRplus = mean(sorted[1:n.alpha]) - - # Compute Portfolio CVaR: - lambda = 1 - floor(n*alpha)/(n*alpha) - ans = as.vector(lambda*VaR + (1-lambda)*CVaRplus) - names(ans) = "CVaR" - attr(ans, "control") = c(CVaRplus = CVaRplus, lambda = lambda) + # Input Data: + if (is.null(weights)) weights = rep(1/dim(data)[[2]], dim(data)[[2]]) + n <- dim(data)[1] + Rp <- apply(t(t(data)*weights), 1, sum) + + # Sort the Portfolio returns Y + sorted <- sort(Rp) + + # Compute Portfolio VaR: + n.alpha <- floor(n*alpha) + VaR <- sorted[n.alpha] + + # Compute Portfolio CVaRplus: + n.alpha <- max(1, floor(n*alpha)-1) + CVaRplus <- mean(sorted[1:n.alpha]) + + # Compute Portfolio CVaR: + lambda <- 1 - floor(n*alpha)/(n*alpha) + ans <- as.vector(lambda*VaR + (1-lambda)*CVaRplus) + names(ans) <- "CVaR" + attr(ans, "control") = c(CVaRplus = CVaRplus, lambda = lambda) - # Return Value: - ans + # Return Value: + ans } @@ -156,25 +152,66 @@ lambdaCVaR <- -function(n, alpha = 0.05) + function(n, alpha = 0.05) { - # A function implemented by Diethelm Wuertz + # A function implemented by Diethelm Wuertz + + # Description: + # Computes CVaR's atomic split value lambda + + # Arguments: + # n - the number of oberservations + # alpha - the confidence interval + + # FUNCTION: + + # Compute CVaR lambda: + lambda <- 1 - floor(alpha * n) / (alpha * n) + names(lambda) <- "lambda" + + # Return Value: + lambda +} - # Description: - # Computes CVaR's atomic split value lambda - # Arguments: - # n - the number of oberservations - # alpha - the confidence interval +# ------------------------------------------------------------------------------ + + +pfolioCVaRoptim <- + function(x, weights = NULL, alpha=0.05) +{ + # A function implemented by Diethelm Wuertz + + # Description: + # Compute Conditional Value-at-risk by mean-CVaR portfolio Optimization - # FUNCTION: + # Arguments: + # x - a time series, data.frame or any other rectangular object + # of assets which can be written as a matrix object + # weights - a numeric vector of weights + # alpha - the confidence level - # Compute CVaR lambda: - lambda = 1 - floor(alpha * n) / (alpha * n) - names(lambda) = "lambda" + # FUNCTION: - # Return Value: - lambda + # Transform: + data <- as.matrix(x) + + if (is.null(weights)) weights <- rep(1/dim(data)[[2]], dim(data)[[2]]) + Rp <- apply(t(t(data) * weights), 1, sum) + .f <- function(VaR, data, weights, alpha) { + S <- nrow(data) + X <- apply(t(t(data) * weights), 1, sum) -VaR + CVaR <- VaR + sum((X - abs(X))/2) / S / alpha + CVaR } + + # Compute optimized CVaR: + ans <- optimize(.f, interval=range(Rp), tol=.Machine$double.eps, + maximum=TRUE, data=data, weights=weights, alpha=alpha) + ans <- ans$objective + names(ans) <- "CVaRoptim" + + # Return Value: + ans } @@ -182,33 +219,33 @@ pfolioMaxLoss <- -function(x, weights = NULL) + function(x, weights = NULL) { - # A function implemented by Diethelm Wuertz + # A function implemented by Diethelm Wuertz + + # Description: + # Computes maximum loss for a portfolio of assets + + # Arguments: + # x - a timeSeries, data.frame or any other rectangular object + # of assets which can be written as a matrix object + # weights - the vector of weights + # alpha - the confidence level - # Description: - # Computes maximum loss for a portfolio of assets + # FUNCTION: + + # Transform: + x <- as.matrix(x) - # Arguments: - # x - a timeSeries, data.frame or any other rectangular object - # of assets which can be written as a matrix object - # weights - the vector of weights - # alpha - the confidence level - - # FUNCTION: - - # Transform: - x = as.matrix(x) - - # Compute MaxLoss [MinReturn]: - if (is.null(weights)) { - weights = rep(1/dim(x)[[2]], dim(x)[[2]]) - } - x = apply(t(t(x)*weights), 1, sum) - ans = min(x) + # Compute MaxLoss [MinReturn]: + if (is.null(weights)) { + weights = rep(1/dim(x)[[2]], dim(x)[[2]]) + } + x = apply(t(t(x)*weights), 1, sum) + ans = min(x) - # Return Value: - ans + # Return Value: + ans } @@ -250,37 +287,33 @@ } -# ----------------------------------------------------------------------------- - - - # ------------------------------------------------------------------------------ pfolioTargetReturn <- -function(x, weights = NULL) + function(x, weights = NULL) { - # A function implemented by Diethelm Wuertz + # A function implemented by Diethelm Wuertz - # Description: - # Computes return value of a portfolio + # Description: + # Computes return value of a portfolio - # Arguments: - # x - a timeSeries, data.frame or any other rectangular object - # of assets which can be written as a matrix object - # weights - the vector of weights + # Arguments: + # x - a timeSeries, data.frame or any other rectangular object + # of assets which can be written as a matrix object + # weights - the vector of weights - # FUNCTION: + # FUNCTION: - # Transform: - x = as.matrix(x) + # Transform: + x <- as.matrix(x) - # Compute Portfolio Returns: - ans = mean(pfolioReturn(x = x, weights = weights)) + # Compute Portfolio Returns: + ans = mean(pfolioReturn(x = x, weights = weights)) - # Return Value: - names(ans) = "TargetReturn" - ans + # Return Value: + names(ans) = "TargetReturn" + ans } @@ -288,31 +321,31 @@ pfolioTargetRisk <- -function(x, weights = NULL) + function(x, weights = NULL) { - # A function implemented by Diethelm Wuertz + # A function implemented by Diethelm Wuertz - # Description: - # Computes risk from covariance matrix of a portfolio + # Description: + # Computes risk from covariance matrix of a portfolio - # Arguments: - # x - a timeSeries, data.frame or any other rectangular object - # of assets which can be written as a matrix object - # weights - the vector of weights + # Arguments: + # x - a timeSeries, data.frame or any other rectangular object + # of assets which can be written as a matrix object + # weights - the vector of weights - # FUNCTION: + # FUNCTION: - # Transform: - x = as.matrix(x) + # Transform: + x <- as.matrix(x) - # Compute Portfolio Returns: - if (is.null(weights)) - weights = rep(1/dim(x)[[2]], dim(x)[[2]]) - ans = as.vector(sqrt(weights %*% cov(x) %*% weights)) + # Compute Portfolio Returns: + if (is.null(weights)) + weights = rep(1/dim(x)[[2]], dim(x)[[2]]) + ans = as.vector(sqrt(weights %*% cov(x) %*% weights)) - # Return Value: - names(ans) = "TargetRisk" - ans + # Return Value: + names(ans) = "TargetRisk" + ans } @@ -320,80 +353,80 @@ pfolioHist <- -function(x, weights = NULL, alpha = 0.05, range = NULL, details = TRUE, ...) + function(x, weights = NULL, alpha = 0.05, range = NULL, details = TRUE, ...) { - # A function implemented by Diethelm Wuertz + # A function implemented by Diethelm Wuertz - # Description: - # Plots a histogram of the returns of a portfolio + # Description: + # Plots a histogram of the returns of a portfolio + + # Arguments: + # x - a timeSeries, data.frame or any other rectangular object + # of assets which can be written as a matrix object + # weights - the vector of weights + + # FUNCTION: - # Arguments: - # x - a timeSeries, data.frame or any other rectangular object - # of assets which can be written as a matrix object - # weights - the vector of weights - - # FUNCTION: - - # Transform: - x = as.matrix(x) - - # Suppress Warnings: - opt = options() - options(warn = -1) - - # Plot Portfolio Returns: - Returns = pfolioReturn(x = x, weights = weights) - if (is.null(range)) { - lim = 1.05 * pfolioMaxLoss(x = x, weights = weights)[[1]] - xlim = c(lim, -lim) - } else { - xlim = range - } - Histogram = hist(Returns, xlim = xlim, xlab = "Portfolio Return %", - probability = TRUE, col = "steelblue4", border = "white", ...) - r = seq(xlim[1], xlim[2], length = 201) - lines(r, dnorm(r, mean = mean(Returns), sd = sd(Returns)), ...) - - points(Returns, rep(0, length(Returns)), pch = 20, - col = "orange", cex = 1.25) - - # Add VaR, CVaRplus and MaxLoss: - V1 = pfolioVaR(x = x, weights = weights, alpha = alpha)[[1]] - abline(v = V1, col = "blue", ...) - V2 = pfolioCVaRplus(x = x, weights = weights, alpha = alpha)[[1]] - abline(v = V2, col = "red", ...) - V3 = pfolioMaxLoss(x = x, weights = weights)[[1]] - abline(v = V3, col = "green", ...) - V4 = as.vector(mean(Returns))[[1]] - V5 = as.vector(sd(Returns))[[1]] - - yt = max(density(Returns)$y) - - text(V1, yt, as.character(round(V1, 2)), cex = 0.75, col = "orange") - text(V2, yt, as.character(round(V2, 2)), cex = 0.75, col = "orange") - text(V3, yt, as.character(round(V3, 2)), cex = 0.75, col = "orange") - text(V4, yt, as.character(round(V4, 2)), cex = 0.75, col = "orange") - - yt = 0.95 * yt - text(V1, yt, "VaR", cex = 0.75, col = "orange") - text(V2, yt, "CVaR+", cex = 0.75, col = "orange") - text(V3, yt, "maxLoss", cex = 0.75, col = "orange") - text(V4, yt, "Mean", cex = 0.75, col = "orange") - - # Result: - options(opt) - ans = list(VaR = V1, VaRplus = V2, maxLoss = V3, mean = V4, sd = V5) - if (details) { - cat("\nVaR: ", V1) - cat("\nVaRplus: ", V2) - cat("\nmax Loss: ", V3) - cat("\nMean: ", V4) - cat("\nStDev: ", V5) - cat("\n") - } + # Transform: + x <- as.matrix(x) - # Return Value: - invisible(ans) + # Suppress Warnings: + opt = options() + options(warn = -1) + + # Plot Portfolio Returns: + Returns = pfolioReturn(x = x, weights = weights) + if (is.null(range)) { + lim = 1.05 * pfolioMaxLoss(x = x, weights = weights)[[1]] + xlim = c(lim, -lim) + } else { + xlim = range + } + Histogram = hist(Returns, xlim = xlim, xlab = "Portfolio Return %", + probability = TRUE, col = "steelblue4", border = "white", ...) + r = seq(xlim[1], xlim[2], length = 201) + lines(r, dnorm(r, mean = mean(Returns), sd = sd(Returns)), ...) + + points(Returns, rep(0, length(Returns)), pch = 20, + col = "orange", cex = 1.25) + + # Add VaR, CVaRplus and MaxLoss: + V1 = pfolioVaR(x = x, weights = weights, alpha = alpha)[[1]] + abline(v = V1, col = "blue", ...) + V2 = pfolioCVaRplus(x = x, weights = weights, alpha = alpha)[[1]] + abline(v = V2, col = "red", ...) + V3 = pfolioMaxLoss(x = x, weights = weights)[[1]] + abline(v = V3, col = "green", ...) + V4 = as.vector(mean(Returns))[[1]] + V5 = as.vector(sd(Returns))[[1]] + + yt = max(density(Returns)$y) + + text(V1, yt, as.character(round(V1, 2)), cex = 0.75, col = "orange") + text(V2, yt, as.character(round(V2, 2)), cex = 0.75, col = "orange") + text(V3, yt, as.character(round(V3, 2)), cex = 0.75, col = "orange") + text(V4, yt, as.character(round(V4, 2)), cex = 0.75, col = "orange") + + yt = 0.95 * yt + text(V1, yt, "VaR", cex = 0.75, col = "orange") + text(V2, yt, "CVaR+", cex = 0.75, col = "orange") + text(V3, yt, "maxLoss", cex = 0.75, col = "orange") + text(V4, yt, "Mean", cex = 0.75, col = "orange") + + # Result: + options(opt) + ans = list(VaR = V1, VaRplus = V2, maxLoss = V3, mean = V4, sd = V5) + if (details) { + cat("\nVaR: ", V1) + cat("\nVaRplus: ", V2) + cat("\nmax Loss: ", V3) + cat("\nMean: ", V4) + cat("\nStDev: ", V5) + cat("\n") + } + + # Return Value: + invisible(ans) } diff -Nru fportfolio-3011.81/R/risk-tailBudgets.R fportfolio-3042.83/R/risk-tailBudgets.R --- fportfolio-3011.81/R/risk-tailBudgets.R 2014-10-30 14:13:58.000000000 +0000 +++ fportfolio-3042.83/R/risk-tailBudgets.R 2016-04-14 14:02:44.000000000 +0000 @@ -1,585 +1,584 @@ - -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Library General Public -# License as published by the Free Software Foundation; either -# version 2 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Library General Public License for more details. -# -# You should have received a copy of the GNU Library General -# Public License along with this library; if not, write to the -# Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, -# MA 02111-1307 USA - - -################################################################################ -# FUNCTION: DESCRIPTION: -# .tailDependenceCoeffs Returns Lower and Upper Tail Dependence Coeffs -# FUNCTION: MIXED GUMBEL-SURVIVALGUMBEL-NORMAL COPULA: -# .rgsgnormCopula Generates G-SG-NORM copula random variates -# .dgsgnormCopula Computes G-SG-NORM copula density -# FUNCTION: MIXED G-SG-NORM COPULA FIT: -# .gsgnormCopulaFit Estimates the parameters of the G-SG-NORM copula -# FUNCTION: NON-PARAMETRIC TAIL DEPENDECY ESTIMATOR: -# .cfgTDE Estimates non-parametrically tail dependence -# FUNCTION: COPULA FIT WITH NORM, NIG OR GHT MARGINALS: -# .empiricalDependencyFit Estimates tail dependence with empirical marginals -# .normDependencyFit Estimates tail dependence with normal marginals -# .nigDependencyFit Estimates tail dependence with NIG marginals -# .ghtDependencyFit Estimates tail dependence with GHT marginals -################################################################################ - - -.tailDependenceCoeffs <- - function(x, method = c("nig", "norm", "ght"), - trace = FALSE, doplot = TRUE) -{ - # A function implemented by Diethelm Wuertz - - # Description: - # Returns a list with lower and upper bivariate tail depenence matrixes - - # Example: - # x <- 100 * LPP2005.RET[, 1:6]; .tailDependenceCoeffs(x) - - # Notes: - # Tested only for NIG marginal distributions. - - # FUNCTION: - - # Check Settings: - method <- match.arg(method) - - # Compute Coeffs with desired Marginals: - fun <- paste(".", method, "DependencyFit", sep = "") - funFit <- match.fun(fun) - coeffs <- funFit(x, doplot = doplot, trace = trace) - - # Return Value: - coeffs -} - - -################################################################################ - - -.rgsgnormCopula <- - function(n = 1000, alpha = c(2, 2), rho = 0, weights = c(1/3, 1/3)) -{ - # A function implemented by Diethelm Wuertz - - # Description: - # Computes RVs from a mixed Gumbel-SurvivalGumbel-Normal Copula - - # Arguments: - # n - an integer value, the number of random variates to be - # generated. - # alpha - a numeric vector with two entries. The first denotes - # the parameter value of alpha for the Gumbel copula, and - # the second for the Survival Gumbel Copula. - # rho - a numeric value denoting the correlation parameter for - # the normal copula. - # weights - a numeric vector with two entries. The first denotes - # the weight of the Gumbel copula, and the second the weight - # of the Survival Gumbel Copula. The weight for the normal - # copula is evaluated by 1 - sum(weights). - - # Example: - # .rgsgnormCopula(20) - - # FUNCTION: - - # Checking: - stopifnot(any(weights >= 0)) - stopifnot(sum(weights) <= 1) - - # Upper Gumbel = 1 , Lower Gumbel = 2, t = 3: - weights <- c(weights, 1-sum(weights)) - N <- round(n*weights[1:2]) - N <- c(N, n-sum(N)) - - # Random Variates: - r <- rbind( - if (N[1] > 0) fCopulae::rgumbelCopula(N[1], alpha[1]), - if (N[2] > 0) 1-fCopulae::rgumbelCopula(N[2], alpha[2]), - if (N[3] > 0) fCopulae::rellipticalCopula(N[3], rho, type = "norm") ) - index <- sample(1:n) - ans <- r[index, ] - - N <- c(n, N) - names(N) <- c("n", "n1", "n2", "n3") - attr(ans, "control") < -N - - # Return Value: - ans -} - - -# ------------------------------------------------------------------------------ - - -.dgsgnormCopula <- - function(u = 0.5, v = u, alpha = c(2, 2), rho = 0, weights = c(1/3, 1/3), - output = c("vector", "list")) -{ - # A function implemented by Diethelm Wuertz - - # Description: - # Computes mixed Gumbel-SurvivalGumbel-Normal Copula density - - # Example: - # .perspPlot(.dgsgnormCopula(u=grid2d()$x, v=grid2d()$y, output = "list")) - - # FUNCTION: - - # Settings: - if (is.list(u)) { - v = u[[2]] - u = u[[1]] - } - if (is.matrix(u)) { - v = u[, 1] - u = u[, 2] - } - - # Match Arguments: - output = match.arg(output) - - # Mixed Copula: - weights <- c(weights, 1-sum(weights)) - dCopula1 <- fCopulae::dgumbelCopula(u, v, alpha[1]) - dCopula2 <- fCopulae::dgumbelCopula(1-u, 1-v, alpha[2]) - dCopula3 <- fCopulae::dellipticalCopula(u, v, rho, type = "norm") - c.uv <- weights[1]*dCopula1 + weights[2]*dCopula2 + weights[3]*dCopula3 - - attr(c.uv, "control") <- c(alpha = alpha, rho = rho, weights = weights) - if (output == "list") { - N = sqrt(length(u)) - x = u[1:N] - y = matrix(v, ncol = N)[1, ] - c.uv = list(x = x, y = y, z = matrix(c.uv, ncol = N)) - } - - # Return Value: - c.uv -} - - -# ------------------------------------------------------------------------------ - - -.gsgnormCopulaFit <- - function(u, v = NULL, trace = FALSE) -{ - # A function implemented by Diethelm Wuertz - - # Description: - # Fits parameters for a mixed GSG copula - - # FUNCTION: - - # Settings: - U <- u - V <- v - if (is.list(u)) { - U = u[[1]] - V = u[[2]] - } - if (is.matrix(u)) { - U = u[, 1] - V = u[, 2] - } - - # From weights to gamma ... - # G-SG-NORM: W1*Gumbel + W2*SurvivalGumbul + W3*NORM - # with W3 = 1-W2-W3 - # Transformation: Use Weights W1 and W3 - # gamma = c(gamma1, gamma2) - # 0 < gamma1 = W1/(1-W3) < 1 - # 0 < gamma2 = 1-W3 < 1 - # W3 = 1-gamma2 - # W1 = gamma1*gamma2 - # W2 = gamma2*(1-gamma1) - # Note, this transformation has the advantage, that gamma1 - # and gamma2 are independent from each other. - - # Estimate Copula: - start = c(alpha1 = 1.5, alpha2 = 1.5, rho = 0, gamma1 = 1/2, gamma2 = 1/2) - fun = function(x, U, V, trace) - { - alpha = x[1:2] - rho = x[3] - gamma = x[4:5] - weights = c( - weights1 = gamma[[1]]*gamma[[2]], - weights2 = gamma[[2]]*(1-gamma[[1]])) - - density = .dgsgnormCopula(u = U, v = V, alpha, rho, weights = weights) - - density = density[!is.na(density)] - f = -mean( log(density) ) - if (trace) { - params = round(c(x[1:3], - weights[1], weights[2], 1-weights[1]-weights[2]), 4) - names(params) = c("alpha1", "alpha2", "rho", - "gumbel", "survival", "norm") - cat("\n Objective Function Value: ", -f) - cat("\n Parameter Estimates: ", params, "\n") - - } - f - } - - # Fit: - fit = nlminb( - start = start, objective = fun, - lower = c( 1, 1, -0.999, 0, 0), - upper = c(Inf, Inf, 0.999, 1, 1), U = U, V = V, trace = trace) - - # Fitted Parameters: - param = fit$par - - # Named Parameters: - alpha1 = param[1] - alpha2 = param[2] - rho = param[3] - gamma1 = param[4] - gamma2 = param[5] - - # Weights: - weights3 = 1-gamma2 - weights1 = gamma1*gamma2 - weights2 = gamma2*(1-gamma1) - - # Tail Coefficients - upperLambda = (weights1*(2 - 2^(1/alpha1)))[[1]] - lowerLambda = (weights2*(2 - 2^(1/alpha2)))[[1]] - params = c(param[1:3], param[5]*param[4], param[5]*(1-param[4]), 1-param[5]) - names(params) = c("alpha1", "alpha2", "rho", "gumbel", "survival", "norm") - Lambda = c(lower = lowerLambda, upper = upperLambda) - - # Return Value: - list(param = params, lambda = Lambda, fitted = fit$par) -} - - -################################################################################ - - -.cfgTDE <- - function(x, y) -{ - # A function implemented by Diethelm Wuertz - - # Description: - # Estimates non-parametrically tail dependency coefficient - - # FUNCTION: - - # Upper Tail: - lambda = NULL - n = length(x) - for(i in 1:n){ - lambda = c(lambda, - log(sqrt(log(1/x[i])*log(1/y[i]))/log(1/max(x[i],y[i])^2))) - } - upper <- 2 - 2*exp(sum(lambda/n)) - - # Lower Tail: - x = 1-x - y = 1-y - lambda = NULL - n = length(x) - for(i in 1:n){ - lambda = c(lambda, - log(sqrt(log(1/x[i])*log(1/y[i]))/log(1/max(x[i],y[i])^2))) - } - lower <- 2 - 2*exp(sum(lambda/n)) - - # Return Value: - c(lower = lower, upper = upper) -} - - -################################################################################ - - -.empiricalDependencyFit <- - function(x, doplot = TRUE, trace = FALSE) -{ - # A function implemented by Diethelm Wuertz - - # Description: - # Estimates tail dependency coefficients with Normal marginals - - # Arguments: - # x - a multivariate 'timeSeries' object - - # FUNCTION: - - # Settings: - N = ncol(x) - lowerLambda = upperLambda = 0*diag(N) - assetsNames = colnames(x) - P = NULL - - for (i in 1:(N-1)) { - # First asset: - r1 = as.vector(x[, i]) - fit1 = nFit(r1) - estim1 = fit1@fit$estimate - p1 = pnorm(r1, estim1[1], estim1[2]) - Main1 = assetsNames[i] - P = cbind(P, p1) - for (j in (i+1):N) - { - # Second asset: - r2 = as.vector(x[, j]) - fit2 = nFit(r2) - estim2 = fit2@fit$estimate - p2 = pnorm(r2, estim2[1], estim2[2]) - Main2 = assetsNames[j] - # Optional Plot: - if (doplot) - { - # Plot Distribution: - MainR = paste("Distribution:", Main1, "-", Main2) - plot(r1, r2, pch = 19, main = MainR) - grid() - - # Plot Copula: - MainP = paste("Copula:", Main1, "-", Main2) - plot(p1, p2, pch = 19, main = MainP) - grid() - } - - # Fit GSG copula parameters: - fit = .gsgnormCopulaFit(u = p1, v = p2, trace = trace) - if (trace) - cat(assetsNames[c(i,j)], round(fit$lambda, 3), "\n") - - # Compose lambda Matrix: - lowerLambda[i, j] = lowerLambda[j, i] = fit$lambda[1] - upperLambda[i, j] = upperLambda[j, i] = fit$lambda[2] - } - } - - # Result: - colnames(lowerLambda) = rownames(lowerLambda) = assetsNames - colnames(upperLambda) = rownames(upperLambda) = assetsNames - ans = list(lower = lowerLambda, upper = upperLambda) - - # Return Value: - ans -} - - -# ------------------------------------------------------------------------------ - - -.normDependencyFit <- - function(x, doplot = TRUE, trace = FALSE) -{ - # A function implemented by Diethelm Wuertz - - # Description: - # Estimates tail dependency coefficients with Normal marginals - - # Arguments: - # x - a multivariate 'timeSeries' object - - # FUNCTION: - - # Settings: - N = ncol(x) - lowerLambda = upperLambda = 0*diag(N) - assetsNames = colnames(x) - P = NULL - - for (i in 1:(N-1)) { - # First asset: - r1 = as.vector(x[, i]) - fit1 = nFit(r1) - estim1 = fit1@fit$estimate - p1 = pnorm(r1, estim1[1], estim1[2]) - Main1 = assetsNames[i] - P = cbind(P, p1) - for (j in (i+1):N) - { - # Second asset: - r2 = as.vector(x[, j]) - fit2 = nFit(r2) - estim2 = fit2@fit$estimate - p2 = pnorm(r2, estim2[1], estim2[2]) - Main2 = assetsNames[j] - # Optional Plot: - if (doplot) - { - # Plot Distribution: - MainR = paste("Distribution:", Main1, "-", Main2) - plot(r1, r2, pch = 19, main = MainR) - grid() - - # Plot Copula: - MainP = paste("Copula:", Main1, "-", Main2) - plot(p1, p2, pch = 19, main = MainP) - grid() - } - - # Fit GSG copula parameters: - fit = .gsgnormCopulaFit(u = p1, v = p2, trace = trace) - if (trace) - cat(assetsNames[c(i,j)], round(fit$lambda, 3), "\n") - # Compose lambda Matrix: - lowerLambda[i, j] = lowerLambda[j, i] = fit$lambda[1] - upperLambda[i, j] = upperLambda[j, i] = fit$lambda[2] - } - } - - # Result: - colnames(lowerLambda) = rownames(lowerLambda) = assetsNames - colnames(upperLambda) = rownames(upperLambda) = assetsNames - ans = list(lower = lowerLambda, upper = upperLambda) - - # Return Value: - ans -} - - -# ------------------------------------------------------------------------------ - - -.nigDependencyFit <- - function(x, doplot = TRUE, trace = FALSE) -{ - # A function implemented by Diethelm Wuertz - - # Description: - # Estimates tail dependency coefficients with NIG marginals - - # Arguments: - # x - a multivariate 'timeSeries' object - - # FUNCTION: - - # Settings: - N = ncol(x) - lowerLambda = upperLambda = 0*diag(N) - assetsNames = colnames(x) - P = NULL - - for (i in 1:(N-1)) { - # First asset: - r1 = as.vector(x[, i]) - fit1 = nigFit(r1, doplot = FALSE, trace = trace) - estim1 = fit1@fit$estimate - p1 = .pnigC(r1, estim1[1], estim1[2], estim1[3], estim1[4]) - Main1 = assetsNames[i] - P = cbind(P, p1) - for (j in (i+1):N) { - # Second asset: - r2 = as.vector(x[, j]) - fit2 = nigFit(r2, doplot = FALSE, trace = trace) - estim2 = fit2@fit$estimate - p2 = .pnigC(r2, estim2[1], estim2[2], estim2[3], estim2[4]) - Main2 = assetsNames[j] - # Optional Plot: - if (doplot) { - ## MainR = paste("Distribution:", Main1, "-", Main2) - ## plot(r1, r2, pch = 19, main = MainR) - ## grid() - MainP = paste("Copula:", Main1, "-", Main2) - plot(p1, p2, pch = 19, main = MainP, xlab = "", ylab = "") - grid() - } - # Fit GSG copula parameters: - fit = .gsgnormCopulaFit(u = p1, v = p2, trace = trace) - if (trace) - cat(assetsNames[c(i,j)], round(fit$lambda, 3), "\n") - # Compose lambda Matrix: - lowerLambda[i, j] = lowerLambda[j, i] = fit$lambda[1] - upperLambda[i, j] = upperLambda[j, i] = fit$lambda[2] - } - } - - # Result: - colnames(lowerLambda) = rownames(lowerLambda) = assetsNames - colnames(upperLambda) = rownames(upperLambda) = assetsNames - ans = list(lower = lowerLambda, upper = upperLambda) - - # Return Value: - ans -} - - -# ------------------------------------------------------------------------------ - - -.ghtDependencyFit <- - function(x, doplot = TRUE, trace = FALSE) -{ - # A function implemented by Diethelm Wuertz - - # Description: - # Estimates tail dependency coefficients with GH Student-t marginals - - # Arguments: - # x - a multivariate 'timeSeries' object - - # FUNCTION: - - # Settings: - N = ncol(x) - lowerLambda = upperLambda = 0*diag(N) - assetsNames = colnames(x) - P = NULL - - for (i in 1:(N-1)) { - # First asset: - r1 = as.vector(x[, i]) - fit1 = ghtFit(r1, doplot = FALSE, trace = trace) - estim1 = fit1@fit$estimate - p1 = pght(r1, estim1[1], estim1[2], estim1[3], estim1[4]) - Main1 = assetsNames[i] - P = cbind(P, p1) - for (j in (i+1):N) { - # Second asset: - r2 = as.vector(x[, j]) - fit2 = ghtFit(r2, doplot = FALSE, trace = trace) - estim2 = fit2@fit$estimate - p2 = pght(r2, estim2[1], estim2[2], estim2[3], estim2[4]) - Main2 = assetsNames[j] - # Optional Plot: - if (doplot) { - MainR = paste("Distribution:", Main1, "-", Main2) - plot(r1, r2, pch = 19, main = MainR) - grid() - MainP = paste("Copula:", Main1, "-", Main2) - plot(p1, p2, pch = 19, main = MainP) - grid() - } - # Fit GSG copula parameters: - fit = .gsgnormCopulaFit(u = p1, v = p2, trace = trace) - if (trace) - cat(assetsNames[c(i,j)], round(fit$lambda, 3), "\n") - # Compose lambda Matrix: - lowerLambda[i, j] = lowerLambda[j, i] = fit$lambda[1] - upperLambda[i, j] = upperLambda[j, i] = fit$lambda[2] - } - } - - # Result: - colnames(lowerLambda) = rownames(lowerLambda) = assetsNames - colnames(upperLambda) = rownames(upperLambda) = assetsNames - ans = list(lower = lowerLambda, upper = upperLambda) - - # Return Value: - ans -} - - -################################################################################ - + +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Library General Public +# License as published by the Free Software Foundation; either +# version 2 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Library General Public License for more details. +# +# You should have received a copy of the GNU Library General +# Public License along with this library; if not, write to the +# Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, +# MA 02111-1307 USA + + +################################################################################ +# FUNCTION: DESCRIPTION: +# .tailDependenceCoeffs Returns Lower and Upper Tail Dependence Coeffs +# FUNCTION: MIXED GUMBEL-SURVIVALGUMBEL-NORMAL COPULA: +# .rgsgnormCopula Generates G-SG-NORM copula random variates +# .dgsgnormCopula Computes G-SG-NORM copula density +# FUNCTION: MIXED G-SG-NORM COPULA FIT: +# .gsgnormCopulaFit Estimates the parameters of the G-SG-NORM copula +# FUNCTION: NON-PARAMETRIC TAIL DEPENDECY ESTIMATOR: +# .cfgTDE Estimates non-parametrically tail dependence +# FUNCTION: COPULA FIT WITH NORM, NIG OR GHT MARGINALS: +# .empiricalDependencyFit Estimates tail dependence with empirical marginals +# .normDependencyFit Estimates tail dependence with normal marginals +# .gldDependencyFit Estimates tail dependence with GLD marginals +# .ghtDependencyFit Estimates tail dependence with GHT marginals +################################################################################ + + +.tailDependenceCoeffs <- + function(x, method = c("nig", "norm", "ght"), + trace = FALSE, doplot = TRUE) +{ + # A function implemented by Diethelm Wuertz + + # Description: + # Returns a list with lower and upper bivariate tail depenence matrixes + + # Example: + # x <- 100 * LPP2005.RET[, 1:6]; .tailDependenceCoeffs(x) + + # Notes: + # Tested only for NIG marginal distributions. + + # FUNCTION: + + # Check Settings: + method <- match.arg(method) + + # Compute Coeffs with desired Marginals: + fun <- paste(".", method, "DependencyFit", sep = "") + funFit <- match.fun(fun) + coeffs <- funFit(x, doplot = doplot, trace = trace) + + # Return Value: + coeffs +} + + +################################################################################ + + +.rgsgnormCopula <- + function(n = 1000, alpha = c(2, 2), rho = 0, weights = c(1/3, 1/3)) +{ + # A function implemented by Diethelm Wuertz + + # Description: + # Computes RVs from a mixed Gumbel-SurvivalGumbel-Normal Copula + + # Arguments: + # n - an integer value, the number of random variates to be + # generated. + # alpha - a numeric vector with two entries. The first denotes + # the parameter value of alpha for the Gumbel copula, and + # the second for the Survival Gumbel Copula. + # rho - a numeric value denoting the correlation parameter for + # the normal copula. + # weights - a numeric vector with two entries. The first denotes + # the weight of the Gumbel copula, and the second the weight + # of the Survival Gumbel Copula. The weight for the normal + # copula is evaluated by 1 - sum(weights). + + # Example: + # .rgsgnormCopula(20) + + # FUNCTION: + + # Checking: + stopifnot(any(weights >= 0)) + stopifnot(sum(weights) <= 1) + + # Upper Gumbel = 1 , Lower Gumbel = 2, t = 3: + weights <- c(weights, 1-sum(weights)) + N <- round(n*weights[1:2]) + N <- c(N, n-sum(N)) + + # Random Variates: + r <- rbind( + if (N[1] > 0) fCopulae::rgumbelCopula(N[1], alpha[1]), + if (N[2] > 0) 1-fCopulae::rgumbelCopula(N[2], alpha[2]), + if (N[3] > 0) fCopulae::rellipticalCopula(N[3], rho, type = "norm") ) + index <- sample(1:n) + ans <- r[index, ] + + N <- c(n, N) + names(N) <- c("n", "n1", "n2", "n3") + attr(ans, "control") < -N + + # Return Value: + ans +} + + +# ------------------------------------------------------------------------------ + + +.dgsgnormCopula <- + function(u = 0.5, v = u, alpha = c(2, 2), rho = 0, weights = c(1/3, 1/3), + output = c("vector", "list")) +{ + # A function implemented by Diethelm Wuertz + + # Description: + # Computes mixed Gumbel-SurvivalGumbel-Normal Copula density + + # Example: + # .perspPlot(.dgsgnormCopula(u=grid2d()$x, v=grid2d()$y, output = "list")) + + # FUNCTION: + + # Settings: + if (is.list(u)) { + v = u[[2]] + u = u[[1]] + } + if (is.matrix(u)) { + v = u[, 1] + u = u[, 2] + } + + # Match Arguments: + output = match.arg(output) + + # Mixed Copula: + weights <- c(weights, 1-sum(weights)) + dCopula1 <- fCopulae::dgumbelCopula(u, v, alpha[1]) + dCopula2 <- fCopulae::dgumbelCopula(1-u, 1-v, alpha[2]) + dCopula3 <- fCopulae::dellipticalCopula(u, v, rho, type = "norm") + c.uv <- weights[1]*dCopula1 + weights[2]*dCopula2 + weights[3]*dCopula3 + + attr(c.uv, "control") <- c(alpha = alpha, rho = rho, weights = weights) + if (output == "list") { + N = sqrt(length(u)) + x = u[1:N] + y = matrix(v, ncol = N)[1, ] + c.uv = list(x = x, y = y, z = matrix(c.uv, ncol = N)) + } + + # Return Value: + c.uv +} + + +# ------------------------------------------------------------------------------ + + +.gsgnormCopulaFit <- + function(u, v = NULL, trace = FALSE) +{ + # A function implemented by Diethelm Wuertz + + # Description: + # Fits parameters for a mixed GSG copula + + # FUNCTION: + + # Settings: + U <- u + V <- v + if (is.list(u)) { + U = u[[1]] + V = u[[2]] + } + if (is.matrix(u)) { + U = u[, 1] + V = u[, 2] + } + + # From weights to gamma ... + # G-SG-NORM: W1*Gumbel + W2*SurvivalGumbul + W3*NORM + # with W3 = 1-W2-W3 + # Transformation: Use Weights W1 and W3 + # gamma = c(gamma1, gamma2) + # 0 < gamma1 = W1/(1-W3) < 1 + # 0 < gamma2 = 1-W3 < 1 + # W3 = 1-gamma2 + # W1 = gamma1*gamma2 + # W2 = gamma2*(1-gamma1) + # Note, this transformation has the advantage, that gamma1 + # and gamma2 are independent from each other. + + # Estimate Copula: + start = c(alpha1 = 1.5, alpha2 = 1.5, rho = 0, gamma1 = 1/2, gamma2 = 1/2) + fun = function(x, U, V, trace) + { + alpha = x[1:2] + rho = x[3] + gamma = x[4:5] + weights = c( + weights1 = gamma[[1]]*gamma[[2]], + weights2 = gamma[[2]]*(1-gamma[[1]])) + + density = .dgsgnormCopula(u = U, v = V, alpha, rho, weights = weights) + + density = density[!is.na(density)] + f = -mean( log(density) ) + if (trace) { + params = round(c(x[1:3], + weights[1], weights[2], 1-weights[1]-weights[2]), 4) + names(params) = c("alpha1", "alpha2", "rho", + "gumbel", "survival", "norm") + cat("\n Objective Function Value: ", -f) + cat("\n Parameter Estimates: ", params, "\n") + + } + f + } + + # Fit: + fit = nlminb( + start = start, objective = fun, + lower = c( 1, 1, -0.999, 0, 0), + upper = c(Inf, Inf, 0.999, 1, 1), U = U, V = V, trace = trace) + + # Fitted Parameters: + param = fit$par + + # Named Parameters: + alpha1 = param[1] + alpha2 = param[2] + rho = param[3] + gamma1 = param[4] + gamma2 = param[5] + + # Weights: + weights3 = 1-gamma2 + weights1 = gamma1*gamma2 + weights2 = gamma2*(1-gamma1) + + # Tail Coefficients + upperLambda = (weights1*(2 - 2^(1/alpha1)))[[1]] + lowerLambda = (weights2*(2 - 2^(1/alpha2)))[[1]] + params = c(param[1:3], param[5]*param[4], param[5]*(1-param[4]), 1-param[5]) + names(params) = c("alpha1", "alpha2", "rho", "gumbel", "survival", "norm") + Lambda = c(lower = lowerLambda, upper = upperLambda) + + # Return Value: + list(param = params, lambda = Lambda, fitted = fit$par) +} + + +################################################################################ + + +.cfgTDE <- + function(x, y) +{ + # A function implemented by Diethelm Wuertz + + # Description: + # Estimates non-parametrically tail dependency coefficient + + # FUNCTION: + + # Upper Tail: + lambda = NULL + n = length(x) + for(i in 1:n){ + lambda = c(lambda, + log(sqrt(log(1/x[i])*log(1/y[i]))/log(1/max(x[i],y[i])^2))) + } + upper <- 2 - 2*exp(sum(lambda/n)) + + # Lower Tail: + x = 1-x + y = 1-y + lambda = NULL + n = length(x) + for(i in 1:n){ + lambda = c(lambda, + log(sqrt(log(1/x[i])*log(1/y[i]))/log(1/max(x[i],y[i])^2))) + } + lower <- 2 - 2*exp(sum(lambda/n)) + + # Return Value: + c(lower = lower, upper = upper) +} + + +################################################################################ + + +.empiricalDependencyFit <- + function(x, doplot = TRUE, trace = FALSE) +{ + # A function implemented by Diethelm Wuertz + + # Description: + # Estimates tail dependency coefficients with Normal marginals + + # Arguments: + # x - a multivariate 'timeSeries' object + + # FUNCTION: + + # Settings: + N = ncol(x) + lowerLambda = upperLambda = 0*diag(N) + assetsNames = colnames(x) + P = NULL + + for (i in 1:(N-1)) { + # First asset: + r1 = as.vector(x[, i]) + fit1 = nFit(r1) + estim1 = fit1@fit$estimate + p1 = pnorm(r1, estim1[1], estim1[2]) + Main1 = assetsNames[i] + P = cbind(P, p1) + for (j in (i+1):N) + { + # Second asset: + r2 = as.vector(x[, j]) + fit2 = nFit(r2) + estim2 = fit2@fit$estimate + p2 = pnorm(r2, estim2[1], estim2[2]) + Main2 = assetsNames[j] + # Optional Plot: + if (doplot) + { + # Plot Distribution: + MainR = paste("Distribution:", Main1, "-", Main2) + plot(r1, r2, pch = 19, main = MainR) + grid() + + # Plot Copula: + MainP = paste("Copula:", Main1, "-", Main2) + plot(p1, p2, pch = 19, main = MainP) + grid() + } + + # Fit GSG copula parameters: + fit = .gsgnormCopulaFit(u = p1, v = p2, trace = trace) + if (trace) + cat(assetsNames[c(i,j)], round(fit$lambda, 3), "\n") + + # Compose lambda Matrix: + lowerLambda[i, j] = lowerLambda[j, i] = fit$lambda[1] + upperLambda[i, j] = upperLambda[j, i] = fit$lambda[2] + } + } + + # Result: + colnames(lowerLambda) = rownames(lowerLambda) = assetsNames + colnames(upperLambda) = rownames(upperLambda) = assetsNames + ans = list(lower = lowerLambda, upper = upperLambda) + + # Return Value: + ans +} + + +# ------------------------------------------------------------------------------ + + +.normDependencyFit <- + function(x, doplot = TRUE, trace = FALSE) +{ + # A function implemented by Diethelm Wuertz + + # Description: + # Estimates tail dependency coefficients with Normal marginals + + # Arguments: + # x - a multivariate 'timeSeries' object + + # FUNCTION: + + # Settings: + N = ncol(x) + lowerLambda = upperLambda = 0*diag(N) + assetsNames = colnames(x) + P = NULL + + for (i in 1:(N-1)) { + # First asset: + r1 = as.vector(x[, i]) + fit1 = nFit(r1) + estim1 = fit1@fit$estimate + p1 = pnorm(r1, estim1[1], estim1[2]) + Main1 = assetsNames[i] + P = cbind(P, p1) + for (j in (i+1):N) + { + # Second asset: + r2 = as.vector(x[, j]) + fit2 = nFit(r2) + estim2 = fit2@fit$estimate + p2 = pnorm(r2, estim2[1], estim2[2]) + Main2 = assetsNames[j] + # Optional Plot: + if (doplot) + { + # Plot Distribution: + MainR = paste("Distribution:", Main1, "-", Main2) + plot(r1, r2, pch = 19, main = MainR) + grid() + + # Plot Copula: + MainP = paste("Copula:", Main1, "-", Main2) + plot(p1, p2, pch = 19, main = MainP) + grid() + } + + # Fit GSG copula parameters: + fit = .gsgnormCopulaFit(u = p1, v = p2, trace = trace) + if (trace) + cat(assetsNames[c(i,j)], round(fit$lambda, 3), "\n") + # Compose lambda Matrix: + lowerLambda[i, j] = lowerLambda[j, i] = fit$lambda[1] + upperLambda[i, j] = upperLambda[j, i] = fit$lambda[2] + } + } + + # Result: + colnames(lowerLambda) = rownames(lowerLambda) = assetsNames + colnames(upperLambda) = rownames(upperLambda) = assetsNames + ans = list(lower = lowerLambda, upper = upperLambda) + + # Return Value: + ans +} + + +# ------------------------------------------------------------------------------ + + +.gldDependencyFit <- + function(x, doplot = TRUE, trace = FALSE) +{ + # A function implemented by Diethelm Wuertz + + # Description: + # Estimates tail dependency coefficients with NIG marginals + + # Arguments: + # x - a multivariate 'timeSeries' object + + # FUNCTION: + + # Settings: + N <- ncol(x) + lowerLambda <- upperLambda <- 0*diag(N) + assetsNames <- colnames(x) + P <- NULL + + for (i in 1:(N-1)) { + # First asset: + r1 <- as.vector(x[, i]) + fit1 <- gldFit(r1, doplot = FALSE, trace = trace) + estim1 <- fit1@fit$estimate + p1 <- pgld(r1, estim1[1], estim1[2], estim1[3], estim1[4]) + Main1 <- assetsNames[i] + P <- cbind(P, p1) + for (j in (i+1):N) { + # Second asset: + r2 <- as.vector(x[, j]) + fit2 <- gldFit(r2, doplot = FALSE, trace = trace) + estim2 = fit2@fit$estimate + p2 <- pgld(r2, estim2[1], estim2[2], estim2[3], estim2[4]) + Main2 <- assetsNames[j] + # Optional Plot: + if (doplot) { + ## MainR = paste("Distribution:", Main1, "-", Main2) + ## plot(r1, r2, pch = 19, main = MainR) + ## grid() + MainP <- paste("Copula:", Main1, "-", Main2) + plot(p1, p2, pch = 19, main = MainP, xlab = "", ylab = "", cex=0.5) + grid() + } + # Fit GSG copula parameters: + fit <- .gsgnormCopulaFit(u = p1, v = p2, trace = trace) + if (trace) cat(assetsNames[c(i,j)], round(fit$lambda, 3), "\n") + # Compose lambda Matrix: + lowerLambda[i, j] <- lowerLambda[j, i] <- fit$lambda[1] + upperLambda[i, j] <- upperLambda[j, i] <- fit$lambda[2] + } + } + + # Result: + colnames(lowerLambda) <- rownames(lowerLambda) <- assetsNames + colnames(upperLambda) <- rownames(upperLambda) <- assetsNames + ans = list(lower = lowerLambda, upper = upperLambda) + + # Return Value: + ans +} + + +# ------------------------------------------------------------------------------ + + +.ghtDependencyFit <- + function(x, doplot = TRUE, trace = FALSE) +{ + # A function implemented by Diethelm Wuertz + + # Description: + # Estimates tail dependency coefficients with GH Student-t marginals + + # Arguments: + # x - a multivariate 'timeSeries' object + + # FUNCTION: + + # Settings: + N = ncol(x) + lowerLambda = upperLambda = 0*diag(N) + assetsNames = colnames(x) + P = NULL + + for (i in 1:(N-1)) { + # First asset: + r1 = as.vector(x[, i]) + fit1 = ghtFit(r1, doplot = FALSE, trace = trace) + estim1 = fit1@fit$estimate + p1 = pght(r1, estim1[1], estim1[2], estim1[3], estim1[4]) + Main1 = assetsNames[i] + P = cbind(P, p1) + for (j in (i+1):N) { + # Second asset: + r2 = as.vector(x[, j]) + fit2 = ghtFit(r2, doplot = FALSE, trace = trace) + estim2 = fit2@fit$estimate + p2 = pght(r2, estim2[1], estim2[2], estim2[3], estim2[4]) + Main2 = assetsNames[j] + # Optional Plot: + if (doplot) { + MainR = paste("Distribution:", Main1, "-", Main2) + plot(r1, r2, pch = 19, main = MainR) + grid() + MainP = paste("Copula:", Main1, "-", Main2) + plot(p1, p2, pch = 19, main = MainP) + grid() + } + # Fit GSG copula parameters: + fit = .gsgnormCopulaFit(u = p1, v = p2, trace = trace) + if (trace) + cat(assetsNames[c(i,j)], round(fit$lambda, 3), "\n") + # Compose lambda Matrix: + lowerLambda[i, j] = lowerLambda[j, i] = fit$lambda[1] + upperLambda[i, j] = upperLambda[j, i] = fit$lambda[2] + } + } + + # Result: + colnames(lowerLambda) = rownames(lowerLambda) = assetsNames + colnames(upperLambda) = rownames(upperLambda) = assetsNames + ans = list(lower = lowerLambda, upper = upperLambda) + + # Return Value: + ans +} + + +################################################################################ + diff -Nru fportfolio-3011.81/R/zzz.R fportfolio-3042.83/R/zzz.R --- fportfolio-3011.81/R/zzz.R 2014-10-30 14:13:58.000000000 +0000 +++ fportfolio-3042.83/R/zzz.R 2017-11-13 15:44:41.000000000 +0000 @@ -1,69 +1,69 @@ - -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Library General Public -# License as published by the Free Software Foundation; either -# version 2 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Library General Public License for more details. -# -# You should have received a copy of the GNU Library General -# Public License along with this library; if not, write to the -# Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, -# MA 02111-1307 USA - - -################################################################################ - - -.onAttach <- -function(libname, pkgname) -{ - # do whatever needs to be done when the package is loaded - # some people use it to bombard users with - # messages using - - packageStartupMessage( "\n" ) - packageStartupMessage( "Rmetrics Package fPortfolio" ) - packageStartupMessage( "Portfolio Optimization" ) - packageStartupMessage( "Copyright (C) 2005-2014 Rmetrics Association Zurich" ) - packageStartupMessage( "Educational Software for Financial Engineering and Computational Science" ) - packageStartupMessage( "Rmetrics is free software and comes with ABSOLUTELY NO WARRANTY." ) - packageStartupMessage( "https://www.rmetrics.org --- Mail to: info@rmetrics.org" ) -} - - -############################################################################### - - -.onLoad <- - function(libname, pkgname) -{ - if(!is.numeric(timeDate::getRmetricsOptions("length.print"))) - timeDate::setRmetricsOptions(length.print = 5) - - timeDate::setRmetricsOptions(.x.save = NA) - - eval(attach <- function(what) - base::attach(what, warn.conflicts=FALSE), envir=.GlobalEnv) - -} - # Startup Mesage and Desription: - # MSG <- if(getRversion() >= "2.5") packageStartupMessage else message - # dsc <- packageDescription(pkg) - # if(interactive() || getOption("verbose")) { - # title <- paste(strsplit(dsc$Title, split = "-")[1:2]) - # MSG(paste( - # "\nPackage ", pkg, " (", dsc$Version, ") loaded.\n", - # dsc$Title, "\n", - # dsc$Copyright, ", ", dsc$License, "\n", - # dsc$Author, "\n", - # dsc$URL, "\n", sep="")) - # } - - -############################################################################### - - + +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Library General Public +# License as published by the Free Software Foundation; either +# version 2 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Library General Public License for more details. +# +# You should have received a copy of the GNU Library General +# Public License along with this library; if not, write to the +# Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, +# MA 02111-1307 USA + + +################################################################################ + + +.onAttach <- +function(libname, pkgname) +{ + # do whatever needs to be done when the package is loaded + # some people use it to bombard users with + # messages using + + # packageStartupMessage( "\n" ) + # packageStartupMessage( "Rmetrics Package fPortfolio" ) + # packageStartupMessage( "Portfolio Optimization" ) + # packageStartupMessage( "Copyright (C) 2005-2014 Rmetrics Association Zurich" ) + # packageStartupMessage( "Educational Software for Financial Engineering and Computational Science" ) + # packageStartupMessage( "Rmetrics is free software and comes with ABSOLUTELY NO WARRANTY." ) + # packageStartupMessage( "https://www.rmetrics.org --- Mail to: info@rmetrics.org" ) +} + + +############################################################################### + + +.onLoad <- + function(libname, pkgname) +{ + if(!is.numeric(timeDate::getRmetricsOptions("length.print"))) + timeDate::setRmetricsOptions(length.print = 5) + + timeDate::setRmetricsOptions(.x.save = NA) + + eval(attach <- function(what) + base::attach(what, warn.conflicts=FALSE), envir=.GlobalEnv) + +} + # Startup Mesage and Desription: + # MSG <- if(getRversion() >= "2.5") packageStartupMessage else message + # dsc <- packageDescription(pkg) + # if(interactive() || getOption("verbose")) { + # title <- paste(strsplit(dsc$Title, split = "-")[1:2]) + # MSG(paste( + # "\nPackage ", pkg, " (", dsc$Version, ") loaded.\n", + # dsc$Title, "\n", + # dsc$Copyright, ", ", dsc$License, "\n", + # dsc$Author, "\n", + # dsc$URL, "\n", sep="")) + # } + + +############################################################################### + +