forked from sstoeckl/A03_Portfolios
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathA03_Portfolios.Rmd
737 lines (571 loc) · 23.8 KB
/
A03_Portfolios.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
---
title: "Portfoliomanagement and Financial Analysis - Assignment 3"
subtitle: "Submit until Monday 2020-10-07, 13:00"
author: "Amela, Dervisevic"
output: html_notebook
---
clear enviroment
```{r}
rm(list = ls())
```
```{r load_packs}
pacman::p_load(tidyverse,tidyquant,FFdownload,PortfolioAnalytics,tsibble,matrixcalc,Matrix)
```
---
**Please** remember to put your assignment solutions in `rmd` format using **many** chunks and putting readable text in between, similar to my examples given in Research Methods and Assignment 1! Also, each student has to select his own set of 10 stocks having data available as of `2000-01-01`. Select by Sharpe-ratio, dominance or any other method (e.g. matching your first name).
## Exercise 1: Optimzing portfolios
Take your personal dataset of 10 stocks, set the time-frame to January 2000/ August 2018 (use a year-month format - either `as.yearmon` from `zoo` or `yearmonth` from `tsibble`) and calculate monthly simple returns (if you have not done so yet)! Use `pivot_wider()` and `tk_xts()` to make a `xts` (timeseries) from it (having ten columns with simple returns calculated from adjusted prices).
Getting 10 stocks: ABCB, AAPL, ACLS, ADBE, ADTN, AEHR, AEIS, AHPI, AKAM, AMZN
Get the stock prices of the stocks from 2000-01-01 to 2018-08-31
Create a vector with the stocks I want to observe
```{r}
stockselection <- c("ABCB", "AAPL", "ACLS", "ADBE", "ADTN", "AEHR", "AEIS", "AHPI", "AKAM", "AMZN")
stockselection
```
### Get the stock prices
```{r}
stocks.prices <- stockselection %>%
tq_get(get = "stock.prices", from = "2000-01-01",to = "2018-08-31") %>%
dplyr::group_by(symbol) #get all stock prices and sort them by symbol
stocks.prices
```
### Create monthly return for the 10 stocks. Make 10 coumns for each stock one column with covmatrix.
```{r}
stocks.returns.monthly <- stocks.prices %>%
mutate(date=as.yearmon(date))%>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period="monthly",
type="arithmetic",
col_rename = "Stock.returns")
stocks.returns.monthly
```
```{r}
stock.returns.timeseries.xts <- pivot_wider(data = stocks.returns.monthly, names_from = symbol, values_from = Stock.returns)%>%
tk_xts(date_var = date, silent = TRUE)
stock.returns.timeseries.xts
```
a) As off now, we always perform the following steps before doing anything portfolio related: Check the summary/basic statistics and moments of the assets. Plot and check for (multivariate) normality (OPTIONAL). Check the correlations and do a scatterplot. Check the covariance/correlation structure.
```{r}
stock.returns.timeseries.mu.xts <- lapply(stock.returns.timeseries.xts,FUN=mean)
stock.returns.timeseries.mu.xts
```
### Calculate sigma (standard deviation) for each stock
```{r}
stock.returns.timeseries.sigma.xts <- lapply(stock.returns.timeseries.xts,FUN=sd)
stock.returns.timeseries.sigma.xts
```
### Calculate correlation matrix
```{r}
cormatrix <- cor(stock.returns.timeseries.xts)
cormatrix
```
### Plot the correlations
```{r}
chart.Correlation(R=stock.returns.timeseries.xts,method = "pearson"
)
```
### Calculate the covariance matrix
```{r}
covmatrix <- cov(stock.returns.timeseries.xts, use = "everything", method = "pearson")
covmatrix
```
b) Plot the average return of the assets against their standard deviation. Are there any dominated assets? Plot the efficient frontier using `chart.EfficientFrontier` and `chart.EF.Weights` (also check the `demo(demo_efficient_frontier)` from the `portfolioAnalytics`-package.
### Calculate MU and sigma and visualize them in a plot
```{r}
meanstocks <- stocks.returns.monthly %>%
dplyr::group_by(symbol) %>%
dplyr::summarize(mu = mean(Stock.returns, na.rm=TRUE))
stocks.returns.monthly
meanstocks
```
```{r}
sdstocks <- stocks.returns.monthly %>%
dplyr::group_by(symbol) %>%
dplyr::summarize(sigma = sd(Stock.returns, na.rm=TRUE))
sdstocks
sigmamu <- left_join(sdstocks, meanstocks, by = "symbol")
sigmamu
sigmamuggplot <- ggplot(sigmamu, aes(sigma, mu))+
geom_point()+
geom_label_repel(aes(label = symbol),
box.padding = 0.2,
point.padding = 0.1,
label.size = 0.2,
segment.color = 'grey50', size = 2.5)+
theme_classic()
sigmamuggplot
```
There is no dominant asset
c) Now comes the fun: Work through the vignette of the `portfolioAnalytics`-package
(`vignette("portfolio_vignette")`), set a full investment constraint and limit the portfolio weights to be 'long only' and calculate minimum-variance/maximum-return and quadratic utility portfolios.
## Limited to long only
```{r}
port <- portfolio.spec(assets = colnames(stock.returns.timeseries.xts),
category_labels = stockselection)
port <- add.constraint(portfolio=port, type="long_only")
meanvar.portf <- add.objective(portfolio=port, type="return", name="mean")
meanvar.portf <- add.objective(portfolio=port, type="risk", name="StdDev")
summary(meanvar.portf, digits=2)
prt_ef <- create.EfficientFrontier(R=stock.returns.timeseries.xts, portfolio=port, type="mean-StdDev", match.col = "StdDev")
chart.EfficientFrontier(prt_ef, match.col="StdDev", type="b", rf=NULL, pch.assets = 2)
chart.EF.Weights(prt_ef, colorset=rainbow(n = length(stockselection)), match.col="StdDev", cex.lab = 1, main = "StdDev")
```
### Set a full investment
```{r}
portfull <- portfolio.spec(assets = colnames(stock.returns.timeseries.xts))
portfull <- add.constraint(portfolio=portfull, type="full_investment")
meanvar.portf.full <- add.objective(portfolio=portfull, type="return", name="mean")
meanvar.portf.full <- add.objective(portfolio=portfull, type="risk", name="StdDev")
prt_ef_full <- create.EfficientFrontier(R=stock.returns.timeseries.xts, portfolio=portfull, type="mean-StdDev", match.col = "StdDev")
chart.EfficientFrontier(prt_ef_full, match.col="StdDev", type="b", rf=NULL, pch.assets = 1)
chart.EF.Weights(prt_ef_full, colorset=rainbow(n = length(stockselection)), match.col="StdDev", cex.lab = 1, main = "StdDev")
```
### Minimum varriance
```{r}
port_l <- portfolio.spec(assets = colnames(stock.returns.timeseries.xts))
port_l <- add.constraint(portfolio = port_l,
type = "long_only")
minvar <- add.objective(portfolio = port_l, type = "risk", name = "var")
opt_minvar <- optimize.portfolio(R=stock.returns.timeseries.xts, portfolio = minvar, optimize_method = "ROI", trace = TRUE)
print(opt_minvar)
plot(opt_minvar, risk.col="StdDev", return.col="mean",
main="Minimum Variance Optimization", chart.assets=TRUE,
xlim=c(0, 0.1), ylim=c(0,0.012))
```
### Maximize mean return with ROI
```{r}
maxret <-add.objective(portfolio=port_l, type="return", name="mean")
opt_maxret <- optimize.portfolio(R=stock.returns.timeseries.xts, portfolio=maxret,
optimize_method="ROI",
trace=TRUE)
print(opt_maxret)
plot(opt_maxret, risk.col="StdDev", return.col="mean",
main="Maximum Return Optimization", chart.assets=TRUE,
xlim=c(0, 0.3), ylim=c(0,0.013))
```
### Calculate quadratic utility portfolio
```{r}
qu <- add.objective(portfolio=port_l, type="return", name="mean")
qu <- add.objective(portfolio=qu, type="risk", name="var", risk_aversion=0.25)
opt_qu <- optimize.portfolio(R=stock.returns.timeseries.xts, portfolio=qu,
optimize_method="ROI",
trace=TRUE)
print(opt_qu)
plot(opt_qu, risk.col="StdDev", return.col="mean",
main="Quadratic Utility Optimization", chart.assets=TRUE,
xlim=c(0, 0.15), ylim=c(0, 0.015))
```
c) Allow for short selling (delete the long only constraint). What happens to your portfolio? Illustrate using the efficient frontier! Combine efficient frontiers using `chart.EfficientFrontierOverlay` to highlight the differences.
### short selling
```{r}
portf.list <- combine.portfolios(list(port, port_l))
legend.labels <- c("Full Investment", "Long Only")
chart.EfficientFrontierOverlay(R=stock.returns.timeseries.xts,
portfolio_list=portf.list, type="mean-StdDev",
match.col="StdDev", legend.loc="topleft",
legend.labels=legend.labels, cex.legend=0.6,
labels.assets=FALSE, pch.assets=1)
```
d) Play around with the constraints and see what happens. Illustrate using `chart.EfficientFrontierOverlay`.
```{r}
port_c <- add.constraint(portfolio=port, type="diversification", div_target=0.7)
port_c <- add.constraint(portfolio=port_c, type="box", min=0.05, max=0.4)
portf.list.c <- combine.portfolios(list(port, port_c, port_l))
legend.labels <- c("Full Investment", "Constraints", "Long Only")
chart.EfficientFrontierOverlay(R=stock.returns.timeseries.xts,
portfolio_list=portf.list.c, type="mean-StdDev",
match.col="StdDev", legend.loc="topleft",
legend.labels=legend.labels, cex.legend=0.6,
labels.assets=FALSE, pch.assets=1)
```
## Exercise 2: Do it yourself
In this exercise you first download the IBoxx Euro Corporate All Maturities ("IBCRPAL") and the EuroStoxx ("DJES50I") index from Datastream - monthly data as long as possible. We will check the calculations of `R`. Calculate discrete monthly returns.
downloaded it from datastream --> citrix (Thomson Reuters)
uploaded it on the right side --> as a excel (xlsx)
import dataset on the right side above --> the two of them
```{r}
Eurostoxx_correct <- read_xlsx("eurostoxx")
Eurostoxx_correct
View(Eurostoxx_correct)
Iboxx_correct <- read_xlsx("iboxx")
Iboxx_correct
View(Iboxx_correct)
```
### Calculate monthly returns for eurostoxx
```{r}
monthly_returns_eurostoxx <- eurostoxx %>%
mutate(date=as.yearmon(date), price=as.numeric(price))%>%
tq_transmute(select = price,
mutate_fun = periodReturn,
period="monthly",
type="arithmetic",
col_rename = "monthly_returns"
)
monthly_returns_eurostoxx
```
### then the same for iboxx
```{r}
monthly_returns_iboxx <- iboxx %>%
mutate(date=as.yearmon(date), price=as.numeric(price)) %>%
tq_transmute(select = price,
mutate_fun = periodReturn,
period="monthly",
type="arithmetic",
col_rename = "monthly_returns"
)
monthly_returns_iboxx
```
to use portfolioanalytics package we need our data in xts format
```{r}
eurostoxx_returns_xts <- monthly_returns_eurostoxx %>%
select(date,monthly_returns) %>%
tk_xts(silent = TRUE)
eurostoxx_returns_xts
```
```{r}
iboxx_returns_xts <- monthly_returns_iboxx %>%
select(date,monthly_returns) %>%
tk_xts(silent = TRUE)
iboxx_returns_xts
```
merge them together
```{r}
index_final <- left_join(monthly_returns_iboxx, monthly_returns_eurostoxx, by = "date")
index_final
returns_index_final_xts <- index_final %>%
select(date, monthly_returns.x, monthly_returns.y) %>%
tk_xts(silent = TRUE)
returns_index_final_xts
```
a) Stats/Normality (see A1)
Check the summary/basic statistics and moments of the assets. Plot and check for (multivariate) normality (OPTIONAL).
```{r}
monthly_returns_eurostoxx %>%
tq_performance(Ra = monthly_returns, Rb = NULL, performance_fun = table.Stats)
monthly_returns_eurostoxx
```
```{r}
monthly_returns_iboxx %>%
tq_performance(Ra = monthly_returns, Rb = NULL, performance_fun = table.Stats)
monthly_returns_iboxx
```
### plot a histogram to check normality
```{r}
monthly_returns_eurostoxx %>%
ggplot(aes(x=monthly_returns)) +
geom_histogram(aes(y=..density..), colour="black", fill="pink")
```
it is skewed to the left --> it is right steep , negatively skewed --> we see that in thhe skewness in table.Stats as well
but it is almost normally distributed
```{r}
monthly_returns_iboxx %>%
ggplot(aes(x=monthly_returns)) +
geom_histogram(aes(y=..density..), colour="black", fill="lightblue")
```
same as above
is more normally distributed
it kind of has just one outliner on the left
```{r}
qqnorm(monthly_returns_iboxx$monthly_returns)
```
we can see here as well that it is almost normally distributed --> almost a linear regression
```{r}
qqnorm(monthly_returns_eurostoxx$monthly_returns)
```
almost a straight line
b) Get the necessary input parameters (mu, sigma, please using variables, I don't want to see manual numbers in your code) and calculate the Minimum-Variance-Portfolio (manually in R). Then do it using the `portfolioAnalytics`-package.
### Calculate "mu" for each index
```{r}
returns_index_final_xts
colnames(returns_index_final_xts) <- c("iboxx", "eurostoxx")
returns_index_final_xts
```
```{r}
mu_returns_index_final_xts <- lapply(returns_index_final_xts, FUN=mean)
mu_returns_index_final_xts
```
### Calculate "sigma" for each index
```{r}
sigma_returns_index_final_xts <- lapply(returns_index_final_xts,FUN=sd)
sigma_returns_index_final_xts
```
calculate with the package
calculate the minimum-variance-portfolio
-vignette("portfolio_vignette")
-do not allow for short selling
```{r}
labels <- c("iboxx", "eurostoxx")
port_l <- portfolio.spec(assets = colnames(returns_index_final_xts), category_labels = labels)
port_l <- add.constraint(portfolio=port_l,type="long_only")
minvar <- add.objective(portfolio=port_l, type="risk", name="var")
opt_minvar <- optimize.portfolio(R=returns_index_final_xts, portfolio=minvar, optimize_method="ROI", trace=TRUE)
print(opt_minvar)
```
we would invest all in iboxx
With short selling
```{r}
# allow for shortselling
portf_minvar <- portfolio.spec(assets = colnames(returns_index_final_xts), category_labels = labels)
# Add full investment constraint to the portfolio object
portf_minvar <- add.constraint(portfolio=portf_minvar, type="full_investment")
minvarsh <- add.objective(portfolio=portf_minvar, type="risk", name="var")
opt_minvar <- optimize.portfolio(R=returns_index_final_xts, portfolio=minvarsh, optimize_method="ROI", trace=TRUE)
print(opt_minvar)
```
do it manually
### Calculate "mu" for each index separately to use them for calculation
```{r}
returns_eurostoxx <- monthly_returns_eurostoxx%>%
select(monthly_returns)
returns_iboxx <- monthly_returns_iboxx%>%
select(monthly_returns)
mu_iboxx <- lapply(returns_iboxx, FUN=mean)
mu_iboxx
mu_iboxx_numeric <- as.numeric(mu_iboxx)
mu_eurostoxx <- lapply(returns_eurostoxx, FUN=mean)
mu_eurostoxx
mu_eurostoxx_numeric <- as.numeric(mu_eurostoxx)
```
### Calculate "sigma" for each index separately
```{r}
sigma_iboxx <- as.numeric(lapply(returns_iboxx, FUN=sd))
sigma_iboxx
sigma_eurostoxx <- as.numeric(lapply(returns_eurostoxx, FUN=sd))
sigma_eurostoxx
```
```{r}
cor <- cor(returns_index_final_xts)
cor_xy <- cor [1,2]
cor_xy
```
```{r}
abc <- sigma_iboxx^2-(sigma_eurostoxx*sigma_iboxx*cor_xy)
covarianz_xy <- sigma_eurostoxx*sigma_iboxx*cor_xy
xyz <- sigma_eurostoxx^2+sigma_iboxx^2-(2*sigma_eurostoxx*sigma_iboxx*cor_xy)
MVP <- abc/xyz
MVP
```
we do not invest in eurostoxx
we invest everything in iboxx and sell eurostoxx to buy more iboxx
for the minumum varianze portfolio
c) Now assume a risk-free rate of 0 and calculate the Tangency-Portfolio manually and with the `portfolioAnalytics`-package. What is the slope of the CAL? Plot a mu-sigma-diagram including all relevant information. What are your portfolio weights and weighted returns? Additionally allow for shortselling and check for changes.
?portfolioAnalytics
__tangency portfolio with package__
```{r }
wTP <- t(solve(Sigma) %*% (mu*ones))/drop(ones %*% solve(Sigma) %*% (mu*ones))
muTP <- drop(wTP%*%mu); sigmaTP <- drop(wTP %*% Sigma %*% t(wTP))^0.5
srTP <- (muTP)/sigmaTP; srTP2 <- sqrt(drop((mu*ones) %*% solve(Sigma) %*% (mu*ones)))
round(cbind(wTP,"mean"=muTP,"sd"=sigmaTP,"sr"=srTP),4)
```
A negative Sharpe ratio means that the performance of a manager or portfolio is below the risk-free rate.
__tangency portfolio manually__ maximize the sharp ratio
weight of an optimal risky portfolio
```{r}
weight_eurostoxx1 <- (mu_eurostoxx_numeric*sigma_iboxx^2)-(mu_iboxx_numeric*covarianz_xy)
weight_eurostoxx2 <- (mu_eurostoxx_numeric*sigma_iboxx^2)+(mu_iboxx_numeric*sigma_eurostoxx^2)-((mu_eurostoxx_numeric+mu_iboxx_numeric)*covarianz_xy)
weight_eurostoxx <- weight_eurostoxx1/weight_eurostoxx2
weight_eurostoxx
```
```{r}
weight_iboxx1 <- (mu_iboxx_numeric*sigma_eurostoxx^2)-(mu_eurostoxx_numeric*covarianz_xy)
weight_iboxx2 <- (mu_iboxx_numeric*sigma_eurostoxx^2)+(mu_eurostoxx_numeric*sigma_iboxx^2)-((mu_iboxx_numeric+mu_eurostoxx_numeric)*covarianz_xy)
weight_iboxx <- weight_iboxx1/weight_iboxx2
weight_iboxx
```
__calculating sharpratio manually__
mu tangency portfolio_ we calculate manually the sharp ratio
```{r}
mean_tangencyportfolio <- (weight_eurostoxx)*mu_eurostoxx_numeric+((1-(weight_eurostoxx))*mu_iboxx_numeric)
sd_tangencyportfolio <- sqrt(((weight_eurostoxx)^2*(sigma_eurostoxx)^2)+(((1-(weight_eurostoxx))^2)*(sigma_iboxx)^2)+(2*weight_eurostoxx*(1-(weight_eurostoxx))*covarianz_xy))
sr_tangencyportfolio <- (mean_tangencyportfolio-0)/sd_tangencyportfolio
sr_tangencyportfolio
```
__calculate slope__
slope of the CAL would be the Sharpratio = -0.0268
### mu sigma diagram
```{r}
allsigmamu <- bind_rows(merge(sigma_eurostoxx, mu_eurostoxx_numeric), merge( sigma_iboxx,mu_iboxx_numeric))
name <- c("EuroStoxx", "Iboxx")
allsigmamuwithname <- allsigmamu %>% add_column(name)
allsigmamuwithname
```
```{r}
#rename the columns
colnames(allsigmamuwithname) <- c("sigma", "mu", "name")
allsigmamuwithname
```
```{r}
ggplot(allsigmamuwithname, aes(sigma, mu)) +
geom_point() +
theme_classic() + geom_label_repel(aes(label=name),
box.padding = 0.4,
point.padding = 0.3,
size=6)
```
### Plot the efficient frontier
```{r}
port <- portfolio.spec(assets = colnames(returns_index_final_xts),
category_labels = labels)
port <- add.constraint(portfolio=port,
type="full_investment")
meanvar.portf <- add.objective(portfolio=port,
type="return",
name="mean")
meanvar.portf <- add.objective(portfolio=port,
type="risk",
name="StDev")
summary(meanvar.portf, digits=2)
prt_ef <- create.EfficientFrontier(R=returns_index_final_xts, portfolio=port, type="mean-StdDev", match.col = "StdDev")
chart.EfficientFrontier(prt_ef, match.col="StdDev", rf=NULL)
chart.EF.Weights(prt_ef, colorset=rainbow(n = length(labels)), match.col="StdDev", cex.lab = 1, main = "StdDev")
```
### calculate the weighted return manually__
```{r}
2.8329*mu_eurostoxx_numeric + -1.8329*mu_iboxx_numeric
#our weighted return would be about 0.004
```
d) Now, assume a risk-aversion of A=1, 2 or 3 and calculate your optimal complete portfolio (see lecture slides).
```{r}
mean_tangencyportfolio/(1*varianz_tangencyportfolio)
```
```{r}
mean_tangencyportfolio/(2*varianz_tangencyportfolio)
```
```{r}
mean_tangencyportfolio/(3*varianz_tangencyportfolio)
```
## Exercise 3: Covariance Problems
In the first part of this exercise we will be checking covariances and portfolios that might occur from faulty correlation matrices. We use the covariance matrix from our example
```{r cov, echo=FALSE, fig.cap="Faulty covariance matrix", out.width = '60%'}
knitr::include_graphics("cov.png")
```
where we additionally assume mean returns of 10% for all three assets.
If we define $\mu$ to be the vector of mean returns and $\sigma$ the vector of standard deviations, we can calculate the covariance matrix $\Sigma$ as $\Sigma=diag(\sigma)\cdot R\cdot diag(\sigma)$, where $R$ is the correlation matrix (as in the table above) and $diag$ puts the three standard deviations into the diagonal of a matrix.
### create the correlation-Matrix R
```{r}
x1 <- c(1.00, 0.90, 0.90, 0.90, 1.00, 0.00, 0.90, 0.00, 1.00)
R <- matrix(x1, 3)
colnames(R) <- c("A", "B", "C")
rownames(R) <- c("A", "B", "C")
R
```
### Define Mu (10%) and Standard Deviation (20%)
```{r}
mu <- matrix(c(.1, .1, .1), 3)
sd <- matrix(c(.20, .20, .20), 3)
mu
sd
```
### Create covariance Matrix
```{r}
covariance_matrix <- diag(sd)*R*diag(sd)
covariance_matrix
```
Now we can calculate the Minimum-Variance-Portfolio using matrix calculus as
$w_MP=\frac{\Sigma^{-1}\cdot 1'}{1\cdot\Sigma^{-1}\cdot 1'}$
where 1 is a vector of ones with dimension equal to the number of assets.
### Minimum Varriance Portfolio
```{r}
onevector <- matrix(c(1, 1, 1), 1)
wmvpcalctop <- solve(covariance_matrix)%*%t(onevector)
wmvpcalcbottom <- as.numeric(onevector%*%solve(covariance_matrix)%*%t(onevector))
wmvp <- wmvpcalctop/wmvpcalcbottom
wmvp
```
Similarly one can calculate the tangency portfolio as
$w_TP=\frac{\Sigma^{-1}\cdot (\mu-r_f)'}{1\cdot\Sigma^{-1}\cdot (\mu-r_f)'}$.
### Tangency Portfolio Risk free rate = 3%
```{r}
wtpcalctop <- (solve(covariance_matrix)%*%(mu-0.03))
wtpcalcbottom <- as.numeric(onevector%*%solve(covariance_matrix)%*%(mu-0.03))
wtp <- wtpcalctop/wtpcalcbottom
wtp #Weights equal to MVP
```
Now we can calculate the Minimum-Variance-Portfolio using matrix calculus as
$w_MP=\frac{\Sigma^{-1}\cdot 1'}{1\cdot\Sigma^{-1}\cdot 1'}$
where 1 is a vector of ones with dimension equal to the number of assets. Similarly one can calculate the tangency portfolio as
$w_TP=\frac{\Sigma^{-1}\cdot (\mu-r_f)'}{1\cdot\Sigma^{-1}\cdot (\mu-r_f)'}$.
So to get used to the necessary tools, we use the package "matrixcalc" wherein we have a function `is.positive.semi.definite()` that can check covariance/correlation matrices for positive semidefiniteness. In the package `Matrix` we find a function `nearPD` that can help us to create a valid correlation matrix. Try and calculate the weights of the MVP and the TP, and then calculate portfolio mean and variance using $\mu_P=w\cdot \mu'$ and $\sigma_P^2=w\cdot \Sigma\cdot w'$ for the MVP and the TP as well as the weight vector w=(-1,1,1). Do this for the faulty matrix as well as the corrected one. What do you observe?
### Test: Are the Matrices definite?
```{r}
is.positive.semi.definite(R)
is.positive.definite(covariance_matrix)
```
### Compute the nearest positive definite matrix with the help of nearPD and create a new covariance matrix
```{r}
R2 <- nearPD(R,keepDiag = TRUE)
R2 <- matrix(c( 1.00000, 0.74341, 0.74341,
0.74341, 1.00000, 0.10532,
0.74341, 0.10532, 1.00000)
, 3)
covmat2 <- diag(sd)*R2*diag(sd)
```
### Test: Did it work? --> Yes it worked
```{r}
is.positive.definite(R2)
```
```{r}
is.positive.definite(covmat2)
```
### Calculate the new minimum Varriance Portfolio
```{r}
wmvpcalctop2 <- solve(covmat2)%*%t(onevector)
wmvpcalcbottom2 <- as.numeric(onevector%*%solve(covmat2)%*%t(onevector))
wmvp2 <- wmvpcalctop2/wmvpcalcbottom2
wmvp2
```
### Mu
```{r}
mumvp <- t(wmvp)%*%mu
mumvp2 <- wmvp2[,1]%*%mu
mumvp2 #Mu didn't change, still 10
```
### Standard deviation
```{r}
sdmvpcalc <- t(wmvp)%*%R%*%wmvp
sdmvp <- sqrt(sdmvpcalc)
sdmvpcalc2 <- t(wmvp2)%*%R2%*%wmvp2
sdmvp2 <- sqrt(sdmvpcalc2)
sdmvp2 #Standard Deviation didn't change, still .48%
```
### Calculate the new tangency Portfolio
```{r}
wtpcalctop2 <- (solve(covmat2)%*%(mu-0.03))
wtpcalcbottom2 <- as.numeric(onevector%*%solve(covmat2)%*%(mu-0.03))
wtp2 <- wtpcalctop2/wtpcalcbottom2
wtp2 #Weights again equal to MVP
```
### Mu
```{r}
muwtp <- t(wtp)%*%mu
muwtp2 <- wtp2[,1]%*%mu
muwtp2 #Mu didn't change, still 10%
```
### Standard deviation
```{r}
sdwtpcalc <- t(wtp)%*%R%*%wtp
sdwtp <- sqrt(sdwtpcalc)
sdwtpcalc2 <- t(wtp2)%*%R2%*%wtp2
sdwtp2 <- sqrt(sdwtpcalc2)
sdwtp2 #Standard Deviation didn't change, still .48%
```
-1,1,1 portfolio, create the vector weights
```{r}
wv <- matrix(c(-1, 1, 1),3)
wv
```
### mu
```{r}
muwv <- wv[,1]%*%mu
muwv
```
### standard deviation
```{r}
sdwvcalc <- t(wv)%*%R%*%wv
sdwv <- sqrt(sdwvcalc) #In sqrt(sdwvcalc) : NaNs produced
stdmvpcalc3 <- t(wmvp2)%*%R2%*%wmvp2
sdwvcalc <- t(wmvp2)%*%R2%*%wmvp2
sdwv2 <- sqrt(stdmvpcalc3)
sdwv2 #Standard Deviation also .48%
```