Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
braverock
GitHub Repository: braverock/portfolioanalytics
Path: blob/master/demo/demo_max_Sharpe.R
1433 views
1
#' ---
2
#' title: "Maximizing Sharpe Ratio Demo"
3
#' author: Ross Bennett
4
#' date: "7/17/2014"
5
#' ---
6
7
#' This script demonstrates how to solve a constrained
8
#' portfolio optimization problem to maximize Sharpe Ratio.
9
10
#' Load the package and data
11
library(PortfolioAnalytics)
12
data(edhec)
13
R <- edhec[, 1:8]
14
funds <- colnames(R)
15
16
#' Construct initial portfolio with basic constraints.
17
init.portf <- portfolio.spec(assets=funds)
18
init.portf <- add.constraint(portfolio=init.portf, type="full_investment")
19
init.portf <- add.constraint(portfolio=init.portf, type="long_only")
20
init.portf <- add.objective(portfolio=init.portf, type="return", name="mean")
21
init.portf <- add.objective(portfolio=init.portf, type="risk", name="StdDev")
22
init.portf
23
24
#' Maximizing Sharpe Ratio can be formulated as a quadratic programming
25
#' problem and solved very quickly using optimize_method="ROI". Although "StdDev"
26
#' was specified as an objective, the quadratic programming problem uses the
27
#' variance-covariance matrix in the objective function.
28
29
#' The default action if "mean" and "StdDev" are specified as objectives with
30
#' optimize_method="ROI" is to maximize quadratic utility. If we want to maximize
31
#' Sharpe Ratio, we need to pass in maxSR=TRUE to optimize.portfolio.
32
33
maxSR.lo.ROI <- optimize.portfolio(R=R, portfolio=init.portf,
34
optimize_method="ROI",
35
maxSR=TRUE, trace=TRUE)
36
maxSR.lo.ROI
37
38
#' Although the maximum Sharpe Ratio objective can be solved quickly and accurately
39
#' with optimize_method="ROI", it is also possible to solve this optimization
40
#' problem using other solvers such as random portfolios or DEoptim. These
41
#' solvers have the added flexibility of using different methods to calculate
42
#' the Sharpe Ratio (e.g. we could specify annualized measures of risk and return).
43
44
#' For random portfolios and DEoptim, the leverage constraints should be
45
#' relaxed slightly.
46
init.portf$constraints[[1]]$min_sum=0.99
47
init.portf$constraints[[1]]$max_sum=1.01
48
49
# Use random portfolios to run the optimization.
50
maxSR.lo.RP <- optimize.portfolio(R=R, portfolio=init.portf,
51
optimize_method="random",
52
search_size=2000,
53
trace=TRUE)
54
maxSR.lo.RP
55
chart.RiskReward(maxSR.lo.RP, risk.col="StdDev", return.col="mean")
56
57
# Use DEoptim to run the optimization.
58
maxSR.lo.DE <- optimize.portfolio(R=R, portfolio=init.portf,
59
optimize_method="DEoptim",
60
search_size=2000,
61
trace=TRUE)
62
maxSR.lo.DE
63
chart.RiskReward(maxSR.lo.DE, risk.col="StdDev", return.col="mean")
64
65
66