-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathportfolio_construction.R
1839 lines (1839 loc) · 67.6 KB
/
portfolio_construction.R
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
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
library(PortfolioAnalytics)
# Use ETF returns from package rutils
library(rutils)
symbolv <- c("VTI", "IEF", "DBC", "XLF",
"VNQ", "XLP", "XLV", "XLU", "XLB", "XLE")
# Initial portfolio to equal weights
portfi <- rep(1/NROW(symbolv), NROW(symbolv))
# Named vector
names(portfi) <- symbolv
# Create portfolio object
portfi <- portfolio.spec(assets=portfi)
library(PortfolioAnalytics)
# Add constraints
portf_maxSR <- add.constraint(
portfolio=portfi, # Initial portfolio
type="weightsum", # Constraint sum weights
min_sum=0.9, max_sum=1.1)
# Add constraints
portf_maxSR <- add.constraint(
portfolio=portf_maxSR,
type="long_only") # box constraint min=0, max=1
# Add objectives
portf_maxSR <- add.objective(
portfolio=portf_maxSR,
type="return", # Maximize mean return
name="mean")
# Add objectives
portf_maxSR <- add.objective(
portfolio=portf_maxSR,
type="risk", # Minimize stdev
name="stdev")
library(PortfolioAnalytics)
# Use ETF returns from package rutils
library(rutils)
symbolv <- c("VTI", "IEF", "DBC", "XLF",
"VNQ", "XLP", "XLV", "XLU", "XLB", "XLE")
# Initial portfolio to equal weights
portfi <- rep(1/NROW(symbolv), NROW(symbolv))
# Named vector
names(portfi) <- symbolv
# Create portfolio object
portfi <- portfolio.spec(assets=portfi)
library(PortfolioAnalytics)
# Add constraints
portf_maxSR <- add.constraint(
portfolio=portfi, # Initial portfolio
type="weightsum", # Constraint sum weights
min_sum=0.9, max_sum=1.1)
# Add constraints
portf_maxSR <- add.constraint(
portfolio=portf_maxSR,
type="long_only") # box constraint min=0, max=1
# Add objectives
portf_maxSR <- add.objective(
portfolio=portf_maxSR,
type="return", # Maximize mean return
name="mean")
# Add objectives
portf_maxSR <- add.objective(
portfolio=portf_maxSR,
type="risk", # Minimize stdev
name="stdev")
# Calculate daily stock returns
symbolv <- c("VTI", "IEF", "DBC")
nstocks <- NROW(symbolv)
retp <- na.omit(rutils::etfenv$returns[, symbolv])
# Calculate covariance matrix of returns and its inverse
covmat <- cov(retp)
covinv <- solve(a=covmat)
unitv <- rep(1, nstocks)
# Calculate the minimum variance weights
c11 <- drop(t(unitv) %*% covinv %*% unitv)
weightmv <- drop(covinv %*% unitv/c11)
# Calculate the daily minvar portfolio returns in two ways
retmv <- (retp %*% weightmv)
all.equal(retmv, (retp %*% covinv %*% unitv)/c11)
# Calculate the minimum variance in three ways
all.equal(var(retmv),
t(weightmv) %*% covmat %*% weightmv,
1/(t(unitv) %*% covinv %*% unitv))
# Calculate vector of mean returns
retm <- colMeans(retp)
# Specify the target return
retarg <- 1.5*mean(retp)
# Products of inverse with mean returns and unit vector
c11 <- drop(t(unitv) %*% covinv %*% unitv)
cr1 <- drop(t(unitv) %*% covinv %*% retm)
crr <- drop(t(retm) %*% covinv %*% retm)
fmat <- matrix(c(c11, cr1, cr1, crr), nc=2)
# Solve for the Lagrange multipliers
lagm <- solve(a=fmat, b=c(2, 2*retarg))
# Calculate the efficient portfolio weights
weightv <- 0.5*drop(covinv %*% cbind(unitv, retm) %*% lagm)
# Calculate constraints
all.equal(1, sum(weightv))
all.equal(retarg, sum(retm*weightv))
# Calculate the efficient portfolio returns
reteff <- drop(retp %*% weightv)
reteffm <- mean(reteff)
all.equal(reteffm, retarg)
# Calculate the efficient portfolio variance in three ways
uu <- c(1, retarg)
finv <- solve(fmat)
detf <- (c11*crr-cr1^2) # det(fmat)
all.equal(var(reteff),
drop(t(uu) %*% finv %*% uu),
(c11*reteffm^2-2*cr1*reteffm+crr)/detf)
# Calculate the daily and mean minvar portfolio returns
c11 <- drop(t(unitv) %*% covinv %*% unitv)
weightv <- drop(covinv %*% unitv/c11)
retmv <- (retp %*% weightv)
retmvm <- sum(weightv*retm)
# Calculate the minimum variance
varmv <- 1/c11
stdevmv <- sqrt(varmv)
# Calculate efficient frontier from target returns
retargv <- retmvm*(1+seq(from=(-1), to=1, by=0.1))
stdevs <- sapply(retargv, function(rett) {
uu <- c(1, rett)
sqrt(drop(t(uu) %*% finv %*% uu))
}) # end sapply
# Plot the efficient frontier
plot(x=stdevs, y=retargv, t="l", col="blue", lwd=2,
main="Efficient Frontier and Minimum Variance Portfolio",
xlab="standard deviation", ylab="return")
points(x=stdevmv, y=retmvm, col="green", lwd=6)
text(x=stdevmv, y=retmvm, labels="minimum \nvariance",
pos=4, cex=0.8)
# Calculate standard deviation of efficient portfolio
uu <- c(1, retarg)
stdeveff <- sqrt(drop(t(uu) %*% finv %*% uu))
# Calculate the slope of the tangent line
detf <- (c11*crr-cr1^2) # det(fmat)
sharper <- (stdeveff*detf)/(c11*retarg-cr1)
# Calculate the risk-free rate as intercept of the tangent line
raterf <- retarg - sharper*stdeveff
# Calculate the risk-free rate from target return
all.equal(raterf,
(retarg*cr1-crr)/(retarg*c11-cr1))
# Plot efficient frontier
aspectr <- 1.0*max(stdevs)/diff(range(retargv)) # Aspect ratio
plot(x=stdevs, y=retargv, t="l", col="blue", lwd=2, asp=aspectr,
xlim=c(0.4, 0.6)*max(stdevs), ylim=c(0.2, 0.9)*max(retargv),
main="Efficient Frontier and Capital Market Line",
xlab="standard deviation", ylab="return")
# Plot the minimum variance portfolio
points(x=stdevmv, y=retmvm, col="green", lwd=6)
text(x=stdevmv, y=retmvm, labels="minimum \nvariance",
pos=4, cex=0.8)
# Plot the tangent portfolio
points(x=stdeveff, y=retarg, col="red", lwd=6)
text(x=stdeveff, y=retarg, labels="tangency\nportfolio", pos=2, cex=0.8)
# Plot the risk-free point
points(x=0, y=raterf, col="red", lwd=6)
text(x=0, y=raterf, labels="risk-free", pos=4, cex=0.8)
# Plot the tangent line
abline(a=raterf, b=sharper, lwd=2, col="green")
text(x=0.6*stdev, y=0.8*retarg,
labels="Capital Market Line", pos=2, cex=0.8,
srt=180/pi*atan(aspectr*sharper))
# Calculate the mean excess returns
raterf <- retarg - sharper*stdeveff
retx <- (retm - raterf)
# Calculate the efficient portfolio weights
weightv <- 0.5*drop(covinv %*% cbind(unitv, retm) %*% lagm)
# Calculate the maximum Sharpe weights
weightms <- drop(covinv %*% retx)/sum(covinv %*% retx)
all.equal(weightv, weightms)
# Calculate the maximum Sharpe mean return in two ways
all.equal(sum(retm*weightv), (cr1*raterf-crr)/(c11*raterf-cr1))
# Calculate the maximum Sharpe daily returns
retd <- (retp %*% weightms)
# Calculate the maximum Sharpe variance in four ways
detf <- (c11*crr-cr1^2) # det(fmat)
all.equal(var(retd),
t(weightv) %*% covmat %*% weightv,
(t(retx) %*% covinv %*% retx)/sum(covinv %*% retx)^2,
(c11*retarg^2-2*cr1*retarg+crr)/detf)
# Calculate the maximum Sharpe ratio
sqrt(252)*sum(weightv*retx)/
sqrt(drop(t(weightv) %*% covmat %*% weightv))
# Calculate the stock Sharpe ratios
sqrt(252)*sapply((retp - raterf), function(x) mean(x)/sd(x))
# Calculate optimal portfolio returns
wealthv <- cbind(retp %*% weightms, retp %*% weightmv)
wealthv <- xts::xts(wealthv, zoo::index(retp))
colnames(wealthv) <- c("MaxSharpe", "MinVar")
# Calculate the Sharpe and Sortino ratios
sqrt(252)*sapply(wealthv,
function(x) c(Sharpe=(mean(x)-raterf)/sd(x), Sortino=(mean(x)-raterf)/sd(x[x<0])))
# Plot the log wealth
endd <- rutils::calc_endpoints(retp, interval="weeks")
dygraphs::dygraph(cumsum(wealthv)[endd],
main="Maximum Sharpe and Minimum Variance Portfolios") %>%
dyOptions(colors=c("blue", "green"), strokeWidth=2) %>%
dyLegend(show="always", width=500)
# Calculate the maximum Sharpe portfolios for different risk-free rates
detf <- (c11*crr-cr1^2) # det(fmat)
raterfv <- retmvm*seq(from=1.3, to=20, by=0.1)
raterfv <- c(raterfv, retmvm*seq(from=(-20), to=0.7, by=0.1))
effront <- sapply(raterfv, function(raterf) {
# Calculate the maximum Sharpe mean return
reteffm <- (cr1*raterf-crr)/(c11*raterf-cr1)
# Calculate the maximum Sharpe standard deviation
stdev <- sqrt((c11*reteffm^2-2*cr1*reteffm+crr)/detf)
c(return=reteffm, stdev=stdev)
}) # end sapply
effront <- effront[, order(effront["return", ])]
# Plot the efficient frontier
reteffv <- effront["return", ]
stdevs <- effront["stdev", ]
aspectr <- 0.6*max(stdevs)/diff(range(reteffv)) # Aspect ratio
plot(x=stdevs, y=reteffv, t="l", col="blue", lwd=2, asp=aspectr,
main="Maximum Sharpe Portfolio and Efficient Frontier",
xlim=c(0.0, max(stdevs)), xlab="standard deviation", ylab="return")
# Plot the minimum variance portfolio
points(x=stdevmv, y=retmvm, col="green", lwd=6)
text(x=stdevmv, y=retmvm, labels="minimum \nvariance", pos=4, cex=0.8)
# Calculate the maximum Sharpe return and standard deviation
raterf <- min(reteffv)
retmax <- (cr1*raterf-crr)/(c11*raterf-cr1)
stdevmax <- sqrt((c11*retmax^2-2*cr1*retmax+crr)/detf)
# Plot the maximum Sharpe portfolio
points(x=stdevmax, y=retmax, col="red", lwd=6)
text(x=stdevmax, y=retmax, labels="Max Sharpe\nportfolio", pos=2, cex=0.8)
# Plot the risk-free point
points(x=0, y=raterf, col="red", lwd=6)
text(x=0, y=raterf, labels="risk-free", pos=4, cex=0.8)
# Plot the tangent line
sharper <- (stdevmax*detf)/(c11*retmax-cr1)
abline(a=raterf, b=sharper, lwd=2, col="green")
text(x=0.6*stdevmax, y=0.8*retmax, labels="Capital Market Line",
pos=2, cex=0.8, srt=180/pi*atan(aspectr*sharper))
# Plot the efficient frontier
reteffv <- effront["return", ]
stdevs <- effront["stdev", ]
plot(x=stdevs, y=reteffv, t="l", col="blue", lwd=2,
xlim=c(0.0, max(stdevs)),
main="Efficient Frontier and Tangent Lines",
xlab="standard deviation", ylab="return")
# Calculate vector of mean returns
reteffv <- min(reteffv) + diff(range(reteffv))*c(0.2, 0.4, 0.6, 0.8)
# Plot the tangent lines
for (reteffm in reteffv) {
# Calculate the maximum Sharpe standard deviation
stdev <- sqrt((c11*reteffm^2-2*cr1*reteffm+crr)/detf)
# Calculate the slope of the tangent line
sharper <- (stdev*detf)/(c11*reteffm-cr1)
# Calculate the risk-free rate as intercept of the tangent line
raterf <- reteffm - sharper*stdev
# Plot the tangent portfolio
points(x=stdev, y=reteffm, col="red", lwd=3)
# Plot the tangent line
abline(a=raterf, b=sharper, lwd=2, col="green")
} # end for
# Calculate random portfolios
nportf <- 1000
randportf <- sapply(1:nportf, function(it) {
weightv <- runif(nstocks-1, min=-0.25, max=1.0)
weightv <- c(weightv, 1-sum(weightv))
# Portfolio returns and standard deviation
c(return=252*sum(weightv*retm),
stdev=sqrt(252*drop(weightv %*% covmat %*% weightv)))
}) # end sapply
# Plot scatterplot of random portfolios
x11(widthp <- 6, heightp <- 6)
plot(x=randportf["stdev", ], y=randportf["return", ],
main="Efficient Frontier and Random Portfolios",
xlim=c(0.5*stdev, 0.8*max(randportf["stdev", ])),
xlab="standard deviation", ylab="return")
# Plot maximum Sharpe portfolios
lines(x=effront[, "stdev"], y=effront[, "return"], lwd=2)
points(x=effront[, "stdev"], y=effront[, "return"],
col="red", lwd=3)
# Plot the minimum variance portfolio
points(x=stdev, y=retp, col="green", lwd=6)
text(stdev, retp, labels="minimum\nvariance", pos=2, cex=0.8)
# Plot efficient portfolio
points(x=effront[marketp, "stdev"],
y=effront[marketp, "return"], col="green", lwd=6)
text(x=effront[marketp, "stdev"], y=effront[marketp, "return"],
labels="market\nportfolio", pos=2, cex=0.8)
# Plot individual assets
points(x=sqrt(252*diag(covmat)),
y=252*retm, col="blue", lwd=6)
text(x=sqrt(252*diag(covmat)), y=252*retm,
labels=names(retm),
col="blue", pos=1, cex=0.8)
# Vector of symbol names
symbolv <- c("VTI", "IEF", "DBC")
nstocks <- NROW(symbolv)
# Calculate random portfolios
nportf <- 1000
randportf <- sapply(1:nportf, function(it) {
weightv <- runif(nstocks, min=0, max=10)
weightv <- weightv/sum(weightv)
retp <- rutils::etfenv$returns[, symbolv] %*% weightv
100*c(ret=mean(retp), sd=sd(retp))
}) # end sapply
# Plot scatterplot of random portfolios
x11(width=6, height=5)
plot(x=randportf[2, ], y=randportf[1, ], xlim=c(0, max(randportf[2, ])),
main="Random portfolios",
ylim=c(min(0, min(randportf[1, ])), max(randportf[1, ])),
xlab=rownames(randportf)[2], ylab=rownames(randportf)[1])
# Plot individual assets
points(x=sqrt(252*diag(covmat)),
y=252*retm, col="blue", lwd=6)
text(x=sqrt(252*diag(covmat)), y=252*retm,
labels=names(retm),
col="blue", pos=1, cex=0.8)
# Define the parameters
raterf <- 0.02 # Risk-free rate
retp <- c(stock1=0.06, stock2=0.09) # Returns
stdevs <- c(stock1=0.4, stock2=0.5) # Standard deviations
corrp <- 0.6 # Correlation
covmat <- matrix(c(1, corrp, corrp, 1), nc=2) # Covariance matrix
covmat <- t(t(stdevs*covmat)*stdevs)
weightv <- seq(from=(-1), to=2, length.out=71) # Weights
weightv <- cbind(weightv, 1-weightv)
retport <- weightv %*% retp # Portfolio returns
portfsd <- sqrt(rowSums(weightv*(weightv %*% covmat))) # Portfolio volatility
sharper <- (retport-raterf)/portfsd # Portfolio Sharpe ratios
# Plot the efficient frontier
# x11(widthp <- 6, heightp <- 5) # Windows
dev.new(widthp <- 6, heightp <- 5, noRStudioGD=TRUE) # Mac
plot(portfsd, retport, t="l",
main=paste0("Efficient Frontier and CML for Two Stocks\ncorrelation = ", 100*corrp, "%"),
xlab="standard deviation", ylab="return",
lwd=2, col="orange", xlim=c(0, max(portfsd)), ylim=c(0.01, max(retport)))
# Add the maximum Sharpe portfolio
whichmax <- which.max(sharper)
sharpem <- max(sharper) # Maximum Sharpe ratio
retmax <- retport[whichmax]
sdeff <- portfsd[whichmax]
weightm <- round(weightv[whichmax], 2)
points(sdeff, retmax, col="blue", lwd=3)
text(x=sdeff, y=retmax, labels=paste(c("Max Sharpe\n",
structure(c(weightm, (1-weightm)), names=c("stock1", "stock2"))), collapse=" "),
pos=2, cex=0.8)
# Plot individual stocks
points(stdevs, retp, col="green", lwd=3)
text(stdevs, retp, labels=names(retp), pos=4, cex=0.8)
# Add point at risk-free rate and draw Capital Market Line
points(x=0, y=raterf, col="blue", lwd=3)
text(0, raterf, labels="risk-free\nrate", pos=4, cex=0.8)
abline(a=raterf, b=sharpem, lwd=2, col="blue")
rangev <- par("usr")
text(sdeff/2, (retmax+raterf)/2,
labels="Capital Market Line", cex=0.8, , pos=3,
srt=45*atan(sharpem*(rangev[2]-rangev[1])/
(rangev[4]-rangev[3])*heightp/widthp)/(0.25*pi))
# Plot portfolios in x11() window
x11(widthp <- 6, heightp <- 5)
par(oma=c(0, 0, 0, 0), mar=c(3,3,2,1)+0.1, mgp=c(2, 1, 0), cex.lab=1.0, cex.axis=1.0, cex.main=1.0, cex.sub=1.0)
# Vector of symbol names
symbolv <- c("VTI", "IEF")
# Matrix of portfolio weights
weightv <- seq(from=(-1), to=2, length.out=31)
weightv <- cbind(weightv, 1-weightv)
# Calculate portfolio returns and volatilities
retp <- na.omit(rutils::etfenv$returns[, symbolv])
retport <- retp %*% t(weightv)
portfv <- cbind(252*colMeans(retport),
sqrt(252)*matrixStats::colSds(retport))
colnames(portfv) <- c("returns", "stdev")
raterf <- 0.06
portfv <- cbind(portfv,
(portfv[, "returns"]-raterf)/portfv[, "stdev"])
colnames(portfv)[3] <- "Sharpe"
whichmax <- which.max(portfv[, "Sharpe"])
sharpem <- portfv[whichmax, "Sharpe"]
plot(x=portfv[, "stdev"], y=portfv[, "returns"],
main="Stock and Bond portfolios", t="l",
xlim=c(0, 0.7*max(portfv[, "stdev"])), ylim=c(0, max(portfv[, "returns"])),
xlab="standard deviation", ylab="return")
# Add blue point for efficient portfolio
points(x=portfv[whichmax, "stdev"], y=portfv[whichmax, "returns"], col="blue", lwd=6)
text(x=portfv[whichmax, "stdev"], y=portfv[whichmax, "returns"],
labels=paste(c("efficient portfolio\n",
structure(c(weightv[whichmax, 1], weightv[whichmax, 2]), names=symbolv)), collapse=" "),
pos=3, cex=0.8)
# Plot individual stocks
retm <- 252*sapply(retport, mean)
stdevs <- sqrt(252)*sapply(retport, sd)
points(stdevs, retm, col="green", lwd=6)
text(stdevs, retm, labels=names(retport), pos=2, cex=0.8)
# Add point at risk-free rate and draw Capital Market Line
points(x=0, y=raterf, col="blue", lwd=6)
text(0, raterf, labels="risk-free", pos=4, cex=0.8)
abline(a=raterf, b=sharpem, col="blue", lwd=2)
rangev <- par("usr")
text(max(portfv[, "stdev"])/3, 0.75*max(portfv[, "returns"]),
labels="Capital Market Line", cex=0.8, , pos=3,
srt=45*atan(sharpem*(rangev[2]-rangev[1])/
(rangev[4]-rangev[3])*
heightp/widthp)/(0.25*pi))
# Plot portfolios in x11() window
x11(widthp <- 6, heightp <- 5)
# Calculate cumulative returns of VTI and IEF
retsoptim <- lapply(retp, function(retp) exp(cumsum(retp)))
retsoptim <- rutils::do_call(cbind, retsoptim)
# Calculate the efficient portfolio returns
retsoptim <- cbind(exp(cumsum(retp %*%
c(weightv[whichmax], 1-weightv[whichmax]))),
retsoptim)
colnames(retsoptim)[1] <- "efficient"
# Plot efficient portfolio with custom line colors
plot_theme <- chart_theme()
plot_theme$col$line.col <- c("orange", "blue", "green")
chart_Series(retsoptim, theme=plot_theme,
name="Efficient Portfolio for Stocks and Bonds")
legend("top", legend=colnames(retsoptim),
cex=0.8, inset=0.1, bg="white", lty=1,
lwd=6, col=plot_theme$col$line.col, bty="n")
library(rutils)
library(Rglpk)
# Vector of symbol names
symbolv <- c("VTI", "IEF", "DBC")
nstocks <- NROW(symbolv)
# Calculate the objective vector - the mean returns
retp <- na.omit(rutils::etfenv$returns[, symbolv])
objvec <- colMeans(retp)
# Specify matrix of linear constraint coefficients
coeffm <- matrix(c(rep(1, nstocks), 1, 1, 0),
nc=nstocks, byrow=TRUE)
# Specify the logical constraint operators
logop <- c("==", "<=")
# Specify the vector of constraints
consv <- c(1, 0)
# Specify box constraints (-1, 1) (default is c(0, Inf))
boxc <- list(lower=list(ind=1:nstocks, val=rep(-1, nstocks)),
upper=list(ind=1:nstocks, val=rep(1, nstocks)))
# Perform optimization
optiml <- Rglpk::Rglpk_solve_LP(
obj=objvec,
mat=coeffm,
dir=logop,
rhs=consv,
bounds=boxc,
max=TRUE)
all.equal(optiml$optimum, sum(objvec*optiml$solution))
optiml$solution
coeffm %*% optiml$solution
# Calculate the VTI percentage returns
retp <- na.omit(rutils::etfenv$returns$VTI)
confl <- 0.1
varisk <- quantile(retp, confl)
cvar <- mean(retp[retp < varisk])
# Or
sortv <- sort(as.numeric(retp))
varind <- round(confl*NROW(retp))
varisk <- sortv[varind]
cvar <- mean(sortv[1:varind])
# Plot histogram of VTI returns
varmin <- (-0.05)
histp <- hist(retp, col="lightgrey",
xlab="returns", breaks=100, xlim=c(varmin, 0.01),
ylab="frequency", freq=FALSE, main="VTI Returns Histogram")
# Plot density of losses
densv <- density(retp, adjust=1.5)
lines(densv, lwd=3, col="blue")
# Add line for VaR
abline(v=varisk, col="red", lwd=3)
ymax <- max(densv$y)
text(x=varisk, y=2*ymax/3, labels="VaR", lwd=2, pos=2)
# Add shading for CVaR
rangev <- (densv$x < varisk) & (densv$x > varmin)
polygon(
c(varmin, densv$x[rangev], varisk),
c(0, densv$y[rangev], 0),
col=rgb(1, 0, 0,0.5), border=NA)
text(x=1.5*varisk, y=ymax/7, labels="CVaR", lwd=2, pos=2)
library(rutils) # Load rutils
library(Rglpk)
# Vector of symbol names and returns
symbolv <- c("VTI", "IEF", "DBC")
nstocks <- NROW(symbolv)
retp <- na.omit(rutils::etfenv$returns[, symbolv])
retm <- colMeans(retp)
confl <- 0.05
rmin <- 0 ; wmin <- 0 ; wmax <- 1
weightsum <- 1
ncols <- NCOL(retp) # number of assets
nrows <- NROW(retp) # number of rows
# Create objective vector
objvec <- c(numeric(ncols), rep(-1/(confl/nrows), nrows), -1)
# Specify matrix of linear constraint coefficients
coeffm <- rbind(cbind(rbind(1, retm),
matrix(data=0, nrow=2, ncol=(nrows+1))),
cbind(coredata(retp), diag(nrows), 1))
# Specify the logical constraint operators
logop <- c("==", ">=", rep(">=", nrows))
# Specify the vector of constraints
consv <- c(weightvum, rmin, rep(0, nrows))
# Specify box constraints (wmin, wmax) (default is c(0, Inf))
boxc <- list(lower=list(ind=1:ncols, val=rep(wmin, ncols)),
upper=list(ind=1:ncols, val=rep(wmax, ncols)))
# Perform optimization
optiml <- Rglpk_solve_LP(obj=objvec, mat=coeffm, dir=logop, rhs=consv, types=rep("C", NROW(objvec)), max=T, bounds=boxc)
all.equal(optiml$optimum, sum(objvec*optiml$solution))
coeffm %*% optiml$solution
as.numeric(optiml$solution[1:ncols])
# Calculate daily percentage returns
symbolv <- c("VTI", "IEF", "DBC")
nstocks <- NROW(symbolv)
retp <- na.omit(rutils::etfenv$returns[, symbolv])
# Create initial vector of portfolio weights
weightv <- rep(1, NROW(symbolv))
names(weightv) <- symbolv
# Objective equal to minus Sharpe ratio
objfun <- function(weightv, retp) {
retp <- retp %*% weightv
if (sd(retp) == 0)
return(0)
else
-return(mean(retp)/sd(retp))
} # end objfun
# Objective for equal weight portfolio
objfun(weightv, retp=retp)
optiml <- unlist(optimize(f=function(weightv)
objfun(c(1, 1, weightv), retp=retp),
interval=c(-4, 1)))
# Vectorize objective function with respect to third weight
objvec <- function(weightv) sapply(weightv,
function(weightv) objfun(c(1, 1, weightv), retp=retp))
# Or
objvec <- Vectorize(FUN=function(weightv)
objfun(c(1, 1, weightv), retp=retp),
vectorize.args="weightv") # end Vectorize
objvec(1)
objvec(1:3)
# Plot objective function with respect to third weight
curve(expr=objvec, type="l", xlim=c(-4.0, 1.0),
xlab=paste("weight of", names(weightv[3])),
ylab="", lwd=2)
title(main="Objective Function", line=(-1)) # Add title
points(x=optiml[1], y=optiml[2], col="green", lwd=6)
text(x=optiml[1], y=optiml[2],
labels="minimum objective", pos=4, cex=0.8)
#below is simplified code for plotting objective function
# Create vector of DBC weights
weightv <- seq(from=-4, to=1, by=0.1)
objv <- sapply(weightv, function(weightv)
objfun(c(1, 1, weightv)))
plot(x=weightv, y=objv, t="l",
xlab="weight of DBC", ylab="", lwd=2)
title(main="Objective Function", line=(-1)) # Add title
points(x=optiml[1], y=optiml[2], col="green", lwd=6)
text(x=optiml[1], y=optiml[2],
labels="minimum objective", pos=4, cex=0.8)
# Vectorize function with respect to all weights
objvec <- Vectorize(
FUN=function(w1, w2, w3) objfun(c(w1, w2, w3), retp),
vectorize.args=c("w2", "w3")) # end Vectorize
# Calculate objective on 2-d (w2 x w3) parameter grid
w2 <- seq(-3, 7, length=50)
w3 <- seq(-5, 5, length=50)
gridm <- outer(w2, w3, FUN=objvec, w1=1)
rownames(gridm) <- round(w2, 2)
colnames(gridm) <- round(w3, 2)
# Perspective plot of objective function
persp(w2, w3, -gridm,
theta=45, phi=30, shade=0.5,
col=rainbow(50), border="green",
main="objective function")
# Interactive perspective plot of objective function
library(rgl)
rgl::persp3d(z=-gridm, zlab="objective",
col="green", main="objective function")
rgl::persp3d(
x=function(w2, w3) {-objvec(w1=1, w2, w3)},
xlim=c(-3, 7), ylim=c(-5, 5),
col="green", axes=FALSE)
# Render the 3d surface plot of function
rgl::rglwidget(elementId="plot3drgl", width=1000, height=1000)
# Vector of initial portfolio weights equal to 1
weightv <- rep(1, nstocks)
names(weightv) <- symbolv
# Objective function equal to standard deviation of returns
objfun <- function(weightv) {
retp <- retp %*% weightv
sd(retp)/sum(weightv)
} # end objfun
# objfun() for equal weight portfolio
objfun(weightv)
objfun(2*weightv)
# Perform portfolio optimization
optiml <- optim(par=weightv,
fn=objfun,
method="L-BFGS-B",
upper=rep(10, nstocks),
lower=rep(-10, nstocks))
# Rescale the optimal weights
weightv <- optiml$par/sum(optiml$par)
# Minimum variance portfolio returns
retsoptim <- xts(x=retp %*% weightv,
order.by=zoo::index(retp))
chart_Series(x=exp(cumsum(retsoptim)), name="minvar portfolio")
# Add green point for minimum variance portfolio
optim_sd <- 100*sd(retsoptim)
optim_ret <- 100*mean(retsoptim)
points(x=optim_sd, y=optim_ret, col="green", lwd=6)
text(x=optim_sd, y=optim_ret, labels="minvar", pos=2, cex=0.8)
# Objective function equal to minus Sharpe ratio
raterf <- 0.03
objfun <- function(weightv) {
retp <- 100*rutils::etfenv$returns[, names(weightv)] %*% weightv / sum(weightv)
-mean(retp-raterf)/sd(retp)
} # end objfun
# Perform portfolio optimization
optiml <- optim(par=weightv,
fn=objfun,
method="L-BFGS-B",
upper=rep(10, nstocks),
lower=rep(-10, nstocks))
# Maximum Sharpe ratio portfolio returns
weightv <- optiml$par/sum(optiml$par)
retsoptim <- xts(x=retp %*% weightv,
order.by=zoo::index(retp))
chart_Series(x=exp(cumsum(retsoptim)), name="maxSR portfolio")
optim_sd <- 100*sd(retsoptim)
optim_ret <- 100*mean(retsoptim)
points(x=optim_sd, y=optim_ret,
col="blue", lwd=3)
text(x=optim_sd, y=optim_ret,
labels="maxSR", pos=2, cex=0.8)
sharpem <- (optim_ret-raterf)/optim_sd
# Plot individual assets
retm <- 100*sapply(retp, mean)
stdevs <- 100*sapply(retp, sd)
points(stdevs, retm, col="green", lwd=3)
text(stdevs, retm, labels=names(retm), pos=2, cex=0.8)
# Add point at risk-free rate and draw Capital Market Line
points(x=0, y=raterf)
text(0, raterf, labels="risk-free", pos=4, cex=0.8)
abline(a=raterf, b=sharpem, col="blue")
rangev <- par("usr")
text(optim_sd/3, (optim_ret+raterf)/2.5,
labels="Capital Market Line", cex=0.8, , pos=3,
srt=45*atan(sharpem*(rangev[2]-rangev[1])/
(rangev[4]-rangev[3])*
heightp/widthp)/(0.25*pi))
# Create initial vector of portfolio weights
weightv <- rep(1, NROW(symbolv))
names(weightv) <- symbolv
# Optimization to find weights with maximum Sharpe ratio
optiml <- optim(par=weightv,
fn=objfun,
retp=retp,
method="L-BFGS-B",
upper=c(1.1, 10, 10),
lower=c(0.9, -10, -10))
# Optimal parameters
optiml$par
optiml$par <- optiml$par/sum(optiml$par)
# Optimal Sharpe ratio
-objfun(optiml$par)
x11(width=6, height=5)
par(oma=c(1, 1, 1, 0), mgp=c(2, 1, 0), mar=c(2, 1, 2, 1), cex.lab=0.8, cex.axis=0.8, cex.main=0.8, cex.sub=0.5)
# Plot in two vertical panels
layout(matrix(c(1,2), 2),
widths=c(1,1), heights=c(1,3))
# barplot of optimal portfolio weights
barplot(optiml$par, col=c("red", "green", "blue"),
main="Optimized portfolio weights")
# Calculate cumulative returns of VTI, IEF, DBC
retc <- lapply(retp,
function(retp) exp(cumsum(retp)))
retc <- rutils::do_call(cbind, retc)
# Calculate optimal portfolio returns with VTI, IEF, DBC
retsoptim <- cbind(
exp(cumsum(retp %*% optiml$par)),
retc)
colnames(retsoptim)[1] <- "retsoptim"
# Plot optimal returns with VTI, IEF, DBC
plot_theme <- chart_theme()
plot_theme$col$line.col <- c("black", "red", "green", "blue")
chart_Series(retsoptim, theme=plot_theme,
name="Optimized portfolio performance")
legend("top", legend=colnames(retsoptim), cex=1.0,
inset=0.1, bg="white", lty=1, lwd=6,
col=plot_theme$col$line.col, bty="n")
# Or plot non-compounded (simple) cumulative returns
PerformanceAnalytics::chart.CumReturns(
cbind(retp %*% optiml$par, retp),
lwd=2, ylab="", legend.loc="topleft", main="")
raterf <- 0.03
retp <- c(asset1=0.05, asset2=0.06)
stdevs <- c(asset1=0.4, asset2=0.5)
corrp <- 0.6
covmat <- matrix(c(1, corrp, corrp, 1), nc=2)
covmat <- t(t(stdevs*covmat)*stdevs)
library(quadprog)
# Minimum variance weights without constraints
optiml <- solve.QP(Dmat=2*covmat,
dvec=rep(0, 2),
Amat=matrix(0, nr=2, nc=1),
bvec=0)
# Minimum variance weights sum equal to 1
optiml <- solve.QP(Dmat=2*covmat,
dvec=rep(0, 2),
Amat=matrix(1, nr=2, nc=1),
bvec=1)
# Optimal value of objective function
t(optiml$solution) %*% covmat %*% optiml$solution
Perform simple optimization for reference
# Objective function for simple optimization
objfun <- function(x) {
x <- c(x, 1-x)
t(x) %*% covmat %*% x
} # end objfun
unlist(optimize(f=objfun, interval=c(-1, 2)))
# Calculate daily percentage returns
symbolv <- c("VTI", "IEF", "DBC")
nstocks <- NROW(symbolv)
retp <- na.omit(rutils::etfenv$returns[, symbolv])
# Calculate the covariance matrix
covmat <- cov(retp)
# Minimum variance weights, with sum equal to 1
optiml <- quadprog::solve.QP(Dmat=2*covmat,
dvec=numeric(3),
Amat=matrix(1, nr=3, nc=1),
bvec=1)
# Minimum variance, maximum returns
optiml <- quadprog::solve.QP(Dmat=2*covmat,
dvec=apply(0.1*retp, 2, mean),
Amat=matrix(1, nr=3, nc=1),
bvec=1)
# Minimum variance positive weights, sum equal to 1
a_mat <- cbind(matrix(1, nr=3, nc=1),
diag(3), -diag(3))
b_vec <- c(1, rep(0, 3), rep(-1, 3))
optiml <- quadprog::solve.QP(Dmat=2*covmat,
dvec=numeric(3),
Amat=a_mat,
bvec=b_vec,
meq=1)
# Rastrigin function with vector argument for optimization
rastrigin <- function(vecv, param=25){
sum(vecv^2 - param*cos(vecv))
} # end rastrigin
vecv <- c(pi/6, pi/6)
rastrigin(vecv=vecv)
library(DEoptim)
# Optimize rastrigin using DEoptim
optiml <- DEoptim(rastrigin,
upper=c(6, 6), lower=c(-6, -6),
DEoptim.control(trace=FALSE, itermax=50))
# Optimal parameters and value
optiml$optim$bestmem
rastrigin(optiml$optim$bestmem)
summary(optiml)
plot(optiml)
# Calculate daily percentage returns
symbolv <- c("VTI", "IEF", "DBC")
nstocks <- NROW(symbolv)
retp <- na.omit(rutils::etfenv$returns[, symbolv])
# Objective equal to minus Sharpe ratio
objfun <- function(weightv, retp) {
retp <- retp %*% weightv
if (sd(retp) == 0)
return(0)
else
-return(mean(retp)/sd(retp))
} # end objfun
# Perform optimization using DEoptim
optiml <- DEoptim::DEoptim(fn=objfun,
upper=rep(10, NCOL(retp)),
lower=rep(-10, NCOL(retp)),
retp=retp,
control=list(trace=FALSE, itermax=100, parallelType=1))
weightv <- optiml$optim$bestmem/sum(abs(optiml$optim$bestmem))
names(weightv) <- colnames(retp)
# Objective with shrinkage penalty
objfun <- function(weightv, retp, lambdaf, alpha) {
retp <- retp %*% weightv
if (sd(retp) == 0)
return(0)
else {
penaltyv <- lambdaf*((1-alpha)*sum(weightv^2) +
alpha*sum(abs(weightv)))
-return(mean(retp)/sd(retp) + penaltyv)
}
} # end objfun
# Objective for equal weight portfolio
weightv <- rep(1, NROW(symbolv))
names(weightv) <- symbolv
lambdaf <- 0.5 ; alpha <- 0.5
objfun(weightv, retp=retp, lambdaf=lambdaf, alpha=alpha)
# Perform optimization using DEoptim
optiml <- DEoptim::DEoptim(fn=objfun,
upper=rep(10, NCOL(retp)),
lower=rep(-10, NCOL(retp)),
retp=retp,
lambdaf=lambdaf,
alpha=alpha,
control=list(trace=FALSE, itermax=100, parallelType=1))
weightv <- optiml$optim$bestmem/sum(abs(optiml$optim$bestmem))
names(weightv) <- colnames(retp)
# Objective with shrinkage penalty
objfun <- function(weightv, retp, lambdaf, alpha) {
retp <- retp %*% weightv
if (sd(retp) == 0)
return(0)
else {
penaltyv <- lambdaf*((1-alpha)*sum(weightv^2) +
alpha*sum(abs(weightv)))
-return(mean(retp)/sd(retp) + penaltyv)
}
} # end objfun
# Objective for equal weight portfolio
weightv <- rep(1, NROW(symbolv))
names(weightv) <- symbolv
lambdaf <- 0.5 ; alpha <- 0.5
objfun(weightv, retp=retp, lambdaf=lambdaf, alpha=alpha)
# Perform optimization using DEoptim
optiml <- DEoptim::DEoptim(fn=objfun,
upper=rep(10, NCOL(retp)),
lower=rep(-10, NCOL(retp)),
retp=retp,
lambdaf=lambdaf,
alpha=alpha,
control=list(trace=FALSE, itermax=100, parallelType=1))
weightv <- optiml$optim$bestmem/sum(abs(optiml$optim$bestmem))
names(weightv) <- colnames(retp)
# Portfolio optimization
library(PortfolioAnalytics) # load package "PortfolioAnalytics"
# get documentation for package "PortfolioAnalytics"
packageDescription("PortfolioAnalytics") # get short description
help(package="PortfolioAnalytics") # load help page
data(package="PortfolioAnalytics") # list all datasets in "PortfolioAnalytics"
ls("package:PortfolioAnalytics") # list all objects in "PortfolioAnalytics"
detach("package:PortfolioAnalytics") # remove PortfolioAnalytics from search path
library(PortfolioAnalytics)
# Use ETF returns from package rutils
library(rutils)
symbolv <- c("VTI", "IEF", "DBC", "XLF",
"VNQ", "XLP", "XLV", "XLU", "XLB", "XLE")
# Initial portfolio to equal weights
portfi <- rep(1/NROW(symbolv), NROW(symbolv))
# named vector
names(portfi) <- symbolv
# Create portfolio object
portfi <- portfolio.spec(assets=portfi)
library(PortfolioAnalytics)
# Add constraints
portf_maxSR <- add.constraint(
portfolio=portfi, # Initial portfolio
type="weightsum", # Constraint sum weights
min_sum=0.9, max_sum=1.1)
# Add constraints
portf_maxSR <- add.constraint(
portfolio=portf_maxSR,
type="long_only") # box constraint min=0, max=1
# Add objectives
portf_maxSR <- add.objective(
portfolio=portf_maxSR,
type="return", # Maximize mean return
name="mean")
# Add objectives
portf_maxSR <- add.objective(
portfolio=portf_maxSR,
type="risk", # Minimize stdev
name="stdev")
load(file="/Users/jerzy/Develop/lecture_slides/data/portf_optim.RData")
library(PortfolioAnalytics)
# Perform optimization of weights
maxSR_DEOpt <- optimize.portfolio(
R=rutils::etfenv$returns[, symbolv], # Specify returns
portfolio=portf_maxSR, # Specify portfolio
optimize_method="DEoptim", # Use DEoptim
maxSR=TRUE, # Maximize Sharpe
trace=TRUE, traceDE=0)
# Plot optimization
chart.RiskReward(maxSR_DEOpt,
risk.col="stdev",
return.col="mean")
options(width=50)
library(PortfolioAnalytics)
load(file="/Users/jerzy/Develop/lecture_slides/data/portf_optim.RData")
maxSR_DEOpt$weights
maxSR_DEOpt$objective_measures$mean[1]
maxSR_DEOpt$objective_measures$stdev[[1]]
library(PortfolioAnalytics)
# Plot optimization
chart.RiskReward(maxSR_DEOpt,
risk.col="stdev",
return.col="mean")
# Plot risk/ret points in portfolio scatterplot
risk_ret_points <- function(rets=rutils::etfenv$returns,
risk=c("sd", "ETL"), symbolv=c("VTI", "IEF")) {
risk <- match.arg(risk) # Match to arg list
if (risk=="ETL") {
stopifnot(
"package:PerformanceAnalytics" %in% search() ||
require("PerformanceAnalytics", quietly=TRUE))
} # end if
risk <- match.fun(risk) # Match to function
risk_ret <- t(sapply(rets[, symbolv],
function(xtsv)
c(ret=mean(xtsv), risk=abs(risk(xtsv)))))
points(x=risk_ret[, "risk"], y=risk_ret[, "ret"],
col="red", lwd=3)
text(x=risk_ret[, "risk"], y=risk_ret[, "ret"],
labels=rownames(risk_ret), col="red",
lwd=2, pos=4)
} # end risk_ret_points
risk_ret_points()
library(PortfolioAnalytics)
plot_portf <- function(portfolio,
rets_data=rutils::etfenv$returns) {
weightv <- portfolio$weights
symbolv <- names(weightv)
# Calculate xts of portfolio
portf_max <- xts(
rets_data[, symbolv] %*% weightv,
order.by=zoo::index(rets_data))
colnames(portf_max) <-
deparse(substitute(portfolio))
graph_params <- par(oma=c(1, 0, 1, 0),
mgp=c(2, 1, 0), mar=c(2, 1, 2, 1),
cex.lab=0.8, cex.axis=1.0,
cex.main=0.8, cex.sub=0.5)
layout(matrix(c(1,2), 2),
widths=c(1,1), heights=c(1,3))
barplot(weightv, names.arg=symbolv,
las=3, ylab="", xlab="Symbol", main="")
title(main=paste("Loadings",
colnames(portf_max)), line=(-1))
chart.CumReturns(
cbind(portf_max, rets_data[, c("IEF", "VTI")]),
lwd=2, ylab="", legend.loc="topleft", main="")
title(main=paste0(colnames(portf_max),
", IEF, VTI"), line=(-1))
par(graph_params) # restore original parameters
invisible(portf_max)
} # end plot_portf
maxSR_DEOpt_xts <- plot_portf(portfolio=maxSR_DEOpt)
library(PortfolioAnalytics)
# Add leverage constraint abs(weightvum)
portf_maxSRN <- add.constraint(
portfolio=portfi, type="leverage",
min_sum=0.9, max_sum=1.1)
# Add box constraint long/short
portf_maxSRN <- add.constraint(
portfolio=portf_maxSRN,
type="box", min=-0.2, max=0.2)
# Add objectives
portf_maxSRN <- add.objective(
portfolio=portf_maxSRN,
type="return", # Maximize mean return
name="mean")
# Add objectives
portf_maxSRN <- add.objective(
portfolio=portf_maxSRN,
type="risk", # Minimize stdev
name="stdev")
load(file="/Users/jerzy/Develop/lecture_slides/data/portf_optim.RData")
library(PortfolioAnalytics)
# Perform optimization of weights
maxSRN_DEOpt <- optimize.portfolio(
R=rutils::etfenv$returns[, symbolv], # Specify returns
portfolio=portf_maxSRN, # Specify portfolio
optimize_method="DEoptim", # Use DEoptim
maxSR=TRUE, # Maximize Sharpe
trace=TRUE, traceDE=0)
# Plot optimization
chart.RiskReward(maxSRN_DEOpt,
risk.col="stdev",
return.col="mean",
xlim=c(
maxSR_DEOpt$objective_measures$stdev[[1]]-0.001,
0.016))
points(x=maxSR_DEOpt$objective_measures$stdev[[1]],
y=maxSR_DEOpt$objective_measures$mean[1],
col="green", lwd=3)
text(x=maxSR_DEOpt$objective_measures$stdev[[1]],
y=maxSR_DEOpt$objective_measures$mean[1],
labels="maxSR", col="green",
lwd=2, pos=4)
# Plot risk/ret points in portfolio scatterplot
risk_ret_points()
library(PortfolioAnalytics)
load(file="/Users/jerzy/Develop/lecture_slides/data/portf_optim.RData")
maxSRN_DEOpt$weights
maxSRN_DEOpt$objective_measures$mean[1]
maxSRN_DEOpt$objective_measures$stdev[[1]]
library(PortfolioAnalytics)
maxSRN_DEOpt_xts <- plot_portf(portfolio=maxSRN_DEOpt)
library(PerformanceAnalytics)
load(file="/Users/jerzy/Develop/lecture_slides/data/portf_optim.RData")
chart.CumReturns(
cbind(maxSR_DEOpt_xts, maxSRN_DEOpt_xts),
lwd=2, ylab="",
legend.loc="topleft", main="")
options(width=50)
library(PerformanceAnalytics)
load(file="/Users/jerzy/Develop/lecture_slides/data/portf_optim.RData")
rbind(maxSR_DEOpt$weights, maxSRN_DEOpt$weightv)