Pemodelan dan Teori Risiko

Tugas Pertemuan 9-10


Kontak : \(\downarrow\)
Email
Instagram https://www.instagram.com/saram.05/
RPubs https://rpubs.com/sausanramadhani/

Lab Exercise 1

Calculate Value at Risk using case example above! Write down your complete answer in your Rpubs and share the link at google clasroom.

Collect Historical Data

The case example in Material 9-10 have a portfolio consisting of three assets: stocks (ST), bonds (BD), and commodities (CM), including :

  • AAPL : Apple Inc based on the stock market
  • GOOG : Alphabet Inc (Google’s parent company) based on the stock market
  • MSFT : Microsoft Corporation based on stock market
  • ^TNX : bond market
  • GLD : SPRD Gold Shares representing the commodity market

To call the historical data, we can use the package quantmod as below:

library(quantmod)
# Define a list of ticker symbols for the datasets you want to fetch
symbols <- c("AAPL", # stock market
             "GOOG", # stock market
             "MSFT", # stock market
             "^TNX", # bond
             "GLD")  # commodity

# Set the start and end dates for historical data retrieval
start_date <- "2023-01-01"
end_date <- Sys.Date()  # Current date

# Fetch historical price data
getSymbols(symbols, src = "yahoo", from = start_date, to = end_date)
## [1] "AAPL" "GOOG" "MSFT" "TNX"  "GLD"

After that, we extract the adjusted closing price for each asset.

# Extract adjusted closing prices for each asset
prices <- merge(Ad(AAPL), Ad(GOOG), Ad(MSFT), Ad(TNX), Ad(GLD))

# rename column names
colnames(prices) <- symbols

# Interpolate missing values
prices <- na.approx(prices)

# print the result
head(prices)
##                AAPL  GOOG     MSFT  ^TNX    GLD
## 2023-01-03 124.2163 89.70 237.0360 3.793 171.06
## 2023-01-04 125.4975 88.71 226.6673 3.709 172.67
## 2023-01-05 124.1666 86.77 219.9494 3.720 170.52
## 2023-01-06 128.7352 88.16 222.5415 3.569 173.71
## 2023-01-09 129.2616 88.80 224.7083 3.517 174.10
## 2023-01-10 129.8377 89.24 226.4199 3.621 174.74

The result is a section of the data frame that contains the adjusted closing prices for some financial assets on a specific date in 2023, i.e. top 6 closing prices (head).

For example, on January 3, 2023, the adjusted closing price for each asset is as follows:

  • AAPL (Apple Inc.): $124.2163
  • GOOG (Alphabet Inc.): $89.70
  • MSFT (Microsoft Corporation): $237.0360
  • ^TNX (Yield on 10-year Treasury notes): 3.793%
  • GLD (SPDR Gold Shares): $171.06

Similarly, on subsequent dates, the adjusted closing price for each asset is also presented.

Calculate Daily Return

Furthermore, to calculate the daily rate of return for each asset from the data, we can use the ROC() function.

# Calculate daily returns for each asset
asset_returns <- na.omit(ROC(prices, type = "discrete"))

# Display the first few rows of the returns data
asset_returns
##                    AAPL         GOOG         MSFT        X.TNX           GLD
## 2023-01-04  0.010314239 -0.011036766 -0.043743202 -0.022146025  0.0094119060
## 2023-01-05 -0.010604644 -0.021869039 -0.029637761  0.002965737 -0.0124514619
## 2023-01-06  0.036794130  0.016019443  0.011785272 -0.040591404  0.0187074968
## 2023-01-09  0.004088757  0.007259521  0.009736513 -0.014569920  0.0022451176
## 2023-01-10  0.004456465  0.004954896  0.007617093  0.029570683  0.0036760446
## 2023-01-11  0.021112250  0.033841375  0.030238181 -0.018503217 -0.0006867939
## 2023-01-12 -0.000599170 -0.003793610  0.011621503 -0.029544182  0.0115680010
## 2023-01-13  0.010118985  0.009683379  0.003018685  0.017976236  0.0120017840
## 2023-01-16  0.006567178 -0.005172409  0.003511318  0.005126780 -0.0049088088
## 2023-01-17  0.002174777 -0.001733101  0.001166344  0.001700210 -0.0016443413
##        ...                                                                  
## 2024-04-12  0.008626656 -0.009950811 -0.014091087 -0.016826953 -0.0132393249
## 2024-04-15 -0.021863498 -0.017965956 -0.019578050  0.028672974  0.0187191552
## 2024-04-16 -0.019167280 -0.002110931  0.002272440  0.006698388  0.0012220153
## 2024-04-17 -0.008147390  0.005641057 -0.006609075 -0.015883212 -0.0073682528
## 2024-04-18 -0.005714326  0.003697105 -0.018380943  0.013522311  0.0034154561
## 2024-04-19 -0.012212604 -0.011050460 -0.012738996 -0.006886177  0.0031315351
## 2024-04-22  0.005090887  0.014320548  0.004610133  0.001733559 -0.0247024905
## 2024-04-23  0.006391688  0.012472309  0.016485475 -0.005407764 -0.0024586632
## 2024-04-24  0.012702280  0.007378739  0.003655790  0.011744215 -0.0018600907
## 2024-04-25  0.005147291 -0.019553129 -0.024495157  0.011607889  0.0059634681

The results above is two frames of data where head(price) shows the asset price data and asset_returns shows the daily rate of return.

1. Asset Price Data

  • Asset list: “AAPL”, “GOOG”, “MSFT”, “TNX”, and “GLD”. This data displays the price of each asset on a specific date. Each row shows the price of the asset on that date.
  • For example, on 2023-01-03, the price of AAPL is 124.2163, GOOG is 89.70, MSFT is 237.0360, TNX is 3.793, and GLD is 171.06.

2. Daily Rate of Return

  • This is the data resulting from the calculation of the daily rate of return for each asset. Each row shows the daily rate of return for each asset on a specific date.
  • For example, on 2023-01-04, the daily rate of return for AAPL is 0.0103143009, for GOOG is -0.011036766, for MSFT is -0.043743202, for TNX (10-year bond yield) is -0.022146025, and for GLD (gold price) is 0.0094119060.

Determine Asset Weights

Use the fPortfolio package to provide various functions for portfolio analysis, including portfolio optimization, performance evaluation, and diversification. The first step in performing portfolio analysis is to determine the weights of the sample portfolio. Portfolio weights indicate how much funds are allocated to each asset in the portfolio. This is important because portfolio weights affect the overall performance of the portfolio.

library(fPortfolio)                              # Load Necessary Libraries
portfolio_weights <- c(0.2, 0.2, 0.2, 0.2, 0.2)  # Example weights (sums to 1)

In lab 1 analysis, the portfolio weights are given equally at 20% for each asset in the portfolio.

Calculate Portfolio Return

After giving the portfolio a weight of 20%, we can calculate the portfolio return from the daily return data.

# Remove column indexes
colnames(asset_returns) <- NULL
# Calculate portfolio returns
portfolio_returns <- colSums(asset_returns* portfolio_weights)/sum(portfolio_weights)
  • colnames(asset_returns) <- NULL: This line removes the column index from the asset daily rate of return data. This is done so that further calculations can be done without taking the column index into account.
  • portfolio_returns <- colSums(asset_returns * portfolio_weights) / sum(portfolio_weights): This line calculates the portfolio’s rate of return using the predetermined portfolio weights. First, the daily rate of return of each asset is multiplied by the corresponding weight. Then, the results are summed up for each row, and divided by the total portfolio weight. This gives the expected rate of return of the portfolio based on the given asset weights.

Estimate Portfolio Volatility

Use the PerformanceAnalytics package to analyze portfolio performance and risk management. From this package, we can use the StdDev() function to calculate portfolio volatility.

library(PerformanceAnalytics)
# Calculate portfolio volatility
portfolio_volatility <- StdDev(portfolio_returns)
portfolio_volatility
##              [,1]
## StdDev 0.03459949

Obtained a portfolio volatility value of 3.46%. So, with a portfolio volatility of 3.46%, investors can expect price fluctuations or portfolio returns of around 3.46% of the average value in the observed period.

In general, the higher the volatility of a portfolio, the greater the fluctuations in the price or rate of return of the portfolio, indicating higher risk. High volatility may indicate greater profit potential, but also increases the possibility of large losses. Conversely, low volatility indicates greater stability, but can also limit potential gains.

Calculate Value at Risk

To measure the maximum loss that may occur in an investment portfolio can use Value at Risk (VaR).

Metode Parametrik

Below is the coding to calculate the parametric Value at Risk (VaR) of investment portfolios using the z-score and portfolio volatility calculated earlier:

z_score <- qnorm(0.95)
market_value <- 1500
VaR_par <- z_score * portfolio_volatility
VaR_par
##              [,1]
## StdDev 0.05691109

Calculate the parametric VaR (Value at Risk) by multiplying the z-score by the portfolio volatility. In the parametric approach, VaR is calculated by assuming that the distribution of portfolio returns is a normal distribution.

The result, StdDev 0.05691109, is the parametric VaR value of the investment portfolio. This indicates that with a 95% confidence level, it is estimated that the maximum loss that may occur in a given period will not exceed approximately 5.691109% of the market value of the portfolio. VaR gives an idea of the potential risk faced by an investment portfolio and helps investors manage risk.

Gauss Copula

To calculate the Value at Risk (VaR) of an investment portfolio can use the Monte Carlo simulation method using the Gauss copula, as follows:

# Load necessary libraries
library(copula)

# Simulate asset returns
set.seed(123)
n <- 1500
rho <- 0.5    # correlation coefficient
normalCop <- normalCopula(param = rho, dim = 2)
U <- rCopula(n, normalCop)
X <- qnorm(U)

# Transform to asset returns
asset1_returns <- X[,1]
asset2_returns <- X[,2]

# Calculate portfolio value
initial_portfolio <- 1500000   # initial portfolio value
portfolio_value <- initial_portfolio * (1 + asset1_returns + asset2_returns)

# Sort simulated portfolio returns
sorted_returns <- sort(portfolio_value)

# Calculate VaR
confidence_level <- 0.95
var_percentile <- 1 - confidence_level
var_index <- round(var_percentile * n)
VaR <- sorted_returns[var_index]
VaR
## [1] -2751083

The result, -2751083, is the estimated VaR value for the investment portfolio with a 95% confidence level. This means that with a 95% confidence level, the maximum loss that can be expected in a given period of time (for example, one day or one month) is $2,751,083.

Thus, from the second calculation of VaR it is stated that :

1. Parametric VaR

  • The result of parametric VaR calculation using z-score and portfolio volatility is StdDev 0.05691109.
  • This indicates that with a 95% confidence level, the maximum loss that may occur in a given period will not exceed approximately 5.691109% of the market value of the portfolio.

2. VaR Copula

  • The result of the copulae approach is -2751083. This is the estimated VaR value for the investment portfolio with a 95% confidence level.
  • That is, with a 95% confidence level, the maximum loss that can be expected in a given period of time (for example, one day or one month) is $2,751,083.

Lab Exercise 2

Let’s assume we have a portfolio consisting of three assets (Stocks from Indonesia): stocks (ST), bonds (BD), and commodities (CM). Calculate Value at Risk using using Copulae method!. Write down your complete answer in your Rpubs and share the link at google clasroom.

Collect Historical Data

The stock data analyzed are:

  • ACES.JK: PT ACE Hardware Indonesia Tbk
  • BUKA.JK: PT Bukalapak.com Tbk
  • GOTO.JK: PT GoTo Gojek Tokopedia Tbk
# Load necessary libraries
library(quantmod)
library(copula)

# Define a list of ticker symbols for the datasets you want to fetch
symbols <- c("ACES.JK", "BUKA.JK", "GOTO.JK")

# Set the start and end dates for historical data retrieval
start_date <- "2023-01-01"
end_date <- Sys.Date()  # Current date

# Fetch historical price data
getSymbols(symbols, src = "yahoo", from = start_date, to = end_date)
## [1] "ACES.JK" "BUKA.JK" "GOTO.JK"
# Extract adjusted closing prices for each asset
prices <- merge(Ad(ACES.JK), Ad(BUKA.JK), Ad(GOTO.JK))

# Rename column names
colnames(prices) <- symbols

# Interpolate missing values
prices <- na.approx(prices)

Calculate Asset Returns

# Calculate asset returns
asset_returns <- na.omit(ROC(prices, type = "discrete"))

Calculate Value at Risk

# Define copula
set.seed(123)
rho <- 0.5
normalCop <- normalCopula(param = rho, dim = ncol(asset_returns))

# Simulate asset returns using copula
U <- rCopula(nrow(asset_returns), normalCop)
X <- qnorm(U)

# Transform to portfolio returns
portfolio_returns <- rowSums(X)

# Calculate portfolio value
initial_portfolio <- 1500000
portfolio_value <- initial_portfolio * (1 + portfolio_returns)

# Sort simulated portfolio returns
sorted_returns <- sort(portfolio_value)

# Calculate VaR
confidence_level <- 0.95
var_percentile <- 1 - confidence_level
var_index <- round(var_percentile * length(sorted_returns))
VaR <- sorted_returns[var_index]

VaR
## [1] -3834143

The result of the VaR calculation using the copula approach is -3834143. The negative number indicates that the VaR indicates the maximum expected loss in the portfolio at the selected confidence level (in this case, 95%). This means that with a 95% confidence level, the maximum expected loss in the portfolio can reach around $3,834,143.