Risk Management Techniques with R
Risk Management Techniques with R
A Practical Guide
2
PREFACE
The topics are structured to build a strong foundation, beginning with the basics of data
retrieval and return calculations, progressing to more advanced topics such as risk
management under both normal and non-normal distributions, and further enhancing
this knowledge with volatility modelling techniques. Each section is enriched with
practical applications, ensuring that theoretical understanding seamlessly integrates
with real-world scenarios.
The author of this book is a seasoned finance and risk management professional with a
deep commitment to excellence and a track record of applying analytical and actuarial
expertise to real-world challenges. With qualifications including certifications from
prestigious institutions such as the CFA Institute (CFA), GARP (FRM), and the Institute
and Faculties of Actuaries (IFoA), the author’s experience spans a wide range of areas,
including risk management, investment, actuarial science, insurance, and compliance.
This book is tailored for professionals, researchers, and students interested in mastering
risk management techniques, particularly using R for financial data analysis. The
author's vast experience in the financial industry, combined with the passion for
knowledge-sharing, ensures that this resource is both practical and insightful, offering
valuable perspectives for anyone looking to understand and apply risk management
methodologies in today's financial world.
3
Contents
4
5
Topic 1: Introduction to R.
In risk management, the first critical step is to collect data related to the portfolio under
study. For portfolios consisting of stocks, understanding their historical returns is
essential for assessing risk. In this exercise, we focus on a portfolio of Indian stocks. A
comprehensive and widely used index for the Indian equity market is the Nifty 50 Index.
The Nifty 50 is a stock market index in India that represents the weighted average of the
50 largest and most liquid Indian companies listed on the National Stock Exchange
(NSE). It is one of the major stock indices in India and provides a snapshot of the
performance of large-cap companies across various sectors of the Indian economy.
Investors often track the Nifty 50 as an indicator of overall market performance, and it is
widely used for index-based investing, benchmarking, and derivative trading (such as
futures and options).
6
Data Retrieval
• Data Retrieval:
o quantmod allows you to easily download financial data (such as stock prices,
indices, etc.) from sources like Yahoo Finance, Google Finance, and FRED
(Federal Reserve Economic Data).
o You can download historical stock prices or index data for analysis with just a
single line of code.
• Charting and Visualization:
o The package makes it easy to create financial charts (like candlestick charts, bar
charts, line charts, etc.) with technical indicators like moving averages, Bollinger
Bands, and MACD.
o These charts are customizable and widely used by technical analysts and traders.
• Technical Indicator Calculations:
o quantmod provides functions for calculating common technical indicators such
as Relative Strength Index (RSI), Exponential Moving Averages (EMA), and others.
o It supports integrating these indicators directly into financial charts.
• Modelling and Strategy Development:
o The package is also useful for back-testing and modelling trading strategies by
applying different algorithms or indicators to the historical data.
o With quantmod, you can pull data, compute indicators, and develop and test
trading models in R.
• Integration with Other Packages:
o It integrates smoothly with other popular R packages like xts (for time series
data), TTR (for technical analysis), and Performance Analytics.
Following sample R codes using quantmod package would retrieve the historical Nifty 50
data and create a candlestick chart with a 50-day moving average and other technical
indicators plotted on it.
7
# Add a 50D SMA, Bollinger Bands, MACD, RSI to the chart
addSMA(n = 50)
addBBands()
addMACD()
addRSI()
quantmod is widely used in finance and actuarial fields for time series analysis, portfolio
management, and market analysis. Its simplicity makes it accessible even for beginners,
while its depth is suitable for experienced quantitative analysts. Process to retrieve the
Nifty 50 Index data from Yahoo Finance is as follows:
• Load the quantmod Package: The first step is to install and load the quantmod
package in R, which allows for easy retrieval of financial data from various sources,
including FRED and Yahoo Finance.
• Retrieve Data from Yahoo Finance: The Nifty 50 Index can be accessed from Yahoo
Finance by its ticker symbol: ^NSEI. The getSymbols() function in quantmod will
retrieve the data and store it in an R object. In this case, the data is stored in an object
named “sec”. This data contains the daily index values of the Nifty 50.
• Handle Missing Data (NAs): Yahoo Finance returns data for each day the market is
open, but if no data is available for a given day (e.g., a holiday), an NA (Not Available)
value is returned. It is important to remove these missing values to ensure the
8
integrity of the data. The function [Link]() removes all rows containing NA values,
leave the clean data.
• Filter Data for a Specific Date Range: The getSymbols() function returns the Nifty 50
data from 2007 to current date. For this exercise, we will focus on the period from the
end of 2007 to the end of 2023. This command limits the dataset to the date range we
are interested in for risk management purposes.
• Display a Sample of the Data: To verify that the data has been retrieved correctly, it’s
good practice to display the first few rows using the head() function. Similarly,
tail() function can display the last few rows of data.
# Retrieve data from Yahoo Finance and store in the object “sec”
sec <- getSymbols("^NSEI", src = "yahoo")
9
Return Calculations
To calculate the holding period return (HPR) and logarithmic (log) return for the Nifty 50
Index, we'll walk through the following. These steps allow us to transform daily index
values into both discrete and log returns, which are crucial for financial risk management
analysis.
Log returns (also called continuously compounded returns) are often preferred over
normal (arithmetic) returns in financial analysis for several reasons:
• Time Additivity: Log returns are additive over time, which means that the total return
over multiple periods can be calculated by summing the log returns of each individual
period. For example, if you have daily log returns, you can easily sum them up to get
the weekly or monthly log return. Arithmetic returns do not have this property, making
them more complicated to aggregate over time.
• Normal Distribution Approximation: Log returns tend to be more normally distributed
than arithmetic returns, especially over shorter time intervals. Many statistical
models, such as the Black-Scholes model and others used in quantitative finance,
assume normality in the returns, so using log returns often simplifies the modelling.
• Non-Negativity of Prices: Using log returns ensures that you never end up with a
negative price when you reverse the calculation. This is because log returns are
derived from a ratio of prices, and the exponential function, which is used to reverse
the log transformation, always results in a positive number.
• Compounding Consistency: Log returns naturally account for compounding over
time, making them a better choice for long-term investments or for assets where
returns are reinvested. Arithmetic returns assume simple interest, which may
underestimate actual returns in compounding scenarios.
• Convenient for Small Returns: For small returns, log returns and arithmetic returns
are approximately the same. This approximation makes log returns practical,
especially when dealing with high-frequency data or short time intervals.
Log returns are commonly used in financial modelling, portfolio management, risk
management, and derivatives pricing. Arithmetic returns are still useful for simple
descriptive statistics and when dealing with raw, unadjusted data.
In summary, log returns are often preferred because they simplify analysis in many
financial contexts, especially when dealing with compounding, aggregating over time, or
assuming normally distributed returns.
10
Calculations
• Discrete Return Calculation: The discrete return over a single day (holding period
return) is calculated as:
𝐼𝑛𝑑𝑒𝑥 𝑉𝑎𝑙𝑢𝑒 𝑎𝑡 𝐷𝑎𝑦 𝑡
𝑟𝑒𝑡(𝑡) = −1
𝐼𝑛𝑑𝑒𝑥 𝑉𝑎𝑙𝑢𝑒 𝑎𝑡 𝐷𝑎𝑦 𝑡 − 1
This measures the percentage change in the index from one day to the next.
• Log Return Calculation: The log return (continuously compounded return) transforms
the discrete return using the natural logarithm. It provides a symmetric distribution
for easier application of standard statistical methods. The formula for log return is:
Alternatively, the log return can be calculated directly from the index values:
This transformation ensures that returns have no upper or lower bound and work
symmetrically for both gains and losses.
We can calculate the log return by first taking the natural log of the index values and
then finding the differences between consecutive logs using the log() and diff()
functions.
# Calculate log returns using log & diff and store in object “logret”
logret <- diff(log(sec$[Link]))[-1]
11
• log(sec) takes the natural logarithm of the index values.
• diff(log(sec$[Link])) calculates the difference between consecutive
logs of closing price (log returns).
• [-1] removes the first NA (because there’s no previous index value for the first
observation).
• round(logret, 6) rounds the output to six decimal places for readability.
• head( ,3) function, you will see the first three values of the log returns.
We can easily revert to discrete returns from the log return using the following
formula. This converts log returns back to discrete returns.
𝑟𝑒𝑡(𝑡) = exp(𝑙𝑜𝑔𝑟𝑒𝑡(𝑡)) − 1
The discrete return will be very close to the continuously compounded (log) return,
especially for small percentage changes.
12
This graph shows the daily volatility of the Nifty 50 Index, with many small fluctuations
and occasional larger spikes. Understanding the size and frequency of these movements
helps in financial risk management by identifying periods of high volatility or large losses.
By calculating and analysing both discrete returns and log returns, we can:
This process of transforming and analysing returns is essential for building a clear
understanding of the financial risk in any stock portfolio. Now that we've calculated daily
log returns for the Nifty 50 Index, we can proceed with further analysis, such as
calculating long-term returns, examining historical volatility or using these returns to
model potential risks in financial portfolios.
To calculate returns over time periods longer than one day, such as weekly, monthly,
quarterly, or yearly returns, we can extend the logic of summing up one-day log returns
and converting them into discrete returns when needed. In R, this process can be made
easier using functions such as [Link](), [Link]()etc. provided by
libraries like xts and quantmod. Given below is an explanation and corresponding R
code for calculating longer period returns.
• Summing Log Returns Over n Days: For log returns, if we want the return over n days,
we can simply sum the one-day log returns:
If we then need the discrete return over n days, we can use the formula:
Weekly returns can be calculated from the daily log returns by summing them up
using [Link](). Weekly log returns can be converted to discrete returns,
exponentiate the result and subtract 1.
13
# Load required libraries
library(quantmod)
library(xts)
Similarly, we can calculate monthly, quarterly and yearly log returns by using the
[Link](), [Link]() and [Link]() functions, which works
exactly like [Link](). Each of these functions allows to move from shorter to
longer return periods efficiently, making them highly useful in financial risk management.
14
Risk Management Applications
We can apply the knowledge learned so far through an example. Consider a hedge fund
“SanPan”, having financial structure as below:
Risk of Bankruptcy: The hedge fund will be bankrupt if the value of the stock portfolio
drops by more than 10%. Why that is so?
• Assets: The hedge fund has $1 billion in assets invested in Indian equities.
• Liabilities: The hedge fund has $900 million in liabilities (loan from the bank).
• Equity/Capital: The hedge fund manager’s $100 million is the equity or capital at
risk.
If the portfolio falls in value by more than $100 million (or 10% of $1 billion), the value of
assets will drop below $900 million, meaning the hedge fund would not have enough
assets to repay the bank loan, leaving the fund bankrupt. This shows that equity capital
is the buffer between the hedge fund’s assets and liabilities. If the value of the assets
falls too much, the buffer is depleted, and the fund can no longer meet its obligations.
Key Concepts:
• Leverage: The hedge fund is highly leveraged with $900 million of debt and only
$100 million of its own capital. Leverage magnifies both potential returns and
potential losses.
• Risk Factor: In this example, the main risk factor is the value of Indian equities. If
the value of Indian equities declines significantly, the hedge fund’s assets will
drop, bringing the fund closer to bankruptcy.
• Bankruptcy Threshold: The critical threshold is a 10% decline in the stock portfolio
value. A drop greater than 10% wipes out the fund’s equity, making it bankrupt.
Historical vs. Future Risk: Risk management always deals with future distributions of risk
factors. However, since we cannot directly observe future outcomes, we use historical
data to model and estimate future risk. This is where tools like historical data from
indices (e.g., Nifty 50) are used to analyse and understand possible future movements in
equity values.
This example introduces the relationship between assets, liabilities, and equity and how
financial leverage can impact the risk of bankruptcy. The key takeaway is that in risk
management, we need to understand the future distribution of risk factors based on
historical data. In this case, we look at historical stock market returns to estimate
potential future losses that could push the hedge fund into bankruptcy.
15
16
Topic 2: Risk Management under Normal Distribution
Distribution of Returns
In this part we shift our focus to understand the distribution of returns, specifically the
normal distribution, which plays a crucial role in risk management and finance.
• Defined by Two Parameters: The mean (μ) and standard deviation (σ) fully
characterize the normal distribution. This simplicity makes it a powerful and
intuitive tool.
• Central Limit Theorem (CLT): The CLT states that under certain conditions, the
sum of a large number of independent random variables tends to be normally
distributed, even if the original data does not follow a normal distribution. This
property is particularly useful when modelling financial returns.
• Symmetry: The normal distribution is symmetric around the mean, which makes
it easier to work with in risk management.
Understanding the distribution of returns is critical for two reasons:
17
However, when returns deviate from normality (e.g., fat tails, skewness), more complex
calculations are required.
x = σ⋅ ϵ + μ. x
Here, x is now a normally distributed variable with mean μ and standard deviation σ. In
real-world data, we typically do not know the true values of μ and σ, so we estimate them
from the data.
For the Nifty 50 index’s log returns, we can estimate these parameters using simple
functions in R:
These two parameters are important as they allow to model the distribution of returns
and assess risk measures like VaR and ES.
Once we have the mean and standard deviation, we can plot the normal distribution
curve (or probability density function) using these estimated parameters. The curve will
represent the distribution of one-day log returns, providing a visual understanding of how
frequently certain returns are expected to occur.
At this stage, we calculate the mean and standard deviation of the data retrieved from the
Yahoo Finance database. By doing this, we will have a clearer understanding of the
distribution of the Nifty 50 index’s log returns, which will be the foundation for further risk
management analyses such as calculating VaR and expected shortfall.
18
# claculate the mean of log return and store in "mu"
mu<- round(mean(logret),8)
> mu
[1] 0.00032249
> sig
[1] 0.01339796
We are now introduced with the foundational concepts of return distributions and their
role in risk management. The focus now moves to understanding how these statistical
tools are applied in practice, especially in relation to risk metrics.
19
Value at Risk (VaR)
Value-at-Risk (VaR) is one of the most widely used measures in financial risk
management. It provides an estimate of the maximum potential loss a portfolio might
incur with a given probability, over a specific time horizon. VaR helps portfolio managers,
risk officers, and investors assess the risk associated with their investments and make
informed decisions to limit their exposure to adverse market movements.
In this section, we will understand the VaR in detail, demonstrate how it is calculated
assuming returns follow a normal distribution, and provide an example using the Nifty 50
Index.
VaR answers the question "What is the worst expected loss over a given time period at a
specific confidence level?". To express this formally, VaR represents the maximum
expected loss with a given probability (called alpha (α)), over a given time period, under
normal market conditions.
The alpha (α) value indicates the probability of losses beyond VaR, typically expressed as
a percentage. For example, a 5% VaR (α = 0.05) implies there is a 95% chance that the
portfolio will not lose more than the calculated VaR amount over the time horizon, and a
5% chance it could lose more.
The time horizon for VaR can vary, but most commonly it is calculated for:
• Risk Factor: Identify the primary risk factor affecting the portfolio. In our case, we use
the Nifty 50 Index's daily log returns as the risk factor.
• Confidence Level: Select a confidence level (usually 95% or 99%). This corresponds
to the alpha (α) value, which reflects the tail risk. For example, at a 95% confidence
level (α = 0.05), we exclude the worst 5% of potential returns.
• Mean and Standard Deviation: Assume the risk factor (daily returns) follows a normal
distribution and estimate its mean (μ) and standard deviation (σ).
20
• Quantile Calculation: VaR is defined as the quantile of the normal distribution. For a
normal distribution with mean (μ) and standard deviation (σ), the α-quantile can be
calculated using the qnorm() function in R: qnorm(α, mean, sd). This function
gives the α-quantile value, which is the VaR.
The normal distribution is a symmetric, bell-shaped curve centred around the mean (μ).
The tails of the distribution represent extreme outcomes (both positive and negative
returns). The quantile is the point on the x-axis where the cumulative probability equals
α. In the context of VaR, this quantile represents the maximum loss that could occur with
a probability of α. For α = 0.05, the 95% VaR corresponds to the value where 5% of the
outcomes (worst-case scenarios) lie to the left of the quantile on the distribution curve,
and 95% lie to the right.
• Estimate the Mean and Standard Deviation: First, we estimate the mean (μ) and
standard deviation (σ) of the daily log returns. We have already calculated:
o Mean (μ): mu = 0.00032249
o Standard Deviation (σ): sig = 0.01339796
• Calculate the 5% Quantile (VaR): To calculate the 95% VaR (with α = 0.05), we use the
qnorm() function in R. This returns a value of approximately -0.02171519 (or about
−2.17%).
• Interpret the VaR: This quantile value means that, at a 95% confidence level, the
portfolio will not lose more than 2.17% of its value in one day. Conversely, there is a
5% chance that the portfolio could lose more than 2.17%.
• VaR in Dollar Terms (Hedge Fund Example): Recall the hedge fund that has $100
million of invested capital, and $900 million borrowed from a bank. The total portfolio
size is therefore $1 billion.
21
# Calculate the VaR @ 95% confidence interval and store it in "VaR"
VaR <- qnorm(.05, mu, sig)
#Display VaR
VaR
> VaR
[1] -0.02171519
> pf_VaR
[1] -21.48112
Dollar VaR considers the discrete VaR, as the VaR is calculated on the log returns of Nifty
50 Index. Therefore, with 95% confidence, the hedge fund will not lose more than $21.48
million in one day. However, there is a 5% chance that it could lose more than $21.48
million.
• Simplicity: VaR provides a straightforward risk measure in both percentage and dollar
terms, making it easy for portfolio managers to understand the potential downside
risk.
• Confidence Level: VaR can be adjusted by varying the confidence level (95%, 99%,
etc.) depending on the risk tolerance of the organization.
• Assumptions: When using VaR, especially under the assumption of a normal
distribution, it is important to remember that it does not capture extreme tail risks
(e.g., "Black Swan" events).
VaR is an essential risk management tool, offering a quick snapshot of potential losses
over a given time frame. Calculating VaR assuming a normal distribution simplifies the
process, using estimated mean and standard deviation values to compute the relevant
quantiles. For our hedge fund example, we demonstrated how VaR can be applied in
practice, translating potential losses into actionable dollar amounts. By understanding
and regularly calculating VaR, financial institutions can better manage their portfolios
and ensure they remain within acceptable risk limits.
22
Expected Shortfall (ES)
In financial risk management, Value at Risk (VaR) and Expected Shortfall (ES) are crucial
metrics used to assess the potential losses of an investment or portfolio over a given time
period. VaR provides a measure of the maximum potential loss at a specified confidence
level (e.g., 95%) over a set time horizon, such as one day or one week.
However, VaR only tells us the loss threshold, not the average loss if things go worse than
that. This is where Expected Shortfall comes into play. Expected Shortfall (ES), also
known as Conditional Value at Risk (CVaR), Average Value-at-Risk (AVaR), or Expected
Tail Loss, provides the expected return when the loss exceeds the VaR threshold. It
represents the average loss in the tail of the distribution, capturing extreme risks better
than VaR.
For example, if the one-day VaR at the 95% confidence level is -2.17%, the corresponding
ES might be -2.7%. This indicates that in the worst 5% of cases, the average loss would
be 2.7%.
A key point to note is that for normal distributions, there are direct equations to calculate
both VaR and ES. If we take the VaR calculated earlier, say -2.17% for a 95% confidence
level, the ES is the average of all returns to the left of this VaR threshold.
In the example provided, we compute the ES as approximately -2.7%, meaning that if the
return is worse than -2.17%, the average expected loss will be around 2.7%. This is crucial
information for risk managers who need to understand not just the threshold loss, but
what the average loss might look like when the threshold is breached.
23
Hedge Fund Example: Applying Expected Shortfall
Let's apply this concept to a hedge fund. At the 95% confidence level, the one-day VaR
was calculated to be -2.17%, and the ES was calculated to be -2.7%. What does this tell
us? If Indian stocks fall by more than 2.17% in a single day, the hedge fund can expect an
average loss of around 2.7%. Given that the fund is invested with $1 billion, the expected
loss, in monetary terms, would be approximately $26.9 million.
In this case: Expected Shortfall = -2.73% and Total Investment = $1 billion. First, convert
the expected shortfall into a discrete return: exp(−0.027) −1 ≈ −0.026944
Thus, if the market performs worse than the VaR threshold, the hedge fund stands to lose
approximately $26.9 million on average.
#Display es
es
> es
[1] -0.02731365
> expected_loss
[1] -26944009
Expected Shortfall (ES) provides a more comprehensive risk metric than VaR by giving the
expected average loss beyond the VaR threshold. This allows for better risk management,
particularly in extreme market conditions. In the hedge fund example, knowing the VaR
alone (-2.17%) isn't sufficient; the ES (-2.7%) shows the likely average loss in a worst-case
scenario, which translates to $26.9 million. Understanding and calculating both VaR and
ES are critical in managing portfolio risks effectively, especially for large funds exposed
to market volatility.
24
Note on R formula – calculation of expected shortfall
Components:
1. μ\mu: The mean of the normal distribution (representing average return).
2. σ\sigma: The standard deviation of the normal distribution (representing the
volatility of returns).
3. dnorm(x,0,1): This is the probability density function (PDF) of the standard
normal distribution evaluated at x, where the mean is 0 and the standard
deviation is 1.
4. qnorm(0.05,0,1): This is the quantile function (inverse of the cumulative
distribution function) for the standard normal distribution, which returns the 5th
percentile (VaR at the 95% confidence level). This will provide the z-score
corresponding to the 5% tail.
5. 0.05: The 5% threshold used in the calculation for the ES, corresponding to the
alpha level for VaR at the 95% confidence level.
Formula Breakdown:
The formula can be interpreted as:
Explanation:
• μ\mu is subtracted by the adjustment term involving σ\sigma. This is because
we're calculating the average loss in the tail of the distribution.
• The adjustment term dnorm(qnorm(0.05,0,1),0,1)/0.05:
o qnorm(0.05,0,1) gives the z-score for the 5% quantile.
o dnorm(qnorm(0.05,0,1),0,1) gives the PDF evaluated at that z-
score (essentially the height of the curve at that point).
o Dividing by 0.05 normalizes this for the 5% tail.
Purpose:
This formula calculates the Expected Shortfall (ES) for a normal distribution, where
we adjust the mean μ\mu by a scaled version of the standard deviation σ\sigma to
account for the expected losses in the tail (i.e., worse than the VaR level).
In simpler terms, we are finding the expected average loss when returns fall into the
worst 5% of outcomes, given the distribution of the data.
25
Using Simulation to estimate VaR & ES
The simulation method offers a practical alternative for estimating VaR and ES when:
• Simulate Data: We draw a sample of, say, 100,000 outcomes from the normal
distribution. The 5th percentile of this simulated data will give us an estimate of VaR,
since VaR at 95% confidence is the return at the 5th percentile (1 - 0.95 = 0.05).
• Estimate Expected Shortfall: Once we have the simulated VaR, the Expected Shortfall
can be easily calculated. ES is the average of the returns that are worse than the
estimated VaR. We take the simulated data, filter out all the values below the VaR,
and compute the average of these values to get the ES.
Here’s a key point: As the sample size increases, the estimated VaR and ES from
simulation will get closer and closer to the true values.
26
Implementing Simulation in R
Now let’s dive into the steps and R code for simulating VaR and ES. First, we simulate
100,000 outcomes from a normal distribution with mean μ and standard deviation σ.
These parameters could be the ones we have calculated from historical data, such as the
Nifty 50 Index log returns.
# Estimate Expected Shortfall as the mean of the values below the VaR
ES <- mean(rvec[rvec < VaR])
# Display results
VaR
ES
> VaR
5%
-0.021693
> ES
[1] -0.02714128
In this code:
• We first set the confidence level, α\alpha, to 0.05, corresponding to a 95% confidence
level for VaR.
• The function rnorm() generates 100,000 random numbers from a normal distribution
with mean μ\mu and standard deviation σ\sigma. Here we take a note that the value
of μ (mu = 0.00032249) and σ (sig=0.01339796) is the previously calculated mean
and standard deviation of log returns of Nifty 50.
• The VaR is estimated using the quantile() function, which computes the 5th
percentile.
• The Expected Shortfall is calculated by taking the average of all simulated values
worse than the VaR.
Result: For the simulated data, the VaR is approximately -2.169%, and the Expected
Shortfall is around -2.714%. These values are close to the exact values derived from the
formulas for the normal distribution, showing the effectiveness of the simulation
method.
27
To illustrate how close simulation can be to the exact formulas, let’s compare the
simulated values with the exact values:
Even though the simulated results are not exact, they are very close to the true values. As
the number of simulations increases, the results become more precise.
For example, let’s say we have around 4,000 daily log returns for the Nifty 50 Index.
Instead of simulating from a normal distribution, we can bootstrap from the actual
observed returns by sampling with replacement.
Key benefits:
• No assumptions are needed about the underlying population distribution (non-
parametric).
• Bootstrap provides robust estimates of confidence intervals and standard
errors, especially when theoretical formulas are complex or unavailable.
28
# Sample 100,000 values with replacement from the historical log
returns
rvec_empirical <- sample(logret, size = 100000, replace = TRUE)
# Estimate Expected Shortfall as the mean of the values below the VaR
ES_empirical <- mean(rvec_empirical[rvec_empirical < VaR_empirical])
# Display results
VaR_empirical
ES_empirical
> VaR_empirical
5%
-0.01929073
> ES_empirical
[1] -0.03259898
Here, the only change is that instead of using rnorm(), we use sample() to sample with
replacement from the actual historical returns stored in logret.
Result: When we simulate from the empirical distribution, the VaR is around -1.93%, and
the Expected Shortfall is around -3.26%. These values are higher than the ones estimated
from the normal distribution, indicating that the actual data has fatter tails—meaning
that extreme losses are more frequent than the normal distribution predicts.
The empirical distribution shows fatter tails than the normal distribution, leading to
different estimates for both VaR and ES. This indicates that extreme losses are more
common than a normal distribution would suggest, making the normal assumption
insufficient in this case.
29
The simulation method for estimating VaR and Expected Shortfall is highly versatile and
powerful. It allows us to:
By simulating both from normal and empirical distributions, we gain deeper insights into
the actual risk profile of the portfolio. This helps us avoid the common pitfall of
underestimating risk when returns deviate from normality, a frequent occurrence in
financial markets. We will look into this aspect of non-normality in the next section.
30
31
Topic 3: Risk Management under non-Normal Distribution
In the context of analysing financial data, specifically returns from indices like the Nifty
50 Index, it’s essential to recognize that real-world data often deviate from the normal
distribution. While we may initially assume that financial returns follow a normal
distribution, empirical evidence frequently shows otherwise, leading to significant
implications for risk measures like Value at Risk (VaR) and Expected Shortfall (ES). Let’s
explore this deviation in more detail, focusing on common non-normal characteristics
like skewness and kurtosis, and their impact on risk estimation.
Non-Normal Distributions
Real-life data, such as financial returns or other behavioural data (e.g., coffee and
alcohol consumption), often do not adhere to the normal distribution. For example, if we
were to graph coffee consumption, there would likely be clusters at zero (non-drinkers),
a group of moderate drinkers, and a small number of extreme consumers (heavy
drinkers). This type of distribution, where there are more extreme values than would be
predicted by a normal distribution, is an example of non-normality.
• Left-skewed (negative skew): The left tail is longer, indicating more extreme negative
values. This is common in financial returns, where large losses (negative returns)
occur more frequently than large gains. Coefficient of skewness < 0.
• Right-skewed (positive skew): The right tail is longer, indicating more extreme
positive values. Coefficient of skewness > 0.
For financial returns, skewness has direct implications for risk management. VaR and
Expected Shortfall are sensitive to extreme negative outcomes. If the returns distribution
is left-skewed but we assume it is normal (and symmetric), we will underestimate the
32
likelihood of extreme negative returns, leading to underestimated VaR and ES. This can
expose a portfolio to more risk than anticipated.
A leptokurtic distribution indicates that extreme market movements (both gains and
losses) are more likely than a normal distribution would suggest. Therefore, VaR and
Expected Shortfall based on the normal distribution will again underestimate the risk
because the probability of large losses is higher.
In R, we can calculate skewness and kurtosis to quantify these deviations from normality.
We need to install and use “moments” package for calculating these statistics.
> round(skewness(rvec),3)
[1] -0.311
33
#calculate the Coefficient of kurtosis of log return of Nifty 50
rvec <- [Link](logret)
round(kurtosis(rvec),3)
> round(kurtosis(rvec),3)
[1] 18.232
• The skewness is -0.311, indicating left skewness, meaning large negative returns are
more likely than large positive returns.
• The kurtosis is 18.232, much greater than 3, confirming that the distribution is
leptokurtic, with heavy tails implying more frequent extreme outcomes.
To formally test whether a dataset follows a normal distribution, we can use the Jarque-
Bera test, which combines skewness and kurtosis into a single test statistic. If the p-value
of the test is very small (close to zero), we reject the null hypothesis that the data are
normally distributed. For the Nifty 50 Index, the Jarque-Bera test produces a p-value near
zero, strongly rejecting the null hypothesis of normality.
> [Link](rvec)
data: rvec
JB = 37961, p-value < 2.2e-16
alternative hypothesis: greater
The deviations from normality—left skewness and heavy tails—highlight a key issue in
risk management. VaR and ES are primarily concerned with the left tail of the return
distribution, where large losses reside. If we assume normality when the true distribution
is skewed or leptokurtic, we will significantly underestimate risk. The skewness and
leptokurtosis of the Nifty 50 Index returns suggest that relying on a normal assumption
leads to overly optimistic (i.e., smaller) estimates for VaR and ES. Thus, we must either
use non-parametric methods or select models that account for these deviations.
These findings, confirmed through skewness, kurtosis, and the Jarque-Bera test,
underscore the importance of avoiding normality assumptions when calculating VaR and
Expected Shortfall. Instead, we should embrace models that accommodate non-
normality, particularly when dealing with high-frequency financial data.
34
Note on Jarque-Bera test of normality
The Jarque-Bera test is a statistical test used to determine whether sample data have
the skewness and kurtosis matching a normal distribution. It assesses whether the data
deviate significantly from the normal distribution in terms of these two measures.
Interpretation if p-value = 0:
• A p-value of 0 (or extremely close to 0) means the test strongly rejects the null
hypothesis that the data is normally distributed. This suggests that the sample
data is significantly different from a normal distribution, implying that either:
In summary, if the p-value is 0, it indicates the data is highly non-normal, either in terms
of skewness, kurtosis, or both.
These graphical methods are useful for visually identifying departures from normality,
complementing the results of formal statistical tests.
35
Student-t Distribution
In analysing the log returns of the Nifty 50 index, we have found significant evidence
against the assumption that they follow a normal distribution. This indicates the need to
explore alternative distributions that may better capture the characteristics of our data.
One promising candidate is the student-t distribution, which we will investigate due to
its flexibility in handling data with heavier tails, a property that aligns with the log returns
of financial indices.
The probability density function (PDF) of the student-t distribution depends on a single
parameter: the degrees of freedom (ν/nu). This parameter ν/nu controls the shape of the
distribution:
• Mean: Regardless of the value of ν/nu, the student-t distribution has a mean of 0.
• Variance: The variance depends on ν and is given by the formula ν/ν−2, provided ν >
2. When ν is between 1 and 2, the variance is infinite. For values of ν ≤ 1, the variance
is undefined.
• Skewness: The student-t distribution is symmetric, meaning its skewness is 0 for ν >
3. If ν ≤ 3, skewness is not defined.
• Kurtosis: The kurtosis is given by 3+6/(ν−4) for ν > 4. The kurtosis becomes infinite for
ν values between 2 and 4, reflecting the heavy tails of the distribution.
As the degrees of freedom ν/nu increases, the student-t distribution approaches the
normal distribution. Specifically:
• When ν→∞, the student-t distribution becomes identical to the normal distribution
with mean 0, variance 1, skewness 0, and kurtosis 3.
• For large values of ν, the distribution becomes approximately normal, while for small
values of ν, the distribution retains its heavier tails.
36
When compared to the normal distribution, the student-t distribution with smaller ν
values exhibits greater probabilities for extreme outcomes (both positive and negative),
which is a key reason why it provides a better fit for financial data.
To better understand how the student-t distribution compares to the normal distribution,
we can plot the probability density functions (PDFs) for different degrees of freedom. As
ν decreases, the tails of the distribution become heavier:
The key challenge in fitting a student-t distribution to the log returns of the Nifty 50 index
lies in matching two important characteristics of the data: it’s standard deviation and
kurtosis. Unfortunately, the student-t distribution has only one parameter (ν/nu), which
makes it difficult to match both the standard deviation and kurtosis simultaneously. This
is because trying to solve for two unknowns (standard deviation and kurtosis) with one
parameter (ν) is like solving two equations with one unknown—an impossible task.
37
Rescaled Student-t Distribution
• Start with the standard student-t distribution with ν degrees of freedom, which has a
mean of 0 and a variance of ν/ν−2.
• Rescale the distribution by dividing each outcome by the square root of ν/ν−2, which
standardizes the variance to 1. The resulting distribution is called the rescaled
Student-t distribution or standardized Student-t distribution.
The advantage of this rescaling is that the rescaled distribution now has a standard
deviation of 1, while maintaining the same kurtosis as the original student-t distribution.
This allows us to separately choose ν to match the kurtosis of our data and then introduce
the scaling parameter to match the standard deviation.
Now that we understand the rescaled student-t distribution model, we can assess how
well it fits the log returns of the Nifty 50 index. The log return of the Nifty 50 index, denoted
r, is modelled as:
r = μ + σ⋅ϵ
where:
This model differs from the normal model only in the choice of the distribution for
ϵ\epsilon. In the normal model, ϵ\epsilon follows a standard normal distribution, whereas
in the rescaled student-t model, ϵ\epsilon follows a rescaled student-t distribution. The
primary reason for using the student-t model is to account for the heavier tails in the
distribution of log returns. The normal distribution has a fixed kurtosis of 3, but our data
exhibits a kurtosis of around 18.23. This discrepancy highlights the need for a model that
can better fit the data's fat tails.
To estimate the three parameters (μ\mu, σ\sigma, and ν\nu) of the rescaled student-t
distribution, we use maximum likelihood estimation (MLE). MLE is a standard statistical
method that identifies parameter values that maximize the likelihood of observing the
given data. The method is widely used, including in ordinary least squares regression,
when the error terms are normally distributed.
38
In R, we can implement MLE using the fitdistr function from the MASS package. This
function can estimate parameters for a variety of distributions, including the rescaled
student-t. Below is the process to estimate the parameters for the Nifty 50 log returns:
• μ\mu (mean),
• σ\sigma (scaling parameter or standard deviation),
• ν\nu (degrees of freedom).
> round([Link]$estimate,6)
m s df
0.000654 0.007961 2.886109
When the fitdistr function is applied to the log returns of the Nifty 50, the estimated
degrees of freedom (ν\nu) is approximately 2.88. This value is much smaller than infinity
(a large value of v/nu corresponds to a normal distribution). This suggests that the data is
far from normally distributed and that the student-t distribution, with its ability to capture
heavy tails, is a better fit for the data.
To visually compare the fit of the rescaled student-t distribution to the normal
distribution, we can plot their probability density functions (PDFs) alongside the
empirical density of the data.
39
• The blue line represents the empirical density (a smoothed histogram of the log
returns).
• The red line is the PDF of the fitted student-t distribution (using the estimated
parameters).
• The black line is the PDF of a normal distribution with the same mean and standard
deviation as the data.
The graph shows that the red line (student-t) aligns much better with the empirical data,
particularly in the tails, than the black line (normal). This confirms that the student-t
distribution provides a superior fit for the log returns of the Nifty 50 index.
40
Note on plotting fitted t-distribution along with the actual distribution
#Plot distribution of log returns of Nifty 50
density_estimation <- density(logret)
plot(density_estimation, col = "blue", xlab = "Log Returns/Fitted-t",
lwd = 4, ylab = "Density", main = "Log Returns & Fitted t-dist. of
Nifty 50")
# Add a legend
legend("topright", legend= c("Logret", "fitted-t", "normal"),
col=c("blue", "red", "black"), lwd=2)
41
Estimating Value at Risk (VaR) and Expected Shortfall
In this section we estimate the Value at Risk (VaR) and Expected Shortfall (ES) using the
fitted student-t model. We need to install and use “metRology” package and use a
simulation-based approach to calculate VaR and ES. Here's the process:
# Estimate Expected Shortfall as the mean of the values below the VaR
ES <- mean(rvec[rvec<VaR])
# Display results
round(VaR,8)
round(ES,8)
> round(VaR,8)
5%
-0.01846782
> round(ES,8)
[1] -0.03125972
For comparison, under the normal distribution, the VaR is around -2.17%, and the
Expected Shortfall is around -2.73%. Thus, the student-t model provides a slightly lower
VaR, but a higher Expected Shortfall than the normal model, indicating that it accounts
better for extreme losses in the data.
42
Application to SanPan Hedge Fund example
Let's apply these results to the SanPan hedge fund example, which
We want to estimate the one-day VaR and Expected Shortfall at a 95% confidence level.
Using the simulation results from the student-t model:
The student-t model suggests that while the potential for extreme losses is higher (as
shown by the Expected Shortfall), the likelihood of hitting the VaR threshold is lower
compared to the normal model.
The rescaled student-t distribution provides a better fit for the log returns of the Nifty 50
index, particularly because of its ability to account for heavy tails. This model yields more
realistic estimates of risk, especially in the context of Value at Risk and Expected
Shortfall.
In this analysis, we expand upon our previous exploration of one-day log returns for the
Nifty 50 Index to estimate the Value at Risk (VaR) and Expected Shortfall (ES) over a ten-
day holding period. To achieve this, we will utilize three distinct methods, each simulating
the ten-day returns in a different manner:
Each of these approaches provides a different perspective on how returns may behave
over the extended time horizon, allowing for deeper insights into risk management
strategies.
43
Method A: Simulating from the Estimated t-Distribution
# Loop to add 10 one day log returns for each 100,000 simulations
for (i in 1:10) {
rvec <- rvec + [Link](100000,
mean=[Link]$estimate[1],sd=[Link]$estimate[2],df=[Link]$estimate[3])
}
> VaR
5%
-0.06255856
> ES
[1] -0.09277709
44
Method B: Simulating from the Empirical Distribution Using IID Draws
Method B leverages the empirical distribution of the observed one-day returns. In this
method, we simulate the ten-day returns by drawing from the actual data, assuming that
each draw is independent and identically distributed (IID).
• Draw 100,000 one-day returns from the empirical distribution with replacement.
• Loop through ten iterations to simulate ten one-day returns for each of the 100,000
simulations.
• Sum the ten one-day log returns to obtain a ten-day return for each simulation.
• Calculate VaR and ES as in Method A.
# Method B
# Set Alpha (significance level) for VaR
alpha <- 0.05
> VaR
5%
-0.06541971
> ES
[1] -0.09082353
The key aspect of this method is that it assumes no time dependence between daily
returns, as each return is drawn independently from the historical data.
45
Method C: Simulating from the Empirical Distribution Using Block Draws
Method C introduces the concept of block draws, where consecutive returns are treated
as dependent rather than independent. This method is useful when there is a potential
correlation between returns across consecutive days.
> VaR
5%
-0.06256083
> ES
[1] -0.106257
46
In contrast to Method B, this approach maintains any time dependence present in the
actual data, as it preserves the consecutive nature of the returns within each block of ten
days.
After running simulations using all three methods, we obtain the following results for the
ten-day VaR and ES at the 95% confidence level:
• Method A (t-distribution) yields the lowest estimates for VaR and ES, potentially due
to the parametric assumptions of the t-distribution.
• Method B (IID from empirical) produces a slightly larger VaR, indicating higher risk due
to the lack of assumptions on the distribution.
• Method C (Block draws) results in similar VaR to Method A, but a higher ES, suggesting
that the ten-day returns tend to exhibit some degree of time dependence in the actual
data.
These results highlight the importance of considering different methods when extending
risk estimates to longer holding periods. Each method provides valuable insights into
potential risks, with Method C being particularly useful for identifying any time
dependence in the data.
47
Note on Estimating VaR and ES for multi-day horizon
Method C: Simulating from the Empirical Distribution Using Block Draws
48
49
Topic 4: Risk Management under volatility clustering
Serial Correlation refers to the relationship between a variable and its past values in a
time series. If past values influence future values, the series is said to have serial
correlation (also called autocorrelation). This is important in financial data, as it can
reveal patterns or predictability over time. Volatility Clustering refers to the tendency of
high-volatility periods to be followed by high volatility, and low-volatility periods by low
volatility. This phenomenon is often observed in financial markets, where periods of large
price movements tend to cluster together, creating a pattern of varying volatility over
time.
Serial Correlation
In risk management, the goal is to develop a statistical model of the future distribution of
portfolio returns. For illustration, we are using the Nifty 50 Index as a proxy for our
portfolio, focusing particularly on the left tail of the distribution, which relates to potential
negative returns. Since the future distribution is unknown, we rely on the historical
returns of the portfolio to make assumptions about the future. Thus, our analysis is based
on two key assumptions regarding the relationship between historical and future returns,
as well as how we estimate the distribution parameters.
50
• However, if there is valuable information embedded in the sequence of returns (i.e.,
how returns evolve over time), then we might miss insights into the future
distribution by ignoring this order.
The second assumption is testable. If the time-order of the returns holds any significant
information, it could provide additional insight into future behaviour, beyond what the
distribution itself can tell us. Ignoring it could mean missing patterns such as serial
correlation, which would suggest that past returns could predict future returns to some
extent.
• Serial correlation evaluates the relationship between a return at time t and its return
at some past time t−j (lag j). For example, positive serial correlation means that a high
return today increases the likelihood of a high return tomorrow. Negative serial
correlation means the opposite.
• According to the theory of market efficiency, prices fully reflect all available
information, and any new information is unpredictable (either good or bad). Therefore,
returns should follow a random walk, implying no serial correlation (returns are
uncorrelated with their past values).
51
For the Nifty 50 index, the lack of significant serial correlation means that past returns do
not predict future returns. This is consistent with the random walk hypothesis, which
underpins market efficiency. Essentially, price movements are largely unpredictable and
are driven by new, unexpected information rather than patterns in past returns.
• No strong evidence of serial correlation: The daily log returns of the Nifty 50 index
show no significant autocorrelation, reinforcing the idea that stock prices follow a
random walk and are not easily predictable based on historical returns.
• Common finding in financial research: The absence of serial correlation is a typical
outcome in stock market studies, further supporting the random walk theory in real-
world data.
By understanding and testing these assumptions, we can better assess the limitations of
our models and the potential risks inherent in our portfolio.
Volatility Clustering
In financial markets, researchers have identified a phenomenon called volatility
clustering, where large changes in prices (returns) tend to be followed by more large
changes, and small changes by more small changes. This phenomenon plays a crucial
role in understanding market behaviour, as it suggests that volatility is not constant over
time but occurs in clusters.
The concept of volatility clustering gained prominence with the work of Robert Engle in
1982, when he introduced the ARCH (Autoregressive Conditional Heteroskedasticity)
model. Later, his student Tim Bollerslev extended this model, creating the GARCH
(Generalized Autoregressive Conditional Heteroskedasticity) model. Both models have
become standard tools for modelling and forecasting financial volatility. Engle’s work on
ARCH earned him the 2003 Nobel Prize in Economics, highlighting the model's
importance in financial time series analysis.
Explanation of Key Terms:
• Autoregressive: In time series analysis, this term means that the current value of a
variable is influenced by its past values.
52
• Conditional Heteroskedasticity: This is the technical term for volatility clustering,
where the variance of a time series is not constant over time but depends on past
variances.
53
The ACF of the absolute values of log returns reveals that large price changes (whether
positive or negative) tend to be followed by more large price changes. This is evidence of
volatility clustering. This means that periods of high volatility tend to cluster together, and
the same is true for periods of low volatility. Such patterns contradict the assumption of
constant volatility, a key aspect of volatility modelling in finance.
54
• Importance for Risk Modelling: Given that volatility is time-varying, risk models such
as VaR and Expected Shortfall can benefit from incorporating GARCH-type models
that adjust for these fluctuations. Static risk models may underestimate risk during
periods of market stress.
The next section covers the aspect of time varying volatility and GARCH.
55
GARCH
• The first "1" refers to the number of lagged squared error terms (past shocks) included
in the model. This means that the model takes into account the most recent past
shock ϵ2t−1 when estimating current volatility.
• The second "1" refers to the number of lagged conditional variance terms (past
volatility) included in the model. This means the model uses the previous period's
estimated volatility σ2t−1 to predict the current volatility.
The concept of modelling volatility in financial time series, particularly in stock returns,
is crucial for understanding market behaviour. Now, we'll break down the explanation of
the GARCH (1,1) model, starting with an overview of the problem and then moving step
by step through the model's structure and implications.
In finance, the log returns of an index like the Nifty 50 are often used to analyse market
movements. Log returns are commonly preferred because they allow for easier analysis
of percentage changes in prices over time. One critical finding with financial time series
is that they typically do not exhibit serial correlation in their returns. In simpler terms, it’s
hard to predict future returns based on past returns, meaning the average return over
time tends to be unpredictable.
However, while the mean of returns might be unpredictable, the volatility of returns often
behaves in a more predictable manner. Volatility, which is a measure of the standard
deviation or dispersion of returns, tends to cluster. This means that periods of high
volatility (large swings in returns) are often followed by more periods of high volatility, and
similarly, low volatility tends to persist for a while. This phenomenon suggests that while
we may not be able to predict the direction of returns, we may be able to predict the
degree of risk or uncertainty in future periods.
56
To model this time-varying volatility, we turn to the GARCH (1,1) model. But before we
dive into it, let’s first revisit the pioneering work of Robert Engle, who proposed the ARCH
model. This model laid the foundation for understanding volatility clustering by assuming
that current variance depends on past squared residuals.
1. Mean Equation:
Here, rt represents the return at time t, a0 is the expected return (a constant), and the
second term is the unexpected return. is the standard deviation (volatility) at time t,
and ϵt is a standard normal random variable (with mean 0 and variance 1).
2. Variance Equation:
This is the core of the GARCH model. It shows how the variance at time t, denoted by h t,
depends on three terms:
• α0: A constant term, representing the baseline level of variance.
• α1ϵ2t−1: This captures the influence of past shocks or surprises (squared residuals
from the previous period).
• β1ht−1: This represents the persistence in volatility, showing how past variance
influences current variance.
3. Distribution Equation:
ϵt∼ N (0,1)
This states that the error term ϵt follows a standard normal distribution.
57
• Impact of Past Shocks: The term α1ϵ2t−1 shows how large shocks (both positive and
negative) in the past can cause an increase in the variance. This is because ϵt−1
represents the unexpected return (or error) in the previous period, and squaring it
ensures that both large positive and large negative shocks increase the variance.
• Volatility Persistence: The term β1ht−1 ensures that if variance was high in the past, it
will likely remain high in the next period, contributing to the persistence of volatility.
Let’s illustrate how the GARCH (1,1) model produces volatility clustering with a simple
numerical example. Suppose we set β1=0.5 and α1=0.5, and consider a large negative
shock in period 1, where ϵ1=−2. Squaring this gives ϵ12 = 4. Using the variance equation:
h2=α0+0.5⋅h1+0.5⋅ϵ12
Assuming h1 was initially small, the large ϵ12 will cause h2 to be unusually large. In the next
period, h3 will depend on h2, which is now large, leading to h3 also being large. This process
continues, showing how large shocks in one period led to elevated volatility in subsequent
periods, creating the clustering effect.
The GARCH (1,1) model is a powerful tool for capturing the dynamic nature of volatility in
financial time series. It accounts for volatility clustering, which is a hallmark of financial
data, by modelling how past shocks and variance influence current volatility. Despite its
simplicity, the GARCH (1,1) model can capture many of the essential features of financial
markets, making it a cornerstone of modern financial econometrics.
58
Estimating GARCH - N (µ, σ)
The Generalized Autoregressive Conditional Heteroskedasticity (GARCH) model is widely
used in financial time series analysis for modelling volatility. The rugarch package in R
allows us to easily estimate and fit GARCH models to time series data, avoiding the
complexity of manually coding the algorithms. As explained in the previous section, the
GARCH (1,1) model includes three key components:
Here:
59
• Fitting the GARCH Model
Next, we use the ugarchfit() function to estimate the GARCH model using the log
return data stored in the variable logret.
The ugarchfit() function estimates the parameters of the model using maximum
likelihood estimation (MLE). The arguments are:
Once the GARCH model is estimated, we can view the results by printing the fitted
object. This will show the estimated parameters, including the mean (μ), variance (ω),
and the GARCH terms (α1, β1).
*---------------------------------*
* GARCH Model Fit *
*---------------------------------*
Optimal Parameters
------------------------------------
Estimate Std. Error t value Pr(>|t|)
mu 0.000740 0.000143 5.1731 0.00000
omega 0.000001 0.000001 1.3127 0.18927
alpha1 0.095023 0.015490 6.1344 0.00000
beta1 0.898427 0.015107 59.4724 0.00000
60
We can now extract fitted values (e.g., conditional standard deviations and residuals)
from the GARCH model for further analysis using the cbind() function.
In this code:
• The first column is the original log returns.
• The second column contains the fitted conditional standard deviations (volatility
estimates).
• The third column contains the fitted residuals (error terms).
Diagnostic Checks
After fitting the GARCH model, it is important to check whether the assumptions hold,
such as the normality of residuals and the absence of volatility clustering in the fitted
residuals. Here’s how to perform these diagnostics:
• Normality of Residuals: The residuals from the GARCH model, denoted zt , should
ideally have a mean close to zero, standard deviation close to one, skewness close to
zero, and kurtosis close to three if the errors are normally distributed.
> mean(save1$z)
[1] -0.04360572
> sd(save1$z)
[1] 0.9998905
> skewness(save1$z)
[1] -0.2088387
> kurtosis(save1$z)
[1] 5.111375
data: [Link](save1$z)
JB = 756.62, p-value < 2.2e-16
alternative hypothesis: greater
61
• Autocorrelation of Residuals: Check for autocorrelation in the residuals using the
autocorrelation function (ACF). Ideally, the residuals should show no significant
autocorrelation if the model is correctly specified.
The ACF of the absolute residuals shows no significant autocorrelation, this indicates
that the GARCH model has successfully captured the volatility clustering in the data.
Interpretation of Results
The results of the diagnostic tests may reveal that the residuals (errors) are not perfectly
normally distributed, but this does not invalidate the usefulness of the GARCH model. In
most cases, the GARCH model reduces the heavy tails observed in financial time series
(e.g., kurtosis), but further refinements (such as using different error distributions) may
be needed to fully capture extreme behaviour.
The GARCH model estimated using the rugarch package provides a robust framework
for modelling financial volatility. While the basic model captures volatility clustering
effectively, diagnostics like the normality test and ACF of residuals help refine the model.
For cases where the residuals exhibit non-normal behaviour, alternative distributions
(such as t-distribution) can be explored to improve the model further.
62
Enhancing the GARCH Model with a Rescaled t-Distribution
In previous section, we saw that the GARCH (1,1) model with a normal distribution
effectively captures volatility clustering but struggles to fully account for the heavy tails
observed in financial time series data. Heavy tails are particularly important when
estimating Value at Risk (VaR) and Expected Shortfall (ES), which are risk measures
sensitive to the left tail of the return distribution.
To address this, we will modify the GARCH model by changing the distribution of the error
term from the normal distribution to a rescaled t-distribution, which has heavier tails.
This allows the model to better capture both volatility clustering and the heavy tails,
providing a more accurate description of return behaviour.
While the GARCH (1,1) model’s variance equation is effective in capturing volatility
clustering, the normal distribution does not adequately explain the heavy tails observed
in financial data. Returns often exhibit higher probabilities of extreme values than what is
predicted by the normal distribution. The t-distribution is better suited for modelling
these extreme returns because of its thicker tails.
63
Here:
Next, we use the ugarchfit() function to estimate the parameters of the GARCH
model with the rescaled t-distribution.
#Fit the GARCH model with rescaled t-distribution to log return data
[Link].t <- ugarchfit(spec = garch.t, data = logret)
Once the model is estimated, we can examine the output. The new model includes
an additional parameter called shape, which represents the degrees of freedom ν\nu
of the t-distribution.
*---------------------------------*
* GARCH Model Fit *
*---------------------------------*
Optimal Parameters
------------------------------------
Estimate Std. Error t value Pr(>|t|)
mu 0.000774 0.000138 5.6190 0.000000
omega 0.000001 0.000001 1.1257 0.260296
alpha1 0.079672 0.017121 4.6535 0.000003
beta1 0.910667 0.017546 51.9018 0.000000
shape 7.645170 0.717462 10.6559 0.000000
64
• Shape (ν): The degrees of freedom for the rescaled t-distribution. Lower values of
ν\nu indicate heavier tails.
As before, we can save some key outputs such as the log returns, fitted conditional
standard deviations, and residuals. Additionally, we save the estimated parameters
for future analysis.
> head(parm1)
mu omega alpha1 beta1 shape
7.740919e-04 1.473945e-06 7.967245e-02 9.106665e-01 7.645170e+00
We have estimated the GARCH (1,1) model with t-distributed errors, we need to evaluate
its adequacy by conducting a diagnostic test.
• Normality of Residuals:
When fitting a GARCH model with t-distributed errors, we examine the standardized
residuals Zt , which are the fitted values of the error term ϵt . For this model, the
statistical properties of standardized residuals (Zt) should exhibit the following
properties:
where ν\nu is the estimated degrees of freedom parameter for the t-distribution. In
this case, ν\nu is estimated to be 7.65 (shape parameter), which gives: Kurtosis=3+ 6/
(7.65−4) ≈4.64. This higher kurtosis reflects the fatter tails of the t-distribution, which
helps capture extreme returns (outliers).
The diagnostic tests on the fitted model reveal the following actual values of
standardized residuals (Zt)
65
# Check for normality of residuals (save1$z)
mean(save1$z)
sd(save1$z)
skewness(save1$z)
kurtosis(save1$z)
> mean(save1$z)
[1] -0.0467351
> sd(save1$z)
[1] 1.0027
> skewness(save1$z)
[1] -0.2128977
> kurtosis(save1$z)
[1] 5.232773
Since the t-distribution is not normal, there is no need to run the Jarque-Bera test for
normality, which is typically used to test for departures from normality in the
residuals.
After estimating the model, we assess the autocorrelation structure of the residuals
to verify whether the model has captured all the significant dynamics in the data.
66
We examine the autocorrelation function (ACF) of the fitted residuals ϵt . We also look
at the ACF of the absolute values of the residuals ∣ϵt∣, which helps detect volatility
clustering (i.e., periods of high volatility followed by more high volatility, and low
volatility followed by low volatility). The results indicate:
The rescaled t-distribution should improve the model’s ability to explain the heavy
tails in the data, particularly in financial time series where extreme values are
common. However, the degrees of freedom parameter ν\nu will reveal how heavy
these tails are:
• If ν\nu is small, the model will exhibit significantly heavier tails compared to the
normal distribution.
• If ν\nu is large, the model will behave more like a standard GARCH model with
normal errors.
By fitting the model with a rescaled t-distribution, we enhance its ability to estimate
extreme risks, such as Value at Risk (VaR) and Expected Shortfall (ES), which are
sensitive to the tails of the return distribution. The GARCH (1,1) model with t-
distributed errors explains much of the volatility clustering and excess kurtosis (i.e.,
the fat tails of the distribution). However, one notable aspect that remains
unexplained is the left skewness observed in the residuals. While this is not captured
by the basic GARCH model, it is possible to extend the model to account for
asymmetry by using a skewed t-distribution or other variants like EGARCH or GJR-
GARCH, but these models introduce additional complexity.
The fitted volatilities from the GARCH model. The variable st represents the daily
standard deviation of log returns, which is then annualized by multiplying it by sqrt
{252} (assuming 252 trading days in a year).
• The fitted volatility changes over time, reflecting periods of market turbulence,
such as the 2008 financial crisis, when volatility surged higher.
• Volatility changes are directly linked to risk measures like Value at Risk (VaR) and
Expected Shortfall (ES). In periods of high volatility, both VaR and ES rise,
indicating increased risk. Conversely, in low-volatility periods, VaR and ES
decrease.
67
The GARCH (1,1) model with t-distributed errors performs well in capturing volatility
clustering and excess kurtosis in financial return data. It provides a reasonable estimate
of time-varying volatility and aligns well with market expectations. However, the model
leaves some left-skewness unexplained, which could be addressed by further extensions
to the model, albeit with increased complexity.
Despite its limitations, the GARCH model remains a robust tool for understanding and
forecasting market volatility, and its outputs are useful for risk management, particularly
in calculating metrics like VaR and Expected Shortfall.
68
VaR and Expected Shortfall for GARCH Bootstrap
The process involves using the GARCH model to estimate Value at Risk (VaR) and
Expected Shortfall (ES) through simulation. We will understand these risk assessment
over different periods using the GARCH model.
In this case, we are using a GARCH model that has been fit to a time series of financial
returns. It incorporates the volatility clustering. We are using a GARCH model with
student-t errors, which allows for fatter tails than the normal distribution. This is
particularly useful in financial markets, where large outliers occur more frequently
than under normal distribution assumptions.
> VaR
5%
-0.01236714
> ES
[1] -0.01699853
We are simulating future returns using the ugarchboot function, which generates
bootstrapped samples from the fitted GARCH model. The aim is to simulate potential
future outcomes of the time series and then estimate risk measures such as VaR and
ES. Following are the key arguments of ugarchboot:
• First Argument: The fitted GARCH model ([Link].t) – This is the model
previously estimated with our dataset and includes parameters that describe both
the conditional mean and volatility dynamics.
• Second Argument: Simulation method (partial) – This method involves
simulating only part of the model, such as the residuals or the volatility process.
69
• Sampling Argument (raw): This implies that the simulation is based on the raw
residuals (errors) of the fitted model, rather than filtering or transforming the
residuals in any way.
• [Link]: This specifies the number of steps ahead for the simulation. We set it to
1, which means simulating returns one day into the future.
• [Link]: The number of bootstrap samples to generate. In this case, we have
used 100,000 simulations, which ensures that the estimates for risk measures like
VaR and ES are based on a large, robust set of simulated outcomes.
• Solver (solnp): Refers to the solver method for numerical optimization. solnp is
a common method used to estimate parameters for nonlinear optimization
problems.
The reason the GARCH model produces varying estimates of VaR and ES is that it takes
into account volatility clustering. This means that it adjusts the risk measures according
to the current state of volatility in the market. When volatility is high (like during the 2008
crisis or Black Monday), the GARCH model reflects this by producing higher VaR and ES
estimates. When volatility is low, the risk measures are correspondingly lower.
In contrast, traditional models (like historical VaR) assume constant volatility and provide
estimates based on typical market conditions, ignoring periods of high or low volatility.
This makes them less responsive to current market risks.
By using the GARCH model and simulating future returns, we are able to obtain dynamic
estimates of VaR and Expected Shortfall that adjust based on the current level of market
volatility. This provides a more accurate reflection of risk compared to static models that
assume constant volatility. Such models are especially useful for portfolio managers,
who can use this information to adjust their strategies in response to changing market
conditions.
# Print table
print(results)
> print(results)
Method Value_at_Risk Expected_Shortfall
1 Formula based -0.02171519 -0.02731365
2 Simulation Normal Distribution -0.02169300 -0.02714128
3 Simulation Empirical Distribution -0.01929073 -0.03259898
4 Fitted T-Distribution -0.01846782 -0.03578082
5 GARCH (1,1) -0.01236714 -0.02632998
70
Estimating Rolling VaR
The process involves calculating rolling one-day ahead Value at Risk (VaR) using a GARCH
model by using the ugarchroll function from the rugarch package in R. This method
mirrors the approach used by a large US based investment bank, as described in their
filing and is designed to continuously update the VaR forecast as new data points are
added, with each forecast based on the GARCH model re-estimated daily.
The goal is to estimate the one-day ahead VaR dynamically over time, specifically for
each day in 2023, using data from previous periods (from 2008). This approach is known
as rolling window forecasting, where we re-estimate the model as new data becomes
available. This approach recalculates the GARCH model for each day by gradually adding
one more observation and estimating the next day’s VaR, making the model dynamically
adjust to new data.
• Determine Data Range: The first step is identifying the last trading day of 2022 in the
dataset of Nifty 50 logret. This day will mark the point where the rolling forecasts start
(from the beginning of 2023). This date is stored in a variable called n2023.
# Step 4: Access and view the VaR results from the @forecast slot
var_rolling <- [Link]([Link]@forecast$VaR)
head(var_rolling)
71
o spec: This argument specifies the GARCH model. In this case, garch.t is used,
which refers to a GARCH model with student-t errors (useful for capturing fat-
tailed distributions in financial returns).
o data: The dataset used for the estimation, which contains the log returns of the
financial instrument (Nifty 50).
o [Link]: This is set to 1, meaning that a one-day ahead VaR is calculated for
each day.
o [Link]: This defines how many observations we want the function
to forecast. Since we are doing rolling one-day ahead VaRs, this is set to 1 as
well.
o [Link]: This specifies the start of the rolling window, which is set to n2023, the
index corresponding to the last trading day of 2022.
o [Link]: This controls how often the model is re-estimated. Setting this to
1 means the GARCH model is re-estimated after every new data point is added.
o [Link]: This is set to recursive, meaning that each new forecast
includes all previous data points, extending the dataset as new observations
come in.
o [Link]: Setting this to TRUE tells the function to calculate VaR for each
forecasted day.
o [Link]: This is set to 0.05, corresponding to the 95% confidence level.
o [Link]: Setting this to TRUE ensures that the coefficients of the model are
kept for each re-estimation. This can be useful for diagnosing model behaviour
over time.
• Storing the output: The output from ugarchroll is stored in a variable called
[Link], which contains all the VaR calculations, forecasts, and model re-
estimates for each day in 2023.
• Graphing the rolling VaR and log returns: Once the rolling VaR is calculated, we can
generate a graph of rolling VaR and actual log returns:
72
• The red line in the graph represents the one-day ahead VaR at the 95% confidence
level for each day in 2023. This line changes over time as the GARCH model
updates its estimates of volatility.
• The blue bars represent the actual log returns for each day. If the GARCH model is
well-calibrated, no more than 5% of the daily log returns should fall below the red
VaR line (i.e., breach the VaR threshold).
• As can be seen from the graph of log returns and rolling VaR below, it is evident
that the actual (negative) returns exceed the rolling VaR 11 times over 245 days,
representing a breach rate of 4.49%.
In 2023, the GARCH model predicted that no more than 5% of the actual returns would
fall below the VaR line. In this case, the actual proportion of breaches was 4.49%, which
is within acceptable limits and indicates that the GARCH model is reasonably accurate
for this dataset.
Rolling VaR is a powerful tool for risk management, as it allows financial institutions to
continuously monitor and adjust their risk forecasts based on the most recent market
data. In contrast to static VaR calculations (which assume constant volatility), the rolling
GARCH model captures the dynamic nature of financial markets by adjusting for volatility
clustering and other time-varying effects.
Using the ugarchroll function, we can dynamically estimate one-day ahead VaR over
time while accounting for changing volatility, thanks to the GARCH model’s ability to
adjust to new data. The rolling VaR provides a robust way to manage and assess risk,
offering portfolio managers a real-time understanding of the risk they face in fluctuating
market conditions.
73
74
Topic 5: Gold: The Safe Heaven
Return Distribution
In the previous sections, we have seen the calculation of VaR and ES for Nifty 50 index by
using multiple methods. We can have a similar kind of analysis for gold prices as well,
like we did for Nifty 50. We have retrieved the gold prices from 2nd January 2007 till 2023.
We can use the same R codes to calculate the log returns, various statistics and plot the
log returns of the gold and its distribution as represented below.
The standard statistical summary of both the assets, i.e. Nifty 50 and Gold is given below.
75
VaR & Expected Shortfall
As discussed previously, we have calculated the Value at Risk (VaR) at the 95%
confidence level and Expected Shortfall (ES) for log returns of gold prices. Here’s a
breakdown of what each method used:
• Formula-based: This uses theoretical distributions and formulas, typically under the
assumption of normality.
• Simulation using Normal Distribution: This approach involves simulating returns
based on a normal distribution. The results are similar to the formula-based
approach, with slight differences may come from the randomness in simulation.
• Simulation using Empirical Distribution: This approach relies on actual historical
data (empirical distribution), providing a non-parametric estimate of VaR and ES.
Nifty 50 Gold
Approach
VaR - 95% ES VaR - 95% ES
Formula based -0.02171519 -0.02731365 -0.01802496 -0.02267402
Simulation -0.02169300 -0.02714128 -0.01800653 -0.02253087
Normal Dist.
Simulation -0.01929073 -0.03259898 -0.01790366 -0.02664023
Empirical Dist.
These comparisons highlight how assumptions and methods affect risk metrics,
especially with non-normal data where empirical methods may capture tail risks better.
Like the Nifty 50 index, we have found significant evidence against the assumption that
log returns of gold follow a normal distribution. This indicates the need to explore
alternative distributions that may better capture the characteristics of our data. We
explore the student-t distribution for gold as well to handle data with heavier tails.
76
Nifty 50 Gold
Approach
VaR - 95% ES VaR - 95% ES
Student-t Model -0.01846782 -0.03125972 -0.01602407 -0.02188191
The student-t model suggesting a more moderate VaR due to the heavy-tailed
distribution. The ES reflecting a heavy tail but still lower than empirical simulation for
Gold. We can summarize as under:
• Formula-based and Normal Simulations yield similar results, assuming returns are
normally distributed.
• Empirical Simulation captures more extreme events in both assets, especially in ES.
• Student-t Model reflects moderate VaR but can show higher ES than normal
assumptions, addressing heavy tails better than normal simulations but with
generally smaller expected losses than empirical.
The choice of model affects both risk metrics, particularly in assets prone to heavy tails
or non-normal distribution, such as financial indices and commodities like Gold.
Like Nifty 50 index, log returns on gold also lacks significant serial correlation, which
means that past returns do not predict future returns. The absolute values of log returns
of gold reveals that large price changes (whether positive or negative) tend to be followed
by more large price changes. This is evidence of volatility clustering similar to Nifty 50.
• Normality: Gold’s log returns deviate from normality, supporting alternative models
like the student-t for heavy-tailed distributions.
• Serial Correlation and Volatility Clustering: Similar to Nifty 50, Gold shows no serial
correlation (no predictive pattern in returns), but large price changes tend to cluster,
indicating volatility clustering.
77
78
Topic 6: Fixed Income: The Conservative Investment
Return Distribution
We will now consider a fixed income asset to analyse the risk in a similar way. A popular
fixed income index available in Bloomberg is “LEGATRUU”. It represents the Bloomberg
Global Aggregate Bond Index, which is widely used as a benchmark for global
investment-grade fixed-income portfolios. This index includes various bond types, such
as government, corporate, and asset-backed securities from both developed and
emerging markets. Its components meet specific liquidity, maturity, and credit-quality
criteria, ensuring a comprehensive view of the global bond market.
The LEGATRUU Index provides important metrics like yield to maturity, duration, and
average maturity, making it useful for analysing overall bond market trends. To access its
data on Bloomberg terminals, we can refer "LEGATRUU Index," which should give
historical returns, performance details, and related analytics.
The standard statistical summary of Nifty 50, Gold and FI Index is given below.
79
The log return plot of LEGATRUU:
• Risk-Return Profile: Nifty 50 has the highest returns but also the highest volatility,
skewness, and kurtosis, which suggests a higher potential reward but with more risk
of extreme negative outcomes.
• Gold provides a balanced profile with relatively high returns and moderate volatility.
• LEGATRUU offers the lowest return but with the least volatility, making it potentially
appealing as a lower-risk option.
• We can check the normality assumptions also for the log returns of LEGATRUU.
80
VaR & Expected Shortfall
As discussed previously, we have calculated the Value at Risk (VaR) at the 95%
confidence level and Expected Shortfall (ES). Here’s outcome of the calculations for each
method used for Nifty 50, Gold and LEGATRUU.
Nifty 50 Gold LEGATRUU
Approach
VaR - 95% ES VaR - 95% ES VaR - 95% ES
Formula based -0.02171 -0.02731 -0.01802 -0.02267 -0.00541 -0.00681
Simulation -0.02169 -0.02714 -0.01801 -0.02253 -0.00541 -0.00676
Normal Dist.
Simulation -0.01929 -0.03260 -0.01790 -0.02664 -0.00533 -0.00751
Empirical Dist.
Looking at the statistical properties of log returns of LEGATRUU, i.e. positively skewed
with higher kurtosis, we need to assess the return with student-t distribution and
calculate the VaR and Expected Shortfall assuming the log returns of LEGATRUU follows
student-t distribution.
The student-t model’s ES shows moderate tail risk beyond the normal distribution for
Nifty 50 and LEGATRUU, reflecting the model’s fat-tail property but with less extremity
than the empirical simulation.
81
We can summarise the risk of these assets as under:
• Riskier Asset (VaR and ES): Nifty 50 exhibits the highest potential losses in all
scenarios, indicating it carries the most tail risk.
• Lower-Risk Asset: LEGATRUU has the lowest VaR and ES across all approaches,
indicating it may be the most stable of the three.
• Model Impact: The Empirical and student-t models suggest that tail risks (especially
ES) may be underrepresented in the normal distribution for assets like Nifty 50, which
have higher skewness and kurtosis.
Like Nifty 50 index, log returns of LEGTRUU also lacks significant serial correlation, which
means that past returns do not predict future returns and evidenced volatility clustering.
82
83
Topic 7: Cryptocurrency: The Unpredictable Titan
Bitcoin
The first cryptocurrency, Bitcoin, was created in 2009 by an anonymous entity known as
Satoshi Nakamoto, and it remains the largest cryptocurrency by market capitalization.
What is Bitcoin?
84
• Investment: Many people buy and hold Bitcoin as an investment, hoping it will
increase in value over time. Bitcoin has seen significant price increases since its
inception, although it remains highly volatile.
• Bitcoin has sparked a global movement and led to the creation of thousands of other
cryptocurrencies and blockchain projects. While it’s still early to predict its ultimate
role, Bitcoin has solidified itself as a cornerstone of the evolving cryptocurrency
space.
85
Return Distribution
Like Nifty 50, Gold and FI Index we can analyse the returns generated by Bitcoin over the
years. The historical prices of Bitcoin from 2015 to current date in 2024 was retrieved and
calculated the log returns and plot the log returns of Bitcoin in a similar fashion.
The standard statistical summary of Nifty 50, Gold, LEGATRUU and Bitcoin is given below.
86
Based on the statistics provided for Nifty 50, Gold, and Bitcoin, we can draw insights into
their daily returns in terms of average return (μ\mu), risk (standard deviation or σ\sigma),
skewness, and kurtosis. Here’s an interpretation of each measure:
Skewness
• Nifty 50: Skewness of -0.311 indicates a slight left skew, meaning extreme negative
returns are slightly more frequent than positive returns.
• Gold: With a skewness of -0.245, Gold also has a minor left skew, though less
pronounced than Nifty 50.
• LEGATRUU: is positively skewed which indicates that the distribution of returns has a
longer tail on the right side.
• Bitcoin: Skewness of -0.794 indicates a stronger left skew, suggesting that Bitcoin is
prone to experiencing occasional sharp declines.
• Interpretation: All three assets, except LEGATRUU exhibit negative skewness, but
Bitcoin's skewness suggests it has the highest tendency for extreme negative events,
which could contribute to its reputation for volatility.
Kurtosis
• Nifty 50: Kurtosis of 18.232 shows extremely high “fat tails,” implying that the Nifty 50
experiences more extreme events than a normal distribution would predict.
• Gold: Kurtosis of 8.708 is still high, though much lower than Nifty 50, showing
moderate risk of extreme returns.
87
• LEGATRUU: Kurtosis is high and relatively lesser than other assets, showing moderate
risk of extreme returns.
• Bitcoin: Kurtosis of 14.604 suggests high kurtosis, indicating a high likelihood of
extreme returns, similar to Nifty 50 but less than the stock index.
• Interpretation: All these assets have high kurtosis, meaning returns have a greater
likelihood of extreme values. However, Nifty 50 is the most prone to extreme events,
followed by Bitcoin.
• Bitcoin stands out with the highest average return but also the highest risk (standard
deviation) and significant skewness and kurtosis, indicating extreme volatility and
susceptibility to sharp declines.
• LEGATRUU has the lowest volatility and positive skewness, making it the safest
assets and used as a hedge against market risk.
• Gold has lower volatility and skewness, making it a safer asset, typically used as a
hedge against market risk.
• Nifty 50 offers moderate returns with moderate volatility, but its high kurtosis
suggests occasional sharp market moves.
This analysis indicates that Bitcoin may provide higher returns, but with considerable
risk, while LEGATRUU and Gold offers stability, and Nifty 50 lies in between, with potential
for moderate growth and risk. Investors would balance these assets depending on their
risk tolerance and return expectations.
In this case of Bitcoin also, we have found significant evidence against the assumption
that log returns follows a normal distribution. Likewise, the student-t distribution needs
to be used for Bitcoin to handle data with heavier tails.
88
VaR & Expected Shortfall
As discussed previously, we have calculated the Value at Risk (VaR) at the 95%
confidence level and Expected Shortfall (ES). Here is a detailed comparative analysis of
the Value at Risk (VaR) and Expected Shortfall (ES) for Nifty 50, Gold, LEGATRUU, and
Bitcoin, under different modelling approaches. Including Bitcoin in this assessment adds
insight into the behaviour of a high-volatility asset within a risk framework.
Bitcoin exhibits the highest VaR among the assets, reflecting its high volatility. The
formula-based and normal simulation approaches suggest potential daily losses of
around 6%, whereas the empirical and student-t models indicate slightly lower VaR
values. The student-t model, with its fat tails, suggests a somewhat lower VaR at 5.2%,
which may indicate a less extreme risk profile for Bitcoin compared to the assumption of
normality.
ES is significantly higher for Bitcoin than for other assets, particularly in the empirical and
student-t models. The empirical simulation estimates that losses beyond VaR could
average around 9.26%, while the student-t model estimates an average loss of 10.56% in
extreme conditions, emphasizing Bitcoin’s susceptibility to extreme tail events.
Comparative Insights:
• Risk and Extreme Events: Bitcoin stands out for its high VaR and ES across all
models, illustrating its substantial tail risk. Nifty 50 also has relatively high ES,
especially under empirical and student-t models, indicating the potential for extreme
losses.
• Risk Aversion: LEGATRUU has the lowest risk (both VaR and ES), suggesting it is the
most stable asset among those considered, aligning with typical bond index
characteristics.
• The Empirical Distribution generally produces higher ES values, capturing the actual
observed data's tail risk and showing how historical distributions can impact risk.
• The student-t model yields mixed results; for Bitcoin, it shows the highest ES, while
for other assets like Gold, it suggests relatively moderate tail risk.
89
• Bitcoin and Nifty 50 exhibit the highest tail risk, making them more suitable for risk-
tolerant investors or as smaller allocations within a diversified portfolio.
• Gold serves as a more stable hedge, offering moderate returns with relatively
contained risk.
• LEGATRUU is a conservative choice, displaying minimal risk across all models.
Investors in high-risk assets (like Bitcoin) should account for the considerable tail risk
beyond typical VaR thresholds, as reflected in high ES values. For risk-averse investors,
LEGATRUU and Gold, with their low VaR and ES, might be more suitable due to their
stability and lower risk of extreme losses.
The differences across approaches highlight the importance of selecting appropriate risk
models based on the asset characteristics. The empirical and student-t methods capture
extreme events more effectively, which could be vital for high-volatility assets like Bitcoin.
Like Nifty 50 index and gold, log returns of Bitcoin also lack significant serial correlation,
which means that past returns do not predict future returns. The absolute values of log
returns of Bitcoin reveals that large price changes (whether positive or negative) tend to
be followed by more large price changes. This is evidence of volatility clustering.
90
91
Appendix – Complete R code for Nifty 50 Analysis
This R code performs an analysis using Nifty 50 data, covering the first four topics of the
analysis. The same structure can be used for other asset classes such as Gold, Fixed
Income, and Bitcoin by simply replacing the dataset. The analysis for these asset classes,
which is covered in topics 5 to 7, follows the same methodology as the initial analysis.
The code is updated to fetch the latest data, ensuring that the analysis is based on the
most current information. You can easily adapt this code by retrieving data for any asset
class from appropriate data sources.
#Topic 1: Introduction to R
#Retrieving Data and calculating returns
library(quantmod)
# Retrieving data from a given source
sec <- getSymbols("^NSEI",src="yahoo",[Link]=FALSE)
#calculating return
#following formula will calculate the logreturn of closing price of
#the security and sotre the daily returns in object "logret"
logret <- diff(log(sec$[Link]))[-1]
92
head(round(discreteret_w, 6), 3)
# calculate the value at risk VaR @ 95% confidence interval and store it in
"var"
var<-qnorm(.05,mu,sig)
#Display VaR
var
# Estimate Expected Shortfall as the mean of the values below the VaR
ES <- mean(rvec[rvec < VaR])
# Display results
VaR
ES
# Sample 100,000 values with replacement from the historical log returns
rvec_empirical <- sample(logret, size = 100000, replace = TRUE)
# Estimate Expected Shortfall as the mean of the values below the VaR
ES_empirical <- mean(rvec_empirical[rvec_empirical < VaR_empirical])
# Display results
VaR_empirical
ES_empirical
93
#compare the calculations for the 3 approaches
es
ES
ES_empirical
var
VaR
VaR_empirical
######################################################################
######################################################################
######################################################################
94
density_estimation <- density(logret)
plot(density_estimation, col = "blue", xlab = "Log Returns/Fitted-t", lwd =
4, ylab = "Density", main = "Log Returns & Fitted t-dist. of Nifty 50")
#Plot normal distribution with same mean and sd as Nifty 50 log returns
x <- seq(min(logret), max(logret), length=4000)
lines(x, dnorm(x,mu,sig), col="black", lwd=2)
# Add a legend
legend("topright", legend= c("Logret", "fitted-t", "normal"),
col=c("blue", "red", "black"), lwd=2)
#####################################################################
library(metRology)
# Set Alpha (significance level) for VaR
alpha <- 0.05
# Estimate Expected Shortfall as the mean of the values below the VaR
ES_t <- mean(rvec[rvec<VaR])
# Display results
round(VaR_t,8)
round(ES_t,8)
95
#Estimating VaR and ES for multiday horizon
#Method A
# Set Alpha (significance level) for VaR
alpha <- 0.05
# Loop to add 10 one day log returns for each 100,000 simulations
for (i in 1:10) {
rvec <- rvec + [Link](100000,
mean=[Link]$estimate[1],sd=[Link]$estimate[2],df=[Link]$estimate[3])
}
#Method B
# Set Alpha (significance level) for VaR
alpha <- 0.05
# Loop through 10 iterations to sum 10 one day returns and generate 100,000
simulations
for (i in 1:10) {
rvec <- rvec + sample([Link](logret), 100000, replace=TRUE)
}
#Method C
# Set Alpha (significance level) for VaR
alpha <- 0.05
96
# Initialize a vector for the 100,000 simulated ten-day returns
rvec <- rep(0, 100000)
library(rugarch)
97
# jarque bera test for normality of z (residual term)
[Link]([Link](save1$z))
98
# Step 3: Apply the ugarchroll function for rolling VaR
[Link] <- ugarchroll(spec = garch.t, data = logret, [Link] = 1,
[Link] = 1, [Link] = n2023, [Link] = 1, [Link] =
"recursive", [Link] = TRUE, [Link] = c(0.01, 0.05), [Link] =
TRUE)
# Step 4: Access and view the VaR results from the @forecast slot
# Access and View the VaR results from the @forecast slot
var_rolling <- [Link]([Link]@forecast$VaR)
head(var_rolling)
tail(var_rolling,150)
max(var_rolling)
# Print table
print(results)
# Add rolling VaR and breaches as columns to a data frame for review
var_breaches <- [Link](
Date = seq_along(logret["2023-01-01/2024-12-31"]),
LogReturns = logret["2023-01-01/2024-12-31"],
RollingVaR = var_rolling$`alpha(5%)`,
Breach = breaches
)
99
100
DISCLAIMER & ACKNOWLEDEGEMENT
The content of this book is intended to serve as a general guide for understanding the principles and practices of risk management.
The information contained herein has been compiled from a variety of sources, including books, online academic courses, and publicly
available materials. While every effort has been made to ensure accuracy and reliability, the author makes no claims or warranties
regarding the completeness, correctness, or timeliness of the content.
The reader should note that this book is not a substitute for professional advice or consultation with qualified experts in the field of risk
management. The application of risk management techniques varies across different industries, and this book should not be
considered a one-size-fits-all solution. The author assumes no responsibility for any actions taken or not taken based on the
information provided. The content has been adapted from multiple sources, and while proper citation and references have been made,
some sections may contain material that is similar to or directly quoted from existing works. Any errors or omissions are unintentional,
and feedback is always welcome. By using this book, reader acknowledge that the information provided is for educational purposes
only, and the application of the material is at reader’s own risk.
I am grateful to the R Core Developers and the many R users and contributors who have provided the software which is used extensively
in our risk management analyses. Most of the graphs in this book are drawn using the graphical packages available in R.
This book is written with the primary intention of sharing valuable knowledge and insights with readers who are seeking to enhance
their understanding of the subject matter. It is not intended for any commercial gain or financial benefit. The purpose behind its
creation is purely educational and philanthropic designed to contribute to the intellectual growth of individuals who are genuinely
interested in learning. There is no intention to profit from the book, and it has been produced solely to provide meaningful content to
the rightful audience. The focus remains firmly on disseminating wisdom, not on generating revenue or promoting any commercial
interests. Through this work, the author hopes to foster a deeper connection to the subject and inspire further exploration for those
who seek to learn.
AUTHOR
101
In a GARCH model, the choice of error distribution critically impacts the estimated risk measures like VaR and ES. A normal distribution may underestimate extreme events due to its thinner tails. In contrast, a rescaled or skewed t-distribution accommodates heavier tails, thus more accurately estimating extreme market risks. This choice enhances the model's ability to predict the probability and magnitude of extreme losses, offering a more robust risk assessment tool .
Essential diagnostic checks for evaluating a GARCH model include testing for normality of residuals, absence of autocorrelation, and checking for volatility clustering. These checks are vital because they ensure that the model appropriately captures the characteristics of the data, such as conditional heteroskedasticity and any unexplained variance. Fitting diagnostics like the Jarque-Bera test for normality, and examining autocorrelation functions, help identify model mis-specification and potential improvements, ensuring the model's predictive reliability for financial risk estimation .
The rescaled student-t distribution provides advantages over a normal distribution by better accommodating the heavy tails and excess kurtosis commonly found in financial return data. This distribution is capable of modeling extreme events more accurately due to its adjustable tail heaviness, thus improving the estimation of metrics like VaR and ES. This capability is crucial for addressing the presence of extreme market movements which often exceed the predictive capacity of the normal distribution .
The GARCH model assists in modeling time-varying volatility by capturing volatility clustering, a common feature of financial markets where high-volatility periods are followed by high volatility, and low volatility is followed by lower volatility. It fits a conditional variance model to data, explaining much of the observed variation and volatility over time. This makes it particularly useful for calculating risk metrics like VaR and ES, as they depend on volatility estimates .
Using various methods of return simulation, such as the t-distribution and empirical distribution, provides diverse perspectives on potential future scenarios, hence strengthening risk management. These methods offer flexibility in capturing complex return behaviors, extending beyond normality assumptions. The empirical approach simulates real market data characteristics, while the t-distribution captures heavy tails, both together allowing comprehensive insights into potential risks over different horizons .
Simulation plays a significant role in estimating VaR and ES by generating a large sample of possible outcomes based on historical data or assumed distribution models. It allows for more flexible and potentially more accurate risk modeling compared to formula-based approaches, particularly when data exhibits non-normal characteristics. Simulations can capture complex return behaviors without the constraints of strict parametric assumptions, leading to values that closely approximate empirical observations as the sample size increases .
Modifying standard GARCH models is essential for non-normal financial return data because traditional models inadequately address features like heavy tails and skewness. Enhancements, such as incorporating a t-distribution or skewed distributions for errors, improve the model's robustness by capturing more complexity in the data. This leads to better predictions of extreme market risks reflected in more accurate VaR and ES estimates, which are crucial for effective risk management and decision-making in financial markets .
VaR is a risk metric that provides a measure of the maximum potential loss at a specified confidence level over a set time horizon, but it only indicates a threshold loss amount that might not be exceeded. ES, on the other hand, provides the expected loss given that the VaR threshold has been breached, offering insight into the average loss in the tail of the distribution. Hence, ES captures extreme risks better than VaR .
For the SanPan hedge fund, the calculated VaR and ES using simulation and different distribution models indicate differing risk levels. A lower VaR but higher ES from a student-t model compared to a normal distribution suggests a lower chance of hitting the risk threshold but a higher potential severity of loss if breached. This reflects a better accommodation of extreme loss scenarios, highlighting the importance of considering tail risks when assessing a hedge fund's potential vulnerabilities .
Assuming a normal distribution simplifies the calculation of VaR and ES, as it allows using direct equations based on the mean and standard deviation to determine quantiles and expected tail losses. However, such an assumption might not adequately capture extreme tail risks, which is a limitation as real-world returns, particularly in financial markets, often exhibit skewness and kurtosis beyond what a normal distribution accounts for .