forked from rossb34/PortfolioAnalyticsPresentation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
presentation.Rmd
891 lines (672 loc) · 28.4 KB
/
presentation.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
---
title : Complex Portfolio Optimization with PortfolioAnalytics
subtitle : R/Finance 2014
author : Ross Bennett
date : May 16, 2014
framework : io2012 # {io2012, html5slides, shower, dzslides, ...}
ext_widgets : {rCharts: libraries/nvd3}
widgets : mathjax
mode : selfcontained
---
```{r, echo=FALSE, message=FALSE}
library(PortfolioAnalytics)
require(methods)
```
## Overview
* Discuss Portfolio Optimization
* Introduce PortfolioAnalytics
* Demonstrate PortfolioAnalytics with Examples
<!--
* Discuss Portfolio Optimization
* Background and challenges of portfolio theory
* Introduce PortfolioAnalytics
* What PortfolioAnalytics does and the problems it solves
* Demonstrate PortfolioAnalytics with Examples
* Brief overview of the examples I will be giving
-->
---
## Modern Portfolio Theory
"Modern" Portfolio Theory (MPT) was introduced by Harry Markowitz in 1952.
In general, MPT states that an investor's objective is to maximize portfolio expected return for a given amount of risk.
General Objectives
* Maximize a measure of gain per unit measure of risk
* Minimize a measure of risk
How do we define risk? What about more complex objectives and constraints?
<!--
Several approaches follow the Markowitz approach using mean return as a measure of gain and standard deviation of returns as a measure of risk. This is an academic approach.
-->
---
## Portfolio Optimization Objectives
* Minimize Risk
* Volatility
* Tail Loss (VaR, ES)
* Other Downside Risk Measure
* Maximize Risk Adjusted Return
* Sharpe Ratio, Modified Sharpe Ratio
* Several Others
* Risk Budgets
* Equal Component Contribution to Risk (i.e. Risk Parity)
* Limits on Component Contribution
* Maximize a Utility Function
* Quadratic, CRRA, etc.
<!--
* Expand on pros/cons of closed-form solvers vs. global solvers and what objectives can be solved.
* The challenge here is knowing what solver to use and the capabilities/limits of the chosen solver.
* Some of these problems can be formulated as a quadratic or linear programming problem. Constructing the constraint matrix and objective function matrix or vector is not trivial. Limited to the quality of LP and QP solvers available for R.
-->
---
## PortfolioAnalytics Overview
PortfolioAnalytics is an R package designed to provide numerical solutions and visualizations for portfolio optimization problems with complex constraints and objectives.
* Support for multiple constraint and objective types
* An objective function can be any valid R function
* Modular constraints and objectives
* Support for user defined moment functions
* Visualizations
* Solver agnostic
* Support for parallel computing
<!---
The key points to make here are:
* Flexibility
* The multiple types and modularity of constraints and objectives allows us to add, remove, combine, etc. multiple constraint and objective types very easily.
* Define an objective as any valid R function
* Define a function to compute the moments (sample, robust, shrinkage, factor model, GARCH model, etc.)
* Estimation error is a significant concern with optimization. Having the ability to test different models with different parameters is critical.
* PortfolioAnalytics comes "out of the box" with several constraint types.
* Visualization helps to build intuition about the problem and understand the feasible space of portfolios
* Periodic rebalancing and analyzing out of sample performance will help refine objectives and constraints
* Framework for evaluating portfolios with different sets of objectives and portfolios through time
-->
---
## Support Multiple Solvers
Linear and Quadratic Programming Solvers
* R Optimization Infrastructure (ROI)
* GLPK (Rglpk)
* Symphony (Rsymphony)
* Quadprog (quadprog)
Global (stochastic or continuous solvers)
* Random Portfolios
* Differential Evolution (DEoptim)
* Particle Swarm Optimization (pso)
* Generalized Simulated Annealing (GenSA)
<!---
Brief explanation of each solver and what optimization problems are supported
-->
---
## Random Portfolios
PortfolioAnalytics has three methods to generate random portfolios.
1. The **sample** method to generate random portfolios is based on an idea by Pat Burns.
2. The **simplex** method to generate random portfolios is based on a paper by W. T. Shaw.
3. The **grid** method to generate random portfolios is based on the `gridSearch` function in the NMOF package.
<!--
* Random portfolios allow one to generate an arbitray number of portfolios based on given constraints. Will cover the edges as well as evenly cover the interior of the feasible space. Allows for massively parallel execution.
* The sample method to generate random portfolios is based on an idea by Patrick Burns. This is the most flexible method, but also the slowest, and can generate portfolios to satisfy leverage, box, group, and position limit constraints.
* The simplex method to generate random portfolios is based on a paper by W. T. Shaw. The simplex method is useful to generate random portfolios with the full investment constraint, where the sum of the weights is equal to 1, and min box constraints. Values for min_sum and max_sum of the leverage constraint will be ignored, the sum of weights will equal 1. All other constraints such as the box constraint max, group and position limit constraints will be handled by elimination. If the constraints are very restrictive, this may result in very few feasible portfolios remaining. Another key point to note is that the solution may not be along the vertexes depending on the objective. For example, a risk budget objective will likely place the portfolio somewhere on the interior.
* The grid method to generate random portfolios is based on the gridSearch function in NMOF package. The grid search method only satisfies the min and max box constraints. The min_sum and max_sum leverage constraint will likely be violated and the weights in the random portfolios should be normalized. Normalization may cause the box constraints to be violated and will be penalized in constrained_objective.
-->
---
## Comparison of Random Portfolio Methods
![](figures/rp_plot.png)
<!--
* This chart is a prime candidate for an interactive viz
* The feasible space is computed using the EDHEC data for a long only portfolio with a search size of 2000.
-->
---
## Comparison of Random Portfolio Methods (Interactive!)
```{r, results = 'asis', comment = NA, message = F, echo = F}
load("figures/rp_viz.rda")
rp_viz$show('inline')
```
<!--
The feasible space is computed using the EDHEC data for a long only portfolio with a search size of 2000.
-->
---
## Random Portfolios: Simplex Method
![](figures/fev_plot.png)
<!--
FEV (Face-Edge-Vertex bias values control how concentrated a portfolio is. This can clearly be seen in the plot. As FEV approaches infinity, the portfolio weight will be concentrated on a single asset. PortfolioAnalytics allows you to specify a vector of fev values for comprehensive coverage of the feasible space.
-->
---
## Workflow: Specify Portfolio
```{r}
args(portfolio.spec)
```
Initializes the portfolio object that holds portfolio level data, constraints, and objectives
<!--
The portfolio object is an S3 object that holds portfolio-level data, constraints, and objectives. The portfolio-level data includes asset names and initial weights, labels to categorize assets, and a sequence of weights for random portfolios. The main argument is assets which can be a character vector (most common use), named numeric vector, or scalar value specifying number of assets.
-->
---
## Workflow: Add Constraints
```{r}
args(add.constraint)
```
Supported Constraint Types
* Sum of Weights
* Box
* Group
* Factor Exposure
* Position Limit
* and many more
<!--
This adds a constraint object to the portfolio object. Constraints are added to the portfolio object with the add.constraint function. Each constraint added is a separate object and stored in the constraints slot in the portfolio object. In this way, the constraints are modular and one can easily add, remove, or modify the constraints in the portfolio object. Main argument is the type, arguments to the constraint constructor are then passed through the dots (...).
-->
---
## Workflow: Add Objectives
```{r}
args(add.objective)
```
Supported Objective types
* Return
* Risk
* Risk Budget
* Weight Concentration
<!--
Objectives are added to the portfolio object with the add.objective function. Each objective added is a separate object and stored in the objectives slot in the portfolio object. In this way, the objectives are modular and one can easily add, remove, or modify the objective objects. The name argument must be a valid R function. Several functions are available in the PerformanceAnalytics package, but custom user defined functions can be used as objective functions.
-->
---
## Workflow: Run Optimization
```{r}
args(optimize.portfolio)
args(optimize.portfolio.rebalancing)
```
<!--
* Notice the similarity between these two functions. You only have to specify a few additional arguments for the backtesting.
* optimize.portfolio: Main arguments for a single period optimization are the returns (R), portfolio, and optimize_method. We take the portfolio object and parse the constraints and objectives according to the optimization method.
* optimize.portfolio.rebalancing: Supports periodic rebalancing (backtesting) to examine out of sample performance. Helps refine constraints and objectives by analyzing out or sample performance. Essentially a wrapper around optimize.portfolio that handles the time interface.
-->
---
## Workflow: Analyze Results
Visualization | Data Extraction
------------- | ----------
plot | extractObjectiveMeasures
chart.Concentration | extractStats
chart.EfficientFrontier | extractWeights
chart.RiskReward | print
chart.RiskBudget | summary
chart.Weights |
<!--
Brief explanation of each function.
-->
---
## Stock Data Setup
Here we will look at portfolio optimization in the context of stocks.
* Selection of large cap, mid cap, and small cap stocks from CRSP data
* Weekly data from 1/7/1997 to 12/28/2010
* 15 Large Cap
* 15 Mid Cap
* 5 Small Cap
```{r, eval=FALSE, tidy=FALSE}
equity.data <- cbind(largecap_weekly[,1:15],
midcap_weekly[,1:15],
smallcap_weekly[,1:5])
```
<!--
slide comments
-->
---
## Distribution of Monthly Returns
![](figures/equity_box.png)
<!--
slide comments
-->
---
## Example 1: Market Neutral Portfolio
Here we consider a portfolio of stocks. Our objective is to maximize portfolio return with a target of 0.0015 and minimize portfolio StdDev with a target of 0.02 subject to dollar neutral, beta, box, and position limit constraints.
<!--
This involves combining several constraints. This is an MIQPQC problem that can't be solved by quadprog so we will use random portfolios. Good example of a problem with layering multiple constraints and objectives.
-->
---
## Specify Portfolio: Constraints
```{r, eval=FALSE, tidy=FALSE}
portf.dn <- portfolio.spec(stocks)
# Add constraint such that the portfolio weights sum to 0*
portf.dn <- add.constraint(portf.dn, type="weight_sum",
min_sum=-0.01, max_sum=0.01)
# Add box constraint such that no asset can have a weight of greater than
# 20% or less than -20%
portf.dn <- add.constraint(portf.dn, type="box", min=-0.2, max=0.2)
# Add constraint such that we have at most 20 positions
portf.dn <- add.constraint(portf.dn, type="position_limit", max_pos=20)
# Add constraint such that the portfolio beta is between -0.25 and 0.25
betas <- t(CAPM.beta(equity.data, market, Rf))
portf.dn <- add.constraint(portf.dn, type="factor_exposure", B=betas,
lower=-0.25, upper=0.25)
```
<!---
explain the constraints
-->
---
## Specify Portfolio: Objectives
```{r,eval=FALSE, tidy=FALSE}
# Add objective to maximize portfolio return with a target of 0.0015
portf.dn.StdDev <- add.objective(portf.dn, type="return", name="mean",
target=0.0015)
# Add objective to minimize portfolio StdDev with a target of 0.02
portf.dn.StdDev <- add.objective(portf.dn.StdDev, type="risk", name="StdDev",
target=0.02)
```
<!---
explain the objectives, specifically the target argument
-->
---
## Run Optimization
```{r, eval=FALSE, tidy=FALSE}
# Generate random portfolios
rp <- random_portfolios(portf.dn, 10000, "sample")
# Run the optimization
opt.dn <- optimize.portfolio(equity.data, portf.dn.StdDev,
optimize_method="random", rp=rp,
trace=TRUE)
```
<!---
generate a set of random portfolios and then pass directly to optimize.portfolio. Could just specify optimize_method = "random" and will automatically generate for you. Generating the random portfolios separately is useful if you plan to evaluate multiple objectives with the same constraints to avoid regenerating random portfolios. Casual benchmarking revealed that generating the random portfolios was often slower than evaluating the objective function on the set of random portfolios. Don't regenerate the portfolios if you don't have to.
-->
---
## Plot Results
```{r, eval=FALSE, tidy=FALSE}
plot(opt.dn, main="Dollar Neutral Portfolio", risk.col="StdDev", neighbors=10)
```
![](figures/opt_dn.png)
<!--
Demonstrates the plot method. Visualize the optimal and feasible portfolios in risk-return space and weights of the optimal portfolios. "Neighbor" portfolios allow you to see where the next closest optimal portfolios are (sorted be the value of the objective function from the optimizer).
-->
---
## EDHEC Data Setup
Here we will look at portfolio optimization in the context of portfolio of hedge funds.
* EDHEC-Risk Alternative Indexes monthly returns from 1/31/1997 to 1/31/2014
Relative Value | Directional
-------------- | -----------
Convertible Arbitrage (CA) | CTA Global (CTAG)
Equity Market Neutral (EMN) | Emerging Markets (EM)
Fixed Income Arbitrage (FIA) | Global Macro (GM)
```{r, eval=FALSE, tidy=FALSE}
R <- edhec[,c("Convertible.Arbitrage", "Equity.Market.Neutral",
"Fixed.Income.Arbitrage",
"CTA.Global", "Emerging.Markets", "Global.Macro")]
# Abreviate column names for convenience and plotting
colnames(R) <- c("CA", "EMN", "FIA", "CTAG", "EM", "GM")
```
<!--
* Chosen to represent investing in hedge funds with different styles
* Not necessarily investable
* Style definitions
-->
---
## Monthly Returns
![](figures/relative_barvar.png)
![](figures/directional_barvar.png)
<!--
* Easy to see the relative volatility
* Periods of coincident drawdowns
-->
<!--
---
## Distribution of Monthly Returns
![](figures/edhec_box.png)
slide comments
-->
---
## Example 2: Minimum Expected Shortfall
Consider an allocation to hedge funds using the EDHEC-Risk Alternative Index as a proxy. This will be an extended example starting with an objective to minimize modified expected shortfall, then add risk budget percent contribution limit, and finally add equal risk contribution limit.
* Minimize Modified Expected Shortfall
* Minimize Modified Expected Shortfall with Risk Budget Limit
* Minimize Modified Expected Shortfall with Equal Risk Contribution
<!--
Add risk budget objective to minimize concentration of percentage component contribution to risk. Concentration is defined as the Herfindahl Hirschman Index (HHI).
$$ \sum_{i=1}^n x_i^2 $$
-->
<!--
* ES is coherent and is a convex function of the weights
* We are actually using modified ES to take into account the higher moments because the return distribution displays skewness and kurtosis. Modified ES uses the Cornish-Fisher estimate of ES.
-->
---
## Specify Initial Portfolio
```{r, eval=FALSE, tidy=FALSE}
# Specify an initial portfolio
funds <- colnames(R)
portf.init <- portfolio.spec(funds)
# Add constraint such that the weights sum to 1*
portf.init <- add.constraint(portf.init, type="weight_sum",
min_sum=0.99, max_sum=1.01)
# Add box constraint such that no asset can have a weight of greater than
# 40% or less than 5%
portf.init <- add.constraint(portf.init, type="box",
min=0.05, max=0.4)
# Add return objective with multiplier=0 such that the portfolio mean
# return is calculated, but does not impact optimization
portf.init <- add.objective(portf.init, type="return",
name="mean", multiplier=0)
```
<!--
Explain the initial portfolio setup
-->
---
## Add Objectives
```{r, eval=FALSE, tidy=FALSE}
# Add objective to minimize expected shortfall
portf.minES <- add.objective(portf.init, type="risk", name="ES")
# Add objective to set upper bound on percentage component contribution
portf.minES.RB <- add.objective(portf.minES, type="risk_budget",
name="ES", max_prisk=0.3)
# Relax box constraints
portf.minES.RB$constraints[[2]]$max <- rep(1,ncol(R))
# Add objective to minimize concentration of modified ES
# component contribution
portf.minES.EqRB <- add.objective(portf.minES, type="risk_budget",
name="ES", min_concentration=TRUE)
# Relax box constraints
portf.minES.EqRB <- add.constraint(portf.minES.EqRB, type="box",
min=0.05, max=1, indexnum=2)
```
<!--
Key points here are that we are creating 3 new portfolios by reusing the initial portfolio and we are relaxing the box constraints because we are no longer concerned with controlling weight concentration... we have limits on risk contribution.
-->
---
## Run Optimization
```{r, eval=FALSE, tidy=FALSE}
# Combine the 3 portfolios
portf <- combine.portfolios(list(minES=portf.minES,
minES.RB=portf.minES.RB,
minES.EqRB=portf.minES.EqRB))
# Run the optimization
opt.minES <- optimize.portfolio(R, portf, optimize_method="DEoptim",
search_size=5000, trace=TRUE, traceDE=0)
```
<!---
Explain how portf is a list of portfolios and passed to optimize.portfolio
-->
---
## Plot in Risk-Return Space
![](figures/opt_minES.png)
<!--
Note here how DEoptim concentrates its search space on the left hand side, towards the objective.... it spends some time in the upper right, but rapidly moves to concentrating closer to the min-risk boundary
-->
---
## Chart Risk Budgets
```{r, echo=FALSE, eval=FALSE, tidy=FALSE}
chart.RiskBudget(opt.minES[[2]], main="Risk Budget Limit",
risk.type="percentage", neighbors=10)
chart.RiskBudget(opt.minES[[3]], main="Equal ES Component Contribution",
risk.type="percentage", neighbors=10)
```
![](figures/rb_minES.png)
![](figures/eqrb_minES.png)
<!--
slide comments
-->
---
## Set Rebalancing Parameters and Run Backtest
```{r, eval=FALSE, tidy=FALSE}
# Set rebalancing frequency
rebal.freq <- "quarters"
# Training Period
training <- 120
# Trailing Period
trailing <- 72
bt.opt.minES <- optimize.portfolio.rebalancing(R, portf,
optimize_method="DEoptim",
rebalance_on=rebal.freq,
training_period=training,
trailing_periods=trailing,
search_size=5000,
traceDE=0)
```
<!--
slide comments
-->
---
## Min ES Risk Contributions and Weights Through Time
![](figures/risk_minES.png)
![](figures/weights_minES.png)
<!--
slide comments
-->
---
## Min ES Risk Budget Limit Risk Contributions and Weights Through Time
![](figures/risk_minESRB.png)
![](figures/weights_minESRB.png)
<!--
slide comments
-->
---
## Min ES Equal Component Contribution Risk Contributions and Weights Through Time
![](figures/risk_minESEqRB.png)
![](figures/weights_minESEqRB.png)
<!--
slide comments
-->
--- &twocol
## Min ES Equal Component Contribution Risk Contributions and Weights (interactive!)
```{r, results = 'asis', comment = NA, message = F, echo = F}
load("figures/bt_w3.rda")
load("figures/bt_rb3.rda")
```
*** =left
#### Percent Contribution to Risk
```{r, results = 'asis', comment = NA, message = F, echo = F}
bt_rb3$set(
height = 400
,width = 450
)
bt_rb3$chart( stacked=T )
bt_rb3$setLib("nvd3")
bt_rb3$setTemplate(afterScript="<script></script>")
bt_rb3$show('inline')
```
*** =right
#### Weights
```{r, results = 'asis', comment = NA, message = F, echo = F}
bt_w3$set(
height = 400
,width = 450
)
bt_w3$chart( stacked=T )
bt_w3$setLib("nvd3")
bt_w3$setTemplate(afterScript="<script></script>")
bt_w3$show('inline')
```
<!--
slide comments
-->
---
## Compute Returns
```{r, eval=FALSE, tidy=FALSE}
ret.bt.opt <- do.call(cbind, lapply(bt.opt.minES,
function(x) summary(x)$portfolio_returns))
colnames(ret.bt.opt) <- c("min ES", "min ES RB", "min ES Eq RB")
```
<!--
Recall that bt.opt.minES is a list where each element is an optimize.portfolio.rebalancing object. Basically, we want to loop through that list and extract the portfolio returns that is computed by the summary method.
-->
---
## Chart Performance
```{r, eval=FALSE, tidy=FALSE}
charts.PerformanceSummary(ret.bt.opt)
```
![](figures/ret_minES.png)
<!--
slide comments
-->
---
## Example 3: Maximize CRRA
Consider an allocation to hedge funds using the EDHEC-Risk Alternative Index as a proxy. Our objective to maximize the fourth order expansion of the Constant Relative Risk Aversion (CRRA) expected utility function as in the Boudt paper and Martellini paper. We use the same data as Example 3.
$$
EU_{\lambda}(w) = - \frac{\lambda}{2} m_{(2)}(w) +
\frac{\lambda (\lambda + 1)}{6} m_{(3)}(w) -
\frac{\lambda (\lambda + 1) (\lambda + 2)}{24} m_{(4)}(w)
$$
<!---
* This example will demonstrate a custom moment function and a custom objective function.
* This is an interesting objective function
* An increase in the 2nd and 4th moment will decrease the objective function
* An increase in the lambda value places a bigger penalty on the higher moments
-->
---
## Define a function to compute CRRA
```{r, eval=FALSE, tidy=FALSE}
CRRA <- function(R, weights, lambda, sigma, m3, m4){
weights <- matrix(weights, ncol=1)
M2.w <- t(weights) %*% sigma %*% weights
M3.w <- t(weights) %*% m3 %*% (weights %x% weights)
M4.w <- t(weights) %*% m4 %*% (weights %x% weights %x% weights)
term1 <- (1 / 2) * lambda * M2.w
term2 <- (1 / 6) * lambda * (lambda + 1) * M3.w
term3 <- (1 / 24) * lambda * (lambda + 1) * (lambda + 2) * M4.w
out <- -term1 + term2 - term3
out
}
```
<!---
The function arguments should have 'R' as the name of the returns and 'weights' as the name of the weights. 'R' and 'weights' are automatically matched, any other function arguments can be passed in through arguments in add.objective.
-->
---
## Define a custom moment function
The default function for `momentFUN` is `set.portfolio.moments`. We need to write our own function to estimate the moments for our objective function.
```{r, eval=FALSE}
crra.moments <- function(R, ...){
out <- list()
out$mu <- colMeans(R)
out$sigma <- cov(R)
out$m3 <- PerformanceAnalytics:::M3.MM(R)
out$m4 <- PerformanceAnalytics:::M4.MM(R)
out
}
```
<!--
The set.portfolio.moments looks for the most common objective function names e.g. mean, StdDev, VaR, and ES. The custom moment function should return a named list of the moments needed for the objective function.
-->
---
## Specify Portfolio
```{r, eval=FALSE, tidy=FALSE}
# Specify portfolio
portf.crra <- portfolio.spec(funds)
# Add constraint such that the weights sum to 1
portf.crra <- add.constraint(portf.crra, type="weight_sum",
min_sum=0.99, max_sum=1.01)
# Add box constraint such that no asset can have a weight of greater than
# 40% or less than 5%
portf.crra <- add.constraint(portf.crra, type="box",
min=0.05, max=0.4)
# Add objective to maximize CRRA
portf.crra <- add.objective(portf.crra, type="return",
name="CRRA", arguments=list(lambda=10))
```
<!---
Focus on how CRRA is added as an objective and the lambda argument is passed
-->
---
## "Dummy" Objectives
```{r, eval=FALSE, tidy=FALSE}
# Dummy objectives for plotting and/or further analysis
portf.crra <- add.objective(portf.crra, type="return", name="mean", multiplier=0)
portf.crra <- add.objective(portf.crra, type="risk", name="ES", multiplier=0)
portf.crra <- add.objective(portf.crra, type="risk", name="StdDev", multiplier=0)
```
<!---
* Explain what multiplier = 0 is doing
* The value is computed, but it does not impact the optimization
-->
---
## Run Optimization
```{r, eval=FALSE, tidy=FALSE}
opt.crra <- optimize.portfolio(R, portf.crra, optimize_method="DEoptim",
search_size=5000, trace=TRUE, traceDE=0,
momentFUN="crra.moments")
```
```{r, echo=FALSE}
load("optimization_results/opt.crra.rda")
```
```{r, tidy=FALSE}
head(extractStats(opt.crra),4)
```
<!--
remember to specify a momentFUN to match the arguments in CRRA
-->
---
## Chart Results
```{r, eval=FALSE}
chart.RiskReward(opt.crra, risk.col="ES")
chart.RiskReward(opt.crra, risk.col="StdDev")
```
![](figures/crra_RR_ES.png)
![](figures/crra_RR_StdDev.png)
<!--
It is very interesting to look at the feasible space in terms of different measures for risk. It appears that the optimal CRRA portfolio is close to the minimum StdDev portfolio, but nowhere near the minimum ES portfolio.
-->
---
## Run Backtest and Compute Returns
```{r, eval=FALSE, tidy=FALSE}
bt.opt.crra <- optimize.portfolio.rebalancing(R, portf.crra,
optimize_method="DEoptim",
search_size=5000, trace=TRUE,
traceDE=0,
momentFUN="crra.moments",
rebalance_on=rebal.freq,
training_period=training,
trailing_periods=trailing)
ret.crra <- summary(bt.opt.crra)$portfolio_returns
colnames(ret.crra) <- "CRRA"
```
<!---
Run optimization and extract the portfolio rebalancing returns from the summary method.
-->
---
## Chart Weights Through Time
```{r, eval=FALSE, tidy=FALSE, fig.align='center'}
chart.Weights(bt.opt.crra, main="CRRA Weights", col=bluemono)
```
![](figures/weights_crra.png)
<!--
slide comments
-->
---
## Chart Performance
```{r, eval=FALSE, tidy=FALSE}
charts.PerformanceSummary(cbind(ret.bt.opt, ret.crra),
main="Optimization Performance")
```
![](figures/ret_crra.png)
<!--
slide comments
-->
---
## Conclusion
* Introduced the goals and summary of PortfolioAnalytics
* Demonstrated the flexibility through examples
* Exciting plans for GSOC 2014
* Support for regime switching
* Support for supervised learning
* many more
#### Acknowledgements
Many thanks to...
* Google: funding for Google Summer of Code (GSoC)
* UW CF&RM Program: continued work on PortfolioAnalytics
* GSoC Mentors: Brian Peterson, Peter Carl, Doug Martin, and Guy Yollin
* R/Finance Committee
<!---
- One of the best things about GSoC is the opportunity to work and interact with the mentors.
- Thank the GSoC mentors for offering help and guidance during the GSoC project and after as I continued to work on the PortfolioAnalytics package.
- R/Finance Committee for the conference and the opportunity to talk about PortfolioAnalytics.
- Google for funding the Google Summer of Code for PortfolioAnalytics and many other proposals for R
-->
---
## PortfolioAnalytics Links
PortfolioAnalytics is on R-Forge in the ReturnAnalytics project
* [PortfolioAnalytics](https://r-forge.r-project.org/projects/returnanalytics/)
Source code for the slides
* https://github.com/rossb34/PortfolioAnalyticsPresentation
and view it here
* http://rossb34.github.io/PortfolioAnalyticsPresentation/
---
## Any Questions?
---
## References and Useful Links
* [ROI](http://cran.r-project.org/web/packages/ROI/index.html)
* [DEoptim](http://cran.r-project.org/web/packages/DEoptim/index.html)
* [pso](http://cran.r-project.org/web/packages/pso/index.html)
* [GenSA](http://cran.r-project.org/web/packages/GenSA/index.html)
* [PerformanceAnalytics](http://cran.r-project.org/web/packages/PerformanceAnalytics/index.html)
* [Patrick Burns Random Portfolios](http://www.burns-stat.com/pages/Finance/randport_practice_theory_annotated.pdf)
* [W.T. Shaw Random Portfolios](http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1856476)
* Martellini paper
* Boudt paper
* [Shiny App](http://spark.rstudio.com/rossbennett3/PortfolioOptimization/)