Hello @snoozecj ,
see the example below where I specify only two combinations of 4 stocks
and set the returns for the five stocks involved to randoms numbers.
I create the function calc_volatility that follows ( I assume but check!) your calculation for one combination.
And then I call that function for all combinations (here restricted to the two I specified) with
volatilities <- Combination_of_certificates %>%
rowwise() %>%
mutate(vol = calc_volatility(ISIN_1,ISIN_2,ISIN_3,ISIN_4))
I hope this helps. The full code you will find here:
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(magrittr)
library(stringr)
library(purrr)
#>
#> Attaching package: 'purrr'
#> The following object is masked from 'package:magrittr':
#>
#> set_names
set.seed(2021)
Combination_of_certificates <- data.frame(
ISIN_1 = c("CH0595726594", "CH0595726594") ,
ISIN_2 = c("CH1111679010", "CH1111679010") ,
ISIN_3 = c("XS1994697115", "XS1994697115") ,
ISIN_4 = c("CH0587331973", "XS2027888150")
)
head(Combination_of_certificates)
#> ISIN_1 ISIN_2 ISIN_3 ISIN_4
#> 1 CH0595726594 CH1111679010 XS1994697115 CH0587331973
#> 2 CH0595726594 CH1111679010 XS1994697115 XS2027888150
perf <- data.frame (
CH0595726594 = rnorm(250),
CH1111679010 = rnorm(250),
XS1994697115 = rnorm(250),
CH0587331973 = rnorm(250),
XS2027888150 = rnorm(250)
)
head(perf)
#> CH0595726594 CH1111679010 XS1994697115 CH0587331973 XS2027888150
#> 1 -0.1224600 0.26093831 0.21598179 1.6508943 0.80959540
#> 2 0.5524566 -0.43434214 -1.39253776 0.2017592 0.09941633
#> 3 0.3486495 -1.87300754 -0.07437819 0.8139997 -2.34302131
#> 4 0.3596322 -0.80304453 -1.13603889 1.0523580 0.67652598
#> 5 0.8980537 0.33232209 -0.42951107 -0.8471807 -3.61147374
#> 6 -1.9225695 0.01211264 0.47957570 0.4378037 -0.16416799
calc_volatility <- function(isin_1,isin_2,isin_3,isin_4) {
# function to calculate volatility for one combination of stocks
stocks <- c(isin_1,isin_2,isin_3,isin_4)
# column numbers in perf for this combination
indices <- purrr::map_dbl(stocks, ~stringr::str_which(names(perf),.))
portfolio_component_monthly_returns <- perf [,indices]
covariance_matrix <- cov(portfolio_component_monthly_returns)
weights <- c(0.25, 0.25, 0.25, 0.25) # weights not necessary now (?)
sqrt(t(weights) %*% covariance_matrix %*% weights) * sqrt(250)
}
volatilities <- Combination_of_certificates %>%
rowwise() %>%
mutate(vol = calc_volatility(ISIN_1,ISIN_2,ISIN_3,ISIN_4))
head(volatilities)
#> # A tibble: 2 x 5
#> # Rowwise:
#> ISIN_1 ISIN_2 ISIN_3 ISIN_4 vol[,1]
#> <chr> <chr> <chr> <chr> <dbl>
#> 1 CH0595726594 CH1111679010 XS1994697115 CH0587331973 8.19
#> 2 CH0595726594 CH1111679010 XS1994697115 XS2027888150 8.04
Created on 2021-08-31 by the reprex package (v2.0.0)