Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
braverock
GitHub Repository: braverock/portfolioanalytics
Path: blob/master/demo/higher_moments_boudt.R
1433 views
1
#' ---
2
#' title: "Higher Moment Estimates Demo"
3
#' author: Ross Bennett
4
#' date: "7/17/2014"
5
#' ---
6
7
#' This script demonstrates how to solve a constrained portfolio optimization
8
#' problem using moments estimated via a factor model based on the work of
9
#' Kris Boudt.
10
11
#' Load package and data.
12
library(PortfolioAnalytics)
13
data(edhec)
14
R <- edhec[, 1:10]
15
funds <- colnames(R)
16
17
#' Construct initial portfolio with basic constraints.
18
init.portf <- portfolio.spec(assets=funds)
19
init.portf <- add.constraint(portfolio=init.portf, type="weight_sum",
20
min_sum=0.99, max_sum=1.01)
21
init.portf <- add.constraint(portfolio=init.portf, type="long_only")
22
init.portf <- add.objective(portfolio=init.portf, type="risk", name="ES",
23
arguments=list(p=0.9, clean="boudt"))
24
25
#' This is not necessary for the optimization, but demonstrates how the
26
#' moments are estimated using portfolio.moments.boudt.
27
cleanR <- Return.clean(R, "boudt")
28
fit <- statistical.factor.model(cleanR, 3)
29
30
#' Here we extract the moments.
31
sigma <- extractCovariance(fit)
32
m3 <- extractCoskewness(fit)
33
m4 <- extractCokurtosis(fit)
34
35
# Here we compute the moments with portfolio.moments.boudt and show that the
36
#' result is equivalent to fitting the factor model and extracting the moment
37
#' estimates.
38
moments.boudt <- portfolio.moments.boudt(R, init.portf, k=3)
39
all.equal(moments.boudt$sigma, sigma)
40
all.equal(moments.boudt$m3, m3)
41
all.equal(moments.boudt$m4, m4)
42
43
#' Generate set of random portfolios to use for the optimization.
44
rp <- random_portfolios(init.portf, 5000)
45
46
#' Here we run the optimization using sample estimates for the moments.
47
#' The default for momentFUN is set.portfolio.moments which computes
48
#' the sample estimates of the moments.
49
minES.lo.sample <- optimize.portfolio(R=R, portfolio=init.portf,
50
rp=rp, optimize_method="random",
51
trace=TRUE)
52
53
#' Now we run the optimization with statistical factor model estimates of the
54
#' moments.
55
minES.lo.boudt <- optimize.portfolio(R=R, portfolio=init.portf,
56
momentFUN=portfolio.moments.boudt,
57
k=3, rp=rp,
58
optimize_method="random",
59
trace=TRUE)
60
61
62
63