Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
braverock
GitHub Repository: braverock/portfolioanalytics
Path: blob/master/demo/multiple_portfolio_optimization.R
1433 views
1
2
library(PortfolioAnalytics)
3
4
# Examples of passing a list portfolio objects to optimize.portfolio and
5
# optimize.portfolio.rebalancing
6
7
data(edhec)
8
R <- edhec[, 1:4]
9
funds <- colnames(R)
10
11
# Construct initial portfolio
12
init.portf <- portfolio.spec(assets=funds)
13
init.portf <- add.constraint(portfolio=init.portf, type="weight_sum",
14
min_sum=0.99, max_sum=1.01)
15
init.portf <- add.constraint(portfolio=init.portf, type="long_only")
16
17
# Minimize portfolio standard deviation
18
minSD.portf <- add.objective(portfolio=init.portf, type="risk", name="StdDev")
19
20
# Maximize mean return per unit portfolio standard deviation
21
meanSD.portf <- add.objective(portfolio=minSD.portf, type="return", name="mean")
22
23
# Minimize expected shortfall
24
minES.portf <- add.objective(portfolio=init.portf, type="risk", name="ES")
25
26
# Maximize mean return per unit portfolio expected shortfall
27
meanES.portf <- add.objective(portfolio=minES.portf, type="return", name="mean")
28
29
# Combine the portfolios
30
mult.portf <- combine.portfolios(list(minSD.portf, meanSD.portf, minES.portf, meanES.portf))
31
mult.portf
32
33
# run the optimization for mult.portf
34
mult.opt <- optimize.portfolio(R, mult.portf, optimize_method="random",
35
search_size=2000, trace=TRUE, message = TRUE)
36
37
class(mult.opt)
38
mult.opt
39
40
# This combines the weights for each portfolio optimized
41
extractWeights(mult.opt)
42
43
# This combines the objective measures for each portfolio
44
extractObjectiveMeasures(mult.opt)
45
46
# For N portfolios, this returns a list of length N with the stats
47
# for each portfolio
48
opt.xtract <- extractStats(mult.opt)
49
50
# Run the rebalancing optimization for mult.portf
51
mult.opt.rebal <- optimize.portfolio.rebalancing(R, mult.portf,
52
optimize_method="random",
53
search_size=2000,
54
trace=TRUE,
55
message=TRUE,
56
rebalance_on="quarters",
57
training_period=140)
58
59
class(mult.opt.rebal)
60
mult.opt.rebal
61
62
# For N portfolios, this returns a list of length N with the optimal weights
63
# at each rebalancing date
64
extractWeights(mult.opt.rebal)
65
66
# For N portfolios, this returns a list of length N with the objective measures
67
# at each rebalancing date
68
extractObjectiveMeasures(mult.opt.rebal)
69
70
# For N portfolios, this returns a list of length N with the stats
71
# for each portfolio
72
opt.rebal.xtract <- extractStats(mult.opt.rebal)
73
74
75
76