Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
braverock
GitHub Repository: braverock/portfolioanalytics
Path: blob/master/demo/sortino.R
1433 views
1
#' ---
2
#' title: "Sortino Demo"
3
#' author: Brian Peterson
4
#' date: "7/17/2014"
5
#' ---
6
7
#' Load the necessary packages
8
# Include optimizer and multi-core packages
9
library(PortfolioAnalytics)
10
library(PerformanceAnalytics)
11
require(xts)
12
require(DEoptim)
13
require(TTR)
14
15
#' Register parallel backend.
16
#' note: these may not be appropriate on Windows
17
require(doMC)
18
registerDoMC()
19
# for Windows
20
#require(doParallel)
21
#registerDoParallel()
22
23
24
#' Load the data. Here we use monthly total returns of four asset-class indexes.
25
data(indexes)
26
#only look at 2000 onward
27
#indexes<-indexes["2000::"]
28
29
30
#' Set the MAR parameter
31
MAR =.005 #~6%/year
32
33
#' Example 1 maximize Sortino Ratio
34
SortinoConstr <- constraint(assets = colnames(indexes[,1:4]), min = 0.05, max = 1, min_sum=.99, max_sum=1.01, weight_seq = generatesequence(by=.001))
35
SortinoConstr <- add.objective(constraints=SortinoConstr, type="return", name="SortinoRatio", enabled=TRUE, arguments = list(MAR=MAR))
36
SortinoConstr <- add.objective(constraints=SortinoConstr, type="return", name="mean", enabled=TRUE, multiplier=0) # multiplier 0 makes it availble for plotting, but not affect optimization
37
38
#' Use random portfolio engine
39
SortinoResult<-optimize.portfolio(R=indexes[,1:4], constraints=SortinoConstr, optimize_method='random', search_size=2000, trace=TRUE, verbose=TRUE)
40
plot(SortinoResult, risk.col='SortinoRatio')
41
42
#' Alternately, Use DEoptim engine
43
#SortinoResultDE<-optimize.portfolio(R=indexes[,1:4], constraints=SortinoConstr, optimize_method='DEoptim', search_size=2000, trace=TRUE, verbose=FALSE,strategy=6, parallel=TRUE) #itermax=55, CR=0.99, F=0.5,
44
#plot(SortinoResultDE, risk.col='SortinoRatio')
45
46
#' Now rebalance quarterly
47
SortinoRebalance <- optimize.portfolio.rebalancing(R=indexes[,1:4], constraints=SortinoConstr, optimize_method="random", trace=TRUE, rebalance_on='quarters', trailing_periods=NULL, training_period=36, search_size=2000)
48
49
###############################################################################
50
# R (http://r-project.org/) Numeric Methods for Optimization of Portfolios
51
#
52
# Copyright (c) 2004-2014 Kris Boudt, Peter Carl and Brian G. Peterson
53
#
54
# This library is distributed under the terms of the GNU Public License (GPL)
55
# for full details see the file COPYING
56
#
57
# $Id$
58
#
59
###############################################################################
60