0% found this document useful (0 votes)
73 views101 pages

Risk Management Techniques with R

The document is a practical guide on risk management using R, authored by Santanu Kumar Panigrahi, aimed at finance professionals and students. It covers essential concepts and methodologies for managing financial risk, including data retrieval, return calculations, and advanced techniques like GARCH and VaR estimation. The book emphasizes practical applications and integrates theoretical knowledge with real-world scenarios, making it a valuable resource for mastering risk management in today's financial landscape.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views101 pages

Risk Management Techniques with R

The document is a practical guide on risk management using R, authored by Santanu Kumar Panigrahi, aimed at finance professionals and students. It covers essential concepts and methodologies for managing financial risk, including data retrieval, return calculations, and advanced techniques like GARCH and VaR estimation. The book emphasizes practical applications and integrates theoretical knowledge with real-world scenarios, making it a valuable resource for mastering risk management in today's financial landscape.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Risk Management with R

A Practical Guide

Master the art of risk management with practical insights


and hands-on strategies using R
Risk Management with R
A Practical Guide

Santanu Kumar Panigrahi, CFA FRM FIII

2
PREFACE

In the ever-evolving landscape of finance and risk management, professionals are


increasingly required to harness sophisticated tools and methodologies to navigate the
complexities of modern markets. This book is designed to serve as a comprehensive
guide to various concepts, frameworks, and applications essential for managing
financial risk. Through a systematic exploration of key topics such as data retrieval,
return calculations, risk management under different distributions, volatility clustering,
and advanced techniques like GARCH and VaR estimation, this book aims to equip
readers with the knowledge and skills to tackle the challenges posed by an unpredictable
financial environment.

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

Topic 1: Introduction to R. ....................................................................................................... 6


Data Retrieval..................................................................................................................... 7
Return Calculations.......................................................................................................... 10
Risk Management Applications ......................................................................................... 15
Topic 2: Risk Management under Normal Distribution ............................................................ 17
Distribution of Returns ...................................................................................................... 17
Value at Risk (VaR) ............................................................................................................ 20
Expected Shortfall (ES) ..................................................................................................... 23
Using Simulation to estimate VaR & ES .............................................................................. 26
Topic 3: Risk Management under non-Normal Distribution..................................................... 32
Non-Normal Distributions................................................................................................. 32
Student-t Distribution ....................................................................................................... 36
Estimating Value at Risk (VaR) and Expected Shortfall ........................................................ 42
Topic 4: Risk Management under volatility clustering ............................................................. 50
Serial Correlation & Volatility Clustering ............................................................................ 50
GARCH ............................................................................................................................ 56
Enhancing the GARCH Model with a Rescaled t-Distribution .............................................. 63
VaR and Expected Shortfall for GARCH Bootstrap .............................................................. 69
Estimating Rolling VaR ...................................................................................................... 71
Topic 5: Gold: The Safe Heaven ............................................................................................. 75
Return Distribution ........................................................................................................... 75
VaR & Expected Shortfall................................................................................................... 76
Serial Correlation and Volatility Clustering......................................................................... 77
Topic 6: Fixed Income: The Conservative Investment ............................................................. 79
Return Distribution ........................................................................................................... 79
VaR & Expected Shortfall................................................................................................... 81
Serial Correlation and Volatility Clustering......................................................................... 82
Topic 7: Cryptocurrency: The Unpredictable Titan.................................................................. 84
Return Distribution ........................................................................................................... 86
VaR & Expected Shortfall................................................................................................... 89
Serial Correlation and Volatility Clustering......................................................................... 90
Appendix – Complete R code for Nifty 50 Analysis ................................................................. 92

4
5
Topic 1: Introduction to R.

R is a language and environment for statistical computing and graphics. R provides a


wide variety of statistical (linear and nonlinear modelling, classical statistical tests, time-
series analysis, classification, clustering) and graphical techniques, and is highly
extensible. One of R’s strengths is the ease with which well-designed publication-quality
plots can be produced, including mathematical symbols and formulae where needed.

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.

Key Points about Nifty 50:

• Base Year: 1995 (with a base value of 1000).


• Components: 50 large-cap stocks, representing approximately 65% of the free-
float market capitalization of the NSE.
• Sectors: It covers a wide range of sectors such as financial services, IT, consumer
goods, energy, auto, pharma and more.
• Market Representation: The Nifty 50 index is designed to reflect the performance
of companies with strong fundamentals and good liquidity, making it a
benchmark for the Indian equity market.
• Calculation: It is a free-float market capitalization-weighted index, meaning the
weight of each stock in the index is based on the stock's market value adjusted for
the portion of shares available for trading.

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

quantmod (Quantitative Financial Modelling Framework) is an R package designed for


financial modelling, trading, and quantitative analysis. It simplifies accessing financial
data, analysing it, and visualizing time series to help traders and analysts develop
models for various financial strategies. Here are some of the key features and
functionality of the quantmod package:

• 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.

# Install and load the quantmod package


[Link]("quantmod")
library(quantmod)

# Get historical stock data for Nifty 50 from Yahoo Finance


getSymbols("^NSEI", src = "yahoo")

# Plot a candlestick chart for the Nifty 50


chartSeries(NSEI)

7
# Add a 50D SMA, Bollinger Bands, MACD, RSI to the chart
addSMA(n = 50)
addBBands()
addMACD()
addRSI()

Process to retrieve Nifty 50 data

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.

# Install the quantmod package if you haven't already


[Link]("quantmod")

# Load the quantmod package


library(quantmod)

# Retrieve data from Yahoo Finance and store in the object “sec”
sec <- getSymbols("^NSEI", src = "yahoo")

# Remove missing values (NAs) from the data


sec <- [Link](sec)

# Filter data from the end of 2007 to the end of 2023


sec <- window(sec, start = [Link]("2007-12-31"), end =
[Link]("2023-12-31"))

# Display the first 3 rows of the data


head(sec, 3)

# Display the last 3 rows of the data


tail(sec, 3)

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.

Why to use log returns:

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:

𝑙𝑜𝑔𝑟𝑒𝑡(𝑡) = log(1 + 𝑟𝑒𝑡(𝑡))

Alternatively, the log return can be calculated directly from the index values:

𝑙𝑜𝑔𝑟𝑒𝑡(𝑡) = log(𝐼𝑛𝑑𝑒𝑥 𝑉𝑎𝑙𝑢𝑒 𝑎𝑡 𝐷𝑎𝑦 𝑡) − log(𝐼𝑛𝑑𝑒𝑥 𝑉𝑎𝑙𝑢𝑒 𝑎𝑡 𝐷𝑎𝑦 𝑡 − 1)

This transformation ensures that returns have no upper or lower bound and work
symmetrically for both gains and losses.

• Calculating Daily Returns in R:

Return calculations is a key metric in financial risk management. Returns measure


the percentage change in the value of the index from one day to the next. This can be
done using the dailyReturn() function in the quantmod package. The
dailyReturn() function computes the percentage change between consecutive
index values, providing a time series of daily returns. The data will serve as the
foundation for understanding portfolio risk, particularly for analysing the magnitude
of fluctuations and downside risks. By using daily returns, we can focus on short-term
market movements, which are crucial for effective risk management.

Calculating Log Returns:

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 daily returns


daily_returns <- dailyReturn(sec)

# Calculate log returns using log & diff and store in object “logret”
logret <- diff(log(sec$[Link]))[-1]

# Display the first three values of log returns


head(round(logret, 6), 3)

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.

Calculating Discrete Return from Log Return

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.

# Convert log return back to discrete return


discreteret <- exp(logret) - 1

# Display the first three values of discrete return


head(round(discreteret, 6), 3)

Plotting Log Returns

To visualize the daily log returns, we can create a simple plot in R:

# Plot the daily log returns


plot(logret, main="Daily Log Returns of the Nifty 50 Index",
ylab="Log Return", xlab="Date", col="blue", type="l")

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:

• Measure the percentage change in stock values (discrete return).


• Transform the return data for statistical symmetry and easier application of risk
management models (log return).
• Prepare the data for further risk analysis, such as calculating volatility, Value at
Risk (VaR), and other risk measures.

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.

Calculating long-term Returns

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:

• Using [Link]() to calculate weekly returns: In R, the [Link]()


function from the xts package allows us to compute weekly log returns by summing
daily log returns over a weekly period. The same principle applies to monthly,
quarterly, and yearly returns.

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)

# Calculate weekly log returns using [Link]


Logret_w <- [Link](logret, FUN = sum)

# Display the first 3 weekly returns (rounded to 6 decimal places)


head(round(logret_w, 6), 3)

# Convert weekly log returns to discrete returns


Discreteret_w <- exp(logret_w) - 1

# Display the first three weekly discrete returns (rounded to six


decimal places)
head(round(discreteret_w, 6), 3)

> head(round(logret_w, 6), 3) > head(round(discreteret_w, 6), 3)

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:

SanPan's Financial Structure:


• Invested Capital: $100 million of the hedge fund manager’s own capital.
• Borrowed Funds: $900 million loan from the bank (interest-free for simplicity).
• Total Portfolio: $1 billion invested entirely in a diversified portfolio of Indian
equities, such as the Nifty 50 Index.

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

Risk management under the assumption of a normal distribution involves using


statistical models to estimate and control potential risks by assuming that asset returns,
losses, or other financial variables follow a bell-shaped distribution. The distribution is
symmetric, meaning that most values cluster around the mean, with fewer values
occurring as we move away from the mean.
One of the most common applications in risk management is VaR. It calculates the
maximum expected loss over a given time period at a certain confidence level. For
normally distributed returns, VaR can be easily calculated using the mean and standard
deviation. We need to understand the distribution before going into the calculation of
VaR.

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.

Why the Normal Distribution?


The normal distribution, also known as the bell curve, is widely used in statistics for
several reasons:

• 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:

• Value-at-Risk (VaR): VaR is a measure of the potential loss in value of a portfolio


over a given time period, with a specified confidence level.
• Expected Shortfall (ES): ES is a measure of the expected loss in the worst-case
scenario beyond the VaR threshold.
Both VaR and ES are linked to the shape of the return distribution. If the returns are
normally distributed, then VaR and ES can be easily computed using explicit formulas.

17
However, when returns deviate from normality (e.g., fat tails, skewness), more complex
calculations are required.

The Standard Normal Distribution:


The standard normal distribution is a specific form of the normal distribution where:

• The mean (μ) is 0.


• The standard deviation (σ) is 1.
It is often denoted as ~N(0, 1). This is a shorthand notation where "N" refers to the normal
distribution, 0 is the mean, and 1 is the standard deviation. The symbol "~" in front of N
means "distributed as," so we say a variable is "distributed as N(0, 1)" to indicate it follows
a standard normal distribution.

General Normal Distribution:


To obtain a general normal distribution with any arbitrary mean (μ) and standard deviation
(σ), we transform a standard normal variable (ε) as follows:

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:

• mean(): To calculate the sample mean.


• sd(): To calculate the sample standard deviation.

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)

# claculate the standard deviation of log return and store in "sig"


sig<- round(sd(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:

• One day (daily VaR).


• One week (weekly VaR).
• Longer periods such as one month or one year, depending on the risk
management objectives.
In this example, we will focus on one-day VaR using daily returns data.

VaR Calculation with the Normal Distribution:


When calculating VaR under the assumption that portfolio returns follow a normal
distribution, the VaR can be computed based on the quantile of the normal distribution.
The process involves the following:

• 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.

Calculation: One-Day VaR for the Nifty 50 Index


Let’s calculate the one-day VaR at the 95% confidence level using the Nifty 50 Index daily
log returns.

• 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

# if portfolio exposure is USD 1000 million to Nifty 50


pf_VaR <- 1000* (exp(VaR)-1)

> pf_VaR
[1] -21.48112

Interpretation: VaR in dollar terms


If the 95% one-day VaR is −2.17%, this means the fund is at risk of losing up to 2.17% of
its value over one day with a 5% chance of exceeding this loss. In dollar terms:

Dollar VaR = (exp (-0.02171519) - 1) x 1,000,000,000 = $- 21.48 million.

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.

Key Insights and Applications of VaR:

• 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.

Relationship Between VaR and Expected Shortfall


Consider a scenario where we calculate a one-day VaR at a 95% confidence level, and
the VaR is -2.17%. This means there is a 5% chance that the loss will exceed 2.17% on a
given day. ES calculates the average loss for all returns worse than -2.17%. If the actual
outcome falls below this threshold, ES gives us the expected average loss.

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%.

Expected Shortfall for a Normal Distribution


In the context of a normal distribution, VaR and ES can be calculated using the probability
density function (PDF) and cumulative distribution function (CDF). The distribution has a
mean (denoted by μ) and a standard deviation (denoted by σ), which are typically
calculated from historical data such as the one-day returns of a stock index (e.g., the
Nifty 50 Index).

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.

Calculating Expected Loss


To arrive at the $26.9 million expected loss, we need to convert the ES from a percentage
to a discrete return. This is done using the following formula:

Expected Loss = (exp(Expected Shortfall)−1) × Total Investment

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

Then, we multiply this value by the total investment:

Expected Loss = −0.026944 x 1,000,000,000 = -26,944,000 (or about $26.9 million)

Thus, if the market performs worse than the VaR threshold, the hedge fund stands to lose
approximately $26.9 million on average.

#calculate the expected shortfall with distribution N(0,1)


es <- mu- sig *dnorm(qnorm(0.05,0,1),0,1)/0.05

#Display es
es

> es
[1] -0.02731365

# If portfolio exposure is USD 1000 million to Nifty 50


expected_loss <- (exp(es)-1) x 1,000,000,000

> 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

The expression “μ- σ *dnorm(qnorm(0.05,0,1),0,1)/0.05” is a formula used to


calculate the Expected Shortfall (ES) for a normal distribution.

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

Why Use Simulation for VaR and ES?


So far, we have relied on formulas to calculate Value at Risk (VaR) and Expected Shortfall
(ES), assuming that returns follow a normal distribution. These formulas work well under
such assumptions, but in the real world, financial returns often follow more complex or
non-normal distributions. In such cases, deriving exact formulas for VaR and ES becomes
challenging, and even, when possible, the formulas can get very complicated.

The simulation method offers a practical alternative for estimating VaR and ES when:

• The distribution of returns is not normal or is unknown.


• Formulas for VaR and ES either do not exist or are difficult to derive.
• We want to validate the accuracy of the formula-based VaR and ES by comparing
them with simulated estimates.

The Principle Behind Simulation


In statistics, we can estimate a quantile (like VaR) of a distribution by simulating data from
that distribution and taking the desired quantile from the simulated data. This works
because VaR is essentially a quantile of the return distribution. Therefore, by generating
a large number of random outcomes from the assumed distribution, we can estimate
both VaR and ES without relying on complicated formulas.

Simulating VaR for a Normal Distribution


Let’s consider an example where we want to calculate VaR at the 95% confidence level,
assuming that returns follow a normal distribution.

• 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.

# Set Alpha (significance level) for VaR


alpha <- 0.05

# Set seed for reproducibility


[Link](1234)

# Generate 100,000 random values from a normal distribution with mean


mu and standard deviation sig and store it in object “rvec”
rvec <- rnorm(100000, mean = mu, sd = sig)

# Estimate VaR as the 5th percentile (Alpha quantile)


VaR <- quantile(rvec, alpha)

# 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:

Approach Value at Risk (VaR) (95%) Expected Shortfall (ES)


Formula based -0.02171519 -0.02731365
Simulation Normal Dist. -0.02169300 -0.02714128

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.

Simulating from the Empirical Distribution of Returns


Now that we understand how to simulate from a normal distribution, let’s consider a
more realistic scenario. Instead of assuming normality, we can directly simulate from the
empirical distribution of historical returns.

Simulating from an empirical distribution of returns is a useful technique in finance,


especially for risk management (e.g., Value at Risk), portfolio optimization, or stress
testing. The idea is to model future returns based on past historical data without
assuming any parametric form (like normal distribution). This approach directly uses the
historical data for resampling. This method does not require any assumption about the
shape of the distribution, making it more flexible and often more accurate for real-world
data.

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.

Note on bootstrap method of simulation

The bootstrap method is a powerful statistical technique that allows us to estimate


the distribution of a statistic (e.g., mean, variance) by resampling with replacement
from the observed data. It can be particularly useful in simulation studies, where the
true underlying distribution may be unknown.

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 VaR as the 5th percentile of the sampled data


VaR_empirical <- quantile(rvec_empirical, alpha)

# 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.

Key Differences between the methods

By comparing the three methods (formula-based, simulation from a normal distribution,


and simulation from the empirical distribution), we observe the following:

• Formula-based and normal simulation: Both assume normality, and as a result,


they tend to underestimate extreme losses (VaR and ES) compared to the actual
empirical data.
• Simulation from empirical distribution: This method does not assume normality
and provides a more accurate estimate of VaR and ES based on the historical
behaviour of the returns.

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.

Approach Value at Risk (VaR) (95%) Expected Shortfall (ES)


Formula based -0.02171519 -0.02731365
Simulation Normal Dist. -0.02169300 -0.02714128
Simulation Empirical Dist. -0.01929073 -0.03259898

29
The simulation method for estimating VaR and Expected Shortfall is highly versatile and
powerful. It allows us to:

• Estimate these risk metrics for non-normal distributions where no closed-form


formulas exist.
• Validate the accuracy of formula-based calculations by comparing them with
simulated results.
• Use the empirical distribution of returns to capture real-world behaviour, including
fat tails and extreme events.

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

Deviation from Normality in Real-World Data

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.

Skewness and its financial implications

Skewness refers to the asymmetry of a distribution. When a distribution is skewed, one


tail is longer than the other. For a normal distribution Coefficient of skewness = 0.

• 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.

Kurtosis and heavy-tailed distributions

Kurtosis refers to the "tailedness" of a distribution:

• Leptokurtic distributions: These have "fat" tails, meaning there is a higher


probability of extreme outcomes (both positive and negative) compared to a normal
distribution. Coefficient of kurtosis >3
• Platykurtic distributions: These have thinner tails than a normal distribution and are
rare in finance. Coefficient of kurtosis < 3

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.

Calculating Skewness and Kurtosis with R

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.

# Install the moments package


[Link]("moments")

# Load the moments package


library(moments)

#calculate the coefficient of skewness of log return of Nifty 50


rvec <- [Link](logret)
round(skewness(rvec),3)

> 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

In the case of the Nifty 50 Index:

• 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.

Formal Tests for Normality: The Jarque-Bera Test

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.

#testing normality with jarque bera test


> [Link](rvec)

> [Link](rvec)

Jarque-Bera Normality Test

data: rvec
JB = 37961, p-value < 2.2e-16
alternative hypothesis: greater

Implications for VaR and Expected Shortfall

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.

Jarque-Bera Test Hypotheses:


• Null Hypothesis (H0): The data follows a normal distribution (i.e., skewness and
kurtosis match those of a normal distribution).
• Alternative Hypothesis (H1): The data does not follow a normal distribution (i.e.,
the skewness or kurtosis deviate from normality).

This statistic follows a chi-square distribution with 2 degrees of freedom. The


corresponding p-value determines whether the null hypothesis can be rejected.

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:

o The skewness is significantly different from 0 (normal data has skewness


= 0), meaning the distribution is either left-skewed or right-skewed.
o The kurtosis is significantly different from 3 (normal distribution kurtosis is
3), indicating either too many or too few extreme values (i.e., heavier or
lighter tails than normal).

In summary, if the p-value is 0, it indicates the data is highly non-normal, either in terms
of skewness, kurtosis, or both.

Visualizing Non-Normality: Q-Q Plots and Histograms

Other common methods to test for normality include:


• Q-Q plots: These compare the quantiles of the actual data to those of a normal
distribution. If the data are normally distributed, the points should lie along a 45-
degree line.
• Kolmogorov-Smirnov test: This compares the empirical distribution function of the
sample with the cumulative distribution function of the assumed distribution (in this
case, normal).

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.

Understanding the Student-t Distribution

The student-t distribution is a probability distribution that is similar to the normal


distribution but has heavier tails. This means it can better model data where extreme
values (outliers) occur more frequently than they would in a normal distribution.

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.

In comparison, the standard normal distribution has a mean of 0, a variance of 1, a


skewness of 0, and a kurtosis of 3. The key difference between the two distributions lies
in their kurtosis, where the student-t distribution has heavier tails (higher kurtosis),
making it more suitable for financial data like log returns, which often exhibit fat tails.

Connection Between Student-t and Normal Distributions

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:

• For ν = 10, the distribution is still fairly close to normal.


• For ν = 5, the tails become noticeably heavier.
• For ν = 3, the tails are much heavier, reflecting a higher kurtosis.

In summary, the student-t distribution provides a useful alternative to the normal


distribution when modelling financial data with heavier tails. By introducing a scaling
parameter to the standard student-t distribution, we can match both the standard
deviation and the kurtosis of the log returns of the Nifty 50 index. This approach allows us
to more accurately estimate risk measures such as Value at Risk (VaR) and Expected
Shortfall (ES), which are sensitive to the tail behaviour of the distribution.

Matching Kurtosis of the Data

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.

To address this, we can modify the standard student-t distribution by introducing a


scaling parameter. This leads to what is known as the rescaled student-t distribution.

37
Rescaled Student-t Distribution

To construct a rescaled student-t distribution, we follow these steps:

• 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.

Rescaled Student-t Model Assumptions

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:

• μ\mu is the mean of the log return,


• σ\sigma is the standard deviation or scaling parameter,
• ϵ\epsilon is a random variable following a rescaled Student-t distribution with ν\nu
degrees of freedom.

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.

Maximum Likelihood Estimation (MLE)

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:

• Install and load the MASS package.


• Store the log returns in a vector.
• Use the fitdistr function, specifying the student-t distribution.

The function returns an estimate for:

• μ\mu (mean),
• σ\sigma (scaling parameter or standard deviation),
• ν\nu (degrees of freedom).

#install and load MASS package


[Link](MASS)
library(MASS)

#fitting the logret to t distribution


rvec <- [Link](logret)
[Link] <- fitdistr(rvec, "t")

#Display three parameters of the rescaled t-distribution


round([Link]$estimate,6)

> round([Link]$estimate,6)
m s df
0.000654 0.007961 2.886109

Fitting the Rescaled Student-t Model

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.

Comparing the Student-t Distribution to the Normal Distribution

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")

#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)

#Plot fitted t-distribution of Nifty 50 log returns


# Fit t-distribution to the log returns
fit <- fitdistr([Link](logret), "t", start=list(m=mean(logret),
s=sd(logret), df=3))

# Extract fitted parameters


mu_fitted <- fit$estimate["m"]
sigma_fitted <- fit$estimate["s"]
df_fitted <- fit$estimate["df"]

# Add the fitted t-distribution density line


x <- seq(min(logret), max(logret), length=4000)

# Density of the fitted t-distribution


lines(x, dt((x - mu_fitted) / sigma_fitted, df=df_fitted) /
sigma_fitted, col="red", lwd=2)

# 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:

• Install and load metRology package.


• Simulate 100,000 outcomes from the rescaled student-t distribution using the
estimated parameters.
• Estimate the VaR as the alpha quantile (e.g., the 5th percentile for 95% confidence
level) of the simulated data.
• Estimate the ES as the average of outcomes worse than the estimated VaR.

#install and load metRology package


[Link](metRology)
library(metRology)

# Set Alpha (significance level) for VaR


alpha <- 0.05

# Set seed for reproducibility


[Link](1234)

# Generate 100,000 random values from the rescaled t-distribution with


3 paramenters (mu, sd and df)
rvec <- [Link](100000,mean=[Link]$estimate[1],sd=[Link]$estimate[2],
df=[Link]$estimate[3])

# Estimate VaR as the 5th percentile (Alpha quantile)


VaR <- quantile(rvec,alpha)

# 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

The results show: VaR = -1.847% and Expected Shortfall = -3.126%

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

• Has $100 million in capital,


• Borrows $900 million from a bank,
• Invests the total $1 billion in a diversified stock portfolio similar to the Nifty 50 index.

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 VaR for the hedge fund is approximately -18.47 million.


• The Expected Shortfall is approximately -31.25 million.

Approach Value at Risk (VaR) (95%) Expected Shortfall (ES)


Formula based -0.02171519 -0.02731365
Simulation Normal Dist. -0.02169300 -0.02714128
Simulation Empirical Dist. -0.01929073 -0.03259898
Student-t Model -0.01846782 -0.03125972

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.

Estimating VaR and ES for multi-day horizon

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:

• Method A: Simulating from a t-distribution based on estimated parameters.


• Method B: Simulating from the empirical distribution using IID (independent and
identically distributed) draws.
• Method C: Simulating from the empirical distribution using block draws.

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

In Method A, we simulate returns by drawing from an estimated t-distribution. Previously,


we used this approach to simulate one-day returns. The t-distribution is characterized by
three parameters: location, scale, and degrees of freedom, which have already been
estimated for the one-day log returns of the Nifty 50 Index. For a ten-day holding period,
the approach involves summing up ten simulated one-day returns.

Steps for Method A:

• Generate 100,000 one-day returns from the t-distribution.


• Loop through the simulation ten times to generate ten consecutive one-day returns
for each of the 100,000 simulations.
• Sum the ten one-day log returns to produce a ten-day log return for each simulation.
• Calculate VaR and ES: After obtaining 100,000 ten-day returns, the VaR at the 95%
confidence level is the 5th percentile of these returns, and the ES is the average of the
returns below the VaR threshold.
# Method A
# Set Alpha (significance level) for VaR
alpha <- 0.05

# Set seed for reproducibility


[Link](1234)

# Initialize a vector for the 100,000 simulated ten-day returns


rvec <- rep(0, 100000)

# 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])
}

# Calculate 5th percentile for VaR


VaR <- quantile(rvec, 0.05)

# Calculate expected shortfall


ES <- mean(rvec [rvec < VaR])

# Dispalay VaR and ES


VaR
ES

> 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).

Steps for Method B:

• 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

# Set seed for reproducibility


[Link](1234)

# Initialize a vector for the 100,000 simulated ten-day returns


rvec <- rep(0, 100000)

# 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)
}

# Calculate 5th percentile for VaR


VaR <- quantile(rvec, 0.05)

# Calculate expected shortfall


ES <- mean(rvec [rvec < VaR])

# Dispalay VaR and ES


VaR
ES

> 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.

Steps for Method C:

• Randomly select 100,000 starting points from the empirical data.


• For each simulation, take ten consecutive one-day returns starting from the randomly
chosen position in the historical data.
• Sum the ten consecutive one-day log returns to obtain a ten-day log return for each
simulation.
• Calculate VaR and ES as before.
# Method C
# Set Alpha (significance level) for VaR
alpha <- 0.05

# Set seed for reproducibility


[Link](1234)

# Initialize a vector for the 100,000 simulated ten-day returns


rvec <- rep(0, 100000)

# Actual one-day log returns


RDAT <- [Link] (logret)

# Valid starting positions for 10-day blocks


POSN <- 1:(length(RDAT) - 9)

# Randomly sample starting positions


RPOS <- sample(POSN, 100000, replace=TRUE)

# Add the returns for 10 consecutive days


for (i in 0:9) {
rvec <- rvec + RDAT[RPOS + i]
}

# Calculate 5th percentile for VaR


VaR <- quantile(rvec, 0.05)

# Calculate expected shortfall


ES <- mean(rvec [rvec < VaR])

# Dispalay VaR and ES


VaR
ES

> 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 VaR (95%) Expected Shortfall


A (t-distribution) -6.26% -9.28%
B (IID from empirical) -6.54% -9.08%
C (Block draws) -6.26% -10.63%

• 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

1. Setting the Significance Level


This sets the significance level (denoted by alpha) at 5%. For VaR calculations, this
represents the probability of returns falling below a certain threshold.

2. Setting a Seed for Reproducibility


This ensures that the results are reproducible. By setting a seed, every time we run the
simulation, the same random numbers will be generated, leading to the same results.

3. Initializing a Vector for Simulated Returns


This creates a vector of length 100,000 initialized with zeros. Each element will eventually
hold the sum of returns over ten consecutive days from the historical return data.

4. One-Day Log Returns


This converts the one-day log returns (denoted as logret) into a simple vector RDAT. These
are the actual historical log returns that will be used to construct the simulated ten-day
returns.

5. Identifying Valid Starting Positions for 10-Day Blocks


This creates a vector POSN of all valid starting positions for a 10-day block of returns. Since
we sum 10 consecutive days, the last possible starting position is at length(RDAT) - 9.

6. Randomly Sampling Starting Positions


This randomly selects 100,000 starting positions from the POSN vector, allowing repetition
(replace=TRUE). These will be the starting points for each of the simulated 10-day return
blocks.

7. Calculating Simulated Ten-Day Returns


This loop sums 10 consecutive daily returns for each starting position in RPOS. For every
iteration i (from 0 to 9), it adds the corresponding day’s return to rvec, thus building up the
10-day return for each of the 100,000 samples.

8. Calculating the 5th Percentile (VaR)


This calculates the 5th percentile of the simulated 10-day returns stored in rvec. The VaR at
5% significance level (or confidence level of 95%) is the return threshold.

9. Calculating the Expected Shortfall (ES)


This calculates the Expected Shortfall (ES), which is the average of the returns that fall
below the VaR threshold. ES is considered a more coherent risk measure than VaR because
it takes into account the magnitude of the losses beyond the VaR threshold.

10. Displaying VaR and ES


Finally, the calculated VaR and ES values are displayed.

48
49
Topic 4: Risk Management under volatility clustering

Serial Correlation & 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.

1. Assumption 1: Historical Distribution as a Proxy for Future Returns


• We assume that the future distribution of the log returns of the Nifty 50 index will
resemble its historical distribution.
• Through analysis, we’ve observed that the historical distribution of returns is not
normally distributed but better approximated by a t-distribution.
• We've used this t-distribution to estimate Value at Risk (VaR) and ES and also used
the empirical historical distribution as we have around 4,000 data points.
• The assumption that historical distributions will mirror future distributions may not
always hold. Market dynamics could change, and new, unforeseen events can
influence future returns. This assumption, though plausible in some cases, cannot
guarantee accuracy for all time periods.

2. Assumption 2: Ignoring the Ordering of Data


• When we estimate the parameters of a distribution (such as the mean and standard
deviation for a normal distribution or the parameters of the t-distribution), we ignore
the time-ordering of the returns.
• This means that whether we permute the sequence of log returns or leave them as is,
the statistical estimates like the mean, standard deviation, and the parameters of the
t-distribution remain unchanged.
• Reasoning for the above point is that statistical functions used for parameter
estimation (e.g., fitdistr() in R) are indifferent to the order of the data, focusing only
on the distribution’s shape and 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.

Testing the Assumption: Serial Correlation


Serial correlation measures how much a variable correlates with its own past values. For
financial markets, serial correlation has been extensively studied to check whether stock
returns show patterns that could contradict market efficiency.

• 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).

Autocorrelation Function (ACF) and Testing for Serial Correlation


To test for serial correlation in our data, we use the autocorrelation function (ACF). The
ACF calculates the correlation between returns & their lagged values for different lags j.

• If the autocorrelation coefficients (ρj ) fall outside of a 95% confidence interval


(usually represented by dashed lines in an ACF plot by using R), this indicates
significant serial correlation. Otherwise, if the coefficients mostly fall within the
confidence bands, we do not have strong evidence of serial correlation.
• The R function acf()generates a plot of the autocorrelation coefficients for various
lags. In the case of the Nifty 50 index, plotting up to 40 lags shows that most
autocorrelation coefficients are within the confidence bands, suggesting little to no
serial correlation.

#checking for autocorrelation


acf(logret)

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.

Evidence of Volatility Clustering


To investigate whether volatility clustering exists in financial time series data, we can
analyse the autocorrelation function (ACF) of the absolute values of the returns. This
method is similar to how we test for serial correlation in raw returns but uses the absolute
values to focus on the magnitude of changes, not their direction.

1. Original Series of Log Returns:


• Let xt represent the daily log returns of the Nifty 50 index.
• We first calculate the autocorrelation function (ACF) for this series to check for
any correlation between returns across different time lags.
• In most cases, the ACF of raw returns shows little or no serial correlation, as was
the case for the Nifty 50 index, meaning that past returns do not predict future
returns.

2. Absolute Values of Log Returns:


• Next, we take the absolute values of the log returns ∣xt∣ to examine the volatility,
i.e., the magnitude of price changes without considering their direction (positive
or negative).
• We then calculate the ACF of these absolute values to check for any
autocorrelation.
• The resulting ACF plot typically shows positive autocorrelation coefficients that
are outside the 95% confidence bands, indicating significant serial dependence
in the volatility.

#checking for volatility clustering


acf(abs(logret))

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.

Demonstration of the Importance of Data Ordering


To further illustrate the significance of volatility clustering, we can perform an experiment
where we randomly permute (shuffle) the order of the log return data and compare the
results to the original data.
In the original series, the ACF of the absolute values of log returns shows significant
autocorrelation, indicating that volatility clustering is present. When the ordering of the
returns is shuffled (like shuffling a deck of cards), the ACF plot of the absolute values
shows no significant autocorrelation. The autocorrelation coefficients are close to zero,
meaning that the volatility clustering has disappeared.
This experiment clearly demonstrates that the order of the data matters, and when we
disrupt this order, the volatility pattern is lost.

Implications of Volatility Clustering in Risk Management


The phenomenon of volatility clustering shows that market volatility is not random but
tends to occur in bursts. This insight is crucial for risk management because periods of
high volatility are often associated with increased financial risk. The following are key
takeaways:

• Predictability of Volatility: Unlike returns, which typically follow a random walk,


volatility exhibits patterns that can be modelled and predicted. The presence of
volatility clustering suggests that during times of high volatility, markets are more
likely to remain volatile for some time.

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 GARCH (Generalized Autoregressive Conditional Heteroskedasticity) model is


commonly used in financial econometrics to model time series data with changing
volatility over time. Specifically, the GARCH (1,1) model is one of the simplest and most
widely used forms of the model. It captures the time-varying volatility and assumes that
the variance of the error term is conditional on past error terms and past variances.
GARCH (1,1) refers to the order of the model, indicating the number of lagged terms used
for both the error (or innovation) and the conditional variance components.

• 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.

So, in a GARCH (1,1) model:


• The squared residual from the previous time step ϵ2t−1 is used to model how current
volatility might be affected by past shocks.
• The previous period's variance σ2t−1 is also used to model the persistence of volatility
over time.

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.

Structure of the GARCH (1,1) Model


The GARCH (1,1) model consists of three main equations:

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.

Volatility Clustering and Time-Varying Variance


The key to understanding the GARCH (1,1) model lies in its variance equation. As
mentioned earlier, financial data often exhibit volatility clustering, where periods of high
volatility are followed by more high volatility and vice versa. The GARCH model explains
this phenomenon in terms of the impact of past shocks and past variance on current
variance.

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.

The GARCH Model and the Constant Variance Model


Interestingly, the GARCH model encompasses the constant variance model (which
assumes no time-varying volatility) as a special case. If both α1 and β1 are set to 0, the
variance equation simplifies to ht = α0, which is a constant. This is essentially the same
as assuming constant volatility in returns, which was the basis of the earlier models of
returns.

In this case, the model reduces to: rt =a0 + σ ⋅ ϵt


where σ is the constant standard deviation of returns.

Numerical Example of GARCH (1,1)

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:

• Mean Equation: This defines the average return of the series.


• Variance Equation: This models the time-varying volatility of returns.
• Distribution Equation: This specifies the distribution of errors (typically assumed
to be normal).

Implementing GARCH (1,1) in R


Here, we will walk through the steps for specifying, estimating, and diagnosing a GARCH
(1,1) model using the rugarch package in R.

• Installing and loading the rugarch Package


Before estimating the GARCH model, ensure that we have the rugarch package
installed and loaded in R.
#Install and load rugarch Package
[Link]("rugarch")
library(rugarch)

• Specifying the GARCH Model


The function ugarchspec() is used to define the GARCH model. We need to specify
the mean equation, variance equation, and distribution type.
# Specify the GARCH(1,1) model
uspec <- ugarchspec([Link] = list(model = "sGARCH",garchOrder
= c(1,1)),
[Link] = list(armaOrder = c(0,0), [Link] = TRUE),
[Link] = "norm")

Here:

• [Link] = list("sGARCH", garchOrder = c(1, 1)) specifies that we


are using a GARCH(1,1) model.
• [Link] = list(armaOrder = c(0, 0)) specifies that the mean is modelled
as a constant.
• [Link] = "norm" specifies that the error terms follow a normal
distribution.

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.

# Fit the GARCH model to the log return data


[Link] <- ugarchfit(spec = uspec, data = logret[,1])

The ugarchfit() function estimates the parameters of the model using maximum
likelihood estimation (MLE). The arguments are:

• spec: The GARCH specification object created earlier.


• data: The log return data.

The estimated parameters are in [Link]@fit$coef

• Viewing the Model Output

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).

# View the fitted GARCH model results


print([Link])

*---------------------------------*
* GARCH Model Fit *
*---------------------------------*

Conditional Variance Dynamics


-----------------------------------
GARCH Model : sGARCH(1,1)
Mean Model : ARFIMA(0,0,0)
Distribution : norm

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

This will display the following parameters:

• Mu (μ): The mean return.


• Omega (ω): The constant in the variance equation.
• Alpha1 (α1): The coefficient for the past squared error term ϵ2t−1.
• Beta1 (β1): The coefficient for the past variance σ2t−1.
• Saving and Extracting Results

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.

# Save fitted values for analysis


save1 <- cbind(logret[,1], [Link]@fit$sigma, [Link]@fit$z )
names(save1) <- c("D", "logret", "s", "z")

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.

# Display summary statistic of z (residual term)


library(moments)
mean(save1$z)
sd(save1$z)
skewness(save1$z)
kurtosis(save1$z)

> mean(save1$z)
[1] -0.04360572
> sd(save1$z)
[1] 0.9998905
> skewness(save1$z)
[1] -0.2088387
> kurtosis(save1$z)
[1] 5.111375

A formal Jarque-Bera test can also be used to test for normality.

# jarque bera test for normality of z (residual term)


[Link]([Link](save1$z))

>Jarque-Bera Normality Test

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.

# testing for z (residual term) for SC & VC


acf(save1$z) # Check for serial correlation (SC)
acf(abs(save1$z)) # Check for volatility clustering (VC)

Serial Correlation Volatility Clustering

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.

By using a rescaled t-distribution, we improve the model’s ability to handle extreme


events and, in turn, obtain more accurate risk measures like VaR and ES. This also
provides a more robust model for predicting future volatility and extreme market
movements.

The Rescaled t-Distribution

As discussed in the previous sections, the rescaled t-distribution introduces a degree of


freedom parameter ν\nu, which controls the heaviness of the tails. As ν\nu increases, the
distribution becomes closer to normal, but for small values of ν\nu, the tails are much
heavier than in the normal distribution. In mathematical terms, the variance of a t-
distribution with ν\nu degrees of freedom is given by: Var(tν) = ν/ν−2

The rescaled t-distribution divides the t-distribution by its standard deviation to


normalize it, making it comparable to the standard normal distribution but with heavier
tails. We will modify the GARCH specification by changing the distribution from normal
to a rescaled t-distribution, with the following steps.

• Specifying the GARCH Model with a Rescaled t-Distribution

The function ugarchspec() is still used, but we change the [Link]


argument to "std" (which stands for a rescaled t-distribution).

# Specify the GARCH(1,1) model with a rescaled t-distribution


garch.t <- ugarchspec([Link] = list(model =
"sGARCH",garchOrder = c(1,1)), [Link] = list(armaOrder = c(0,0),
[Link] = TRUE), [Link] = "std")

63
Here:

• [Link] = list(garchOrder = c(1, 1)) defines the GARCH(1,1)


structure.
• [Link] = list(armaOrder = c(0, 0)) indicates that the mean is modelled
as a constant.
• [Link] = "std" tells R to use the rescaled t-distribution instead of
the normal distribution.

• Fitting the GARCH Model

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)

• Viewing the Model Output

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.

# Print the fitted GARCH model results


print([Link].t)

*---------------------------------*
* GARCH Model Fit *
*---------------------------------*

Conditional Variance Dynamics


-----------------------------------
GARCH Model : sGARCH(1,1)
Mean Model : ARFIMA(0,0,0)
Distribution : std

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

The output includes five parameters:

• Mu (μ): The mean return (from the mean equation).


• Omega (ω): The constant in the variance equation.
• Alpha1 (α1): The coefficient for the past squared error term ϵ2t−1
• Beta1 (β1): The coefficient for the past variance σ2t−1.

64
• Shape (ν): The degrees of freedom for the rescaled t-distribution. Lower values of
ν\nu indicate heavier tails.

• Saving the Results

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.

# Save fitted values and parameters for analysis


save1 <- cbind(logret[,1], [Link].t@fit$sigma, [Link].t@fit$z )
names(save1) <- c(‘logret’, ‘s’, ‘z’ )

# Save estimated parameters


parm1 <- coef([Link].t)

> head(parm1)
mu omega alpha1 beta1 shape
7.740919e-04 1.473945e-06 7.967245e-02 9.106665e-01 7.645170e+00

Diagnostics for GARCH Model with t-Distributed Errors

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:

• Mean: Should be approximately 0.


• Standard Deviation: Should be 1.
• Skewness: Should be close to 0, indicating no skewness (i.e., the distribution is
symmetric).
• Kurtosis: The kurtosis should be higher than in a normal distribution due to the t-
distribution. Specifically, the kurtosis is given by: Kurtosis=3 + 6/ν−4

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

• Mean: Close to 0, as expected.


• Standard Deviation: Close to 1, aligning with the model specification.
• Skewness: The residuals show negative skewness, indicating that the distribution
of returns is left-skewed.
• Kurtosis: The kurtosis exceeds 3, as anticipated from the t-distribution, and is
close to the theoretical value of 4.64.

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.

• Autocorrelation Diagnostic Tests

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.

# Check for serial correlation


acf(save1$z)

# Check for volatility clustering


acf(abs(save1$z))

Serial Correlation Volatility Clustering

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:

• No significant autocorrelation, suggesting that the GARCH (1,1) model has


successfully captured the time-varying volatility structure, and no patterns remain
in the residuals.
• No significant autocorrelation in absolute residuals, meaning that the model has
explained the volatility clustering effectively.

• Explaining Volatility and Kurtosis

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.

• Fitted Volatility Analysis

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.

• GARCH model and setup

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.

#We use the R function “ugarchboot” to simulate 1-day outcomes:


[Link](1234) #set seed value
[Link] <-
ugarchboot([Link], # ignore parameter uncertainty
method=c("Partial","Full")[1], # draw from standardized
sampling="raw", residuals
[Link]=1, # 1-day ahead
[Link]=100000, # number of simulated outcomes
solver="solnp”)

#The simulated outcomes are then saved in the vector “rvec”:


rvec <- [Link]@fseries

#Display VaR and ES


VaR
ES

> VaR
5%
-0.01236714
> ES
[1] -0.01699853

• Simulating future returns with ugarchboot

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.

# Compare calculations of all approaches


# Tabulate results
results <- [Link](
Method = c("Formula based", "Simulation Normal Distribution",
"Simulation Empirical Distribution", "Fitted T-Distribution", "GARCH
(1,1)"),
Value_at_Risk = c(var, VaR, VaR_empirical, VaR_t, VaR_garch),
Expected_Shortfall = c(es, ES, ES_empirical, ES_t, ES_garch)
)

# 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.

Setting Up the GARCH Model and Preparing Data

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.

• Using the ugarchroll Function: The ugarchroll function is designed to perform


rolling forecasts by re-estimating the GARCH model iteratively. The rolling process
involves recalculating VaR for each day by expanding the estimation window and
refitting the model. Here's how the key arguments of the function are set up:

#Estimating Rolling 1-day VaR


#Step 1: Identify the index for the last day of 2022
n2023 <- length(logret["2008-01-01/2022-12-31"])

# Step 2: Specify the GARCH model with Student-t errors


garch.t <- ugarchspec([Link] = list(model =
"sGARCH",garchOrder = c(1,1)), [Link] = list(armaOrder = c(0,0),
[Link] = TRUE), [Link] = "std")

# 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
var_rolling <- [Link]([Link]@forecast$VaR)
head(var_rolling)

# Step 5: Visualize the results


plot([Link], which = 4)

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:

# Plot the first series (5% VaR) with red color


plot(var_rolling$`alpha(5%)`, type = "l", col = "red", lwd =1,
xlab = "Jan-23 to Dec-23", ylab = "Value", main = "Rolling VaR
and Log Returns",
ylim = range(c(var_rolling$`alpha(5%)`, logret["2023-01-01/2023-
12-31"])))

# Overlay the second series (log returns) with blue color


[Link](logret["2023-01-01/2023-12-31"], col = "blue", lwd =1)

legend("top", legend= c("Logret", "VaR"),


col=c("blue", "red"), lwd=1, bty = "n", bg = "transparent")

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%.

Model Accuracy and Interpretation

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.

Statistics Nifty 50 Gold


mu 0.00032249 0.00027548
sigma 0.01339796 0.01112588
skewness -0.311 -0.245
kurtosis 18.232 8.708

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.

Serial Correlation and Volatility Clustering

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.

Gold’s Statistical Properties

• 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.

Access to Bloomberg requires appropriate permissions or licenses, depending on the


financial institution or Bloomberg account setup. Data of this index can be fetched in R,
only with appropriate Bloomberg license. Data from Bloomberg can be retrieved through
the R package “Rblpapi”. Once we have the data of LEGATRUU index, we can calculate
the log returns in a similar way as discussed previously.

#Installing package and connecting to Bloomberg for data


[Link] (Rblpapi)
library(Rblpapi)
blpConnect() #Connect to Bloomberg (Make sure Bloomberg is open)

# Retrive data from Bloomberg


sec <- bdh("LEGATRUU Index", "PX_LAST", [Link] = [Link]("2007-
01-01"), [Link] = [Link]("2024-10-31"))
names(sec) <- c("Date", "Close")

#Convert the retrived data to an xts object


library(xts)
sec <- [Link](sec$Close , [Link] = [Link](sec$Date))
colnames(sec) <- "Close"

The standard statistical summary of Nifty 50, Gold and FI Index is given below.

Statistics Nifty 50 Gold LEGATRUU


mu 0.00032249 0.00027548 0.00007863
sigma 0.01339796 0.01112588 0.00333742
skewness -0.311 -0.245 0.0556
kurtosis 18.232 8.708 7.628

79
The log return plot of LEGATRUU:

For these assets, it can be summarised as

• 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.

Nifty 50 Gold LEGATRUU


Approach
VaR - 95% ES VaR - 95% ES VaR - 95% ES
Student-t Model -0.01847 -0.03126 -0.01602 -0.02188 -0.00534 -0.00702

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.

Serial Correlation and Volatility Clustering

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

Cryptocurrency is a digital or virtual currency that uses cryptography for security,


enabling secure and decentralized financial transactions. Unlike traditional currencies,
cryptocurrencies are typically not issued by any central authority, making them immune
to government interference or manipulation. Cryptocurrencies are digital assets
designed to work as a medium of exchange using blockchain technology, where
individual coin ownership records are stored in a distributed ledger.

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?

• Bitcoin is a decentralized digital currency that operates without a central authority or


government. Instead, it relies on a peer-to-peer network and blockchain technology.
• The blockchain is a public ledger where all Bitcoin transactions are recorded, making
it transparent and secure. Each transaction is verified by network nodes (computers
running the Bitcoin software) through cryptography.

How does Bitcoin work?

• Transactions: Bitcoin transactions involve sending or receiving Bitcoin between


wallets, which are secured with private and public keys. Transactions are added to
blocks, which are then added to the blockchain.
• Mining: Bitcoin uses a Proof of Work (PoW) mechanism where miners (network
participants) solve complex cryptographic puzzles to validate transactions and add
new blocks to the blockchain. This process is energy-intensive, but it secures the
network and controls the release of new Bitcoin.
• Bitcoin has a capped supply of 21 million coins. This limit, set in its code, ensures that
no more than 21 million Bitcoin will ever exist, making it a scarce asset. The rate at
which new Bitcoin is created is halved roughly every four years in an event known as
the halving.

Why do people use Bitcoin?

• Decentralization: Since it’s decentralized, Bitcoin operates independently of


traditional banking systems or government control.
• Store of Value: Some view Bitcoin as "digital gold" due to its capped supply, seeing it
as a hedge against inflation and a store of value.
• Global Transactions: Bitcoin enables fast and low-cost cross-border payments
without intermediaries, which can be helpful in areas where traditional banking is
limited.

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.

Risks and considerations

• Volatility: Bitcoin's price can fluctuate wildly, making it a high-risk asset.


• Security: Although the blockchain itself is secure, individual wallets are not immune
to hacks or theft if security protocols aren’t followed.
• Regulatory Concerns: Some governments are exploring regulations for Bitcoin and
other cryptocurrencies, which could impact their usage and acceptance.

Bitcoin's impact and future

• 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.

Statistics Nifty 50 Gold LEGATRUU Bitcoin


mu 0.00032249 0.00027548 0.00007863 0.00149164
sigma 0.01339796 0.01112588 0.00333742 0.03738866
skewness -0.311 -0.245 0.0556 -0.794
kurtosis 18.232 8.708 7.628 14.604

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:

Mean Return (μ\mu)


• Nifty 50 indicates an average daily return of 0.032%. This is relatively low but is
expected for a diversified stock index.
• Gold gives an average daily return of 0.027%. Gold’s return is similar to Nifty 50,
reflecting its role as a stable asset.
• LEGATRUU gives an average daily return of nearly 0.007%.
• Bitcoin suggests a much higher average daily return of 0.15%, indicating Bitcoin’s
potential for higher returns compared to traditional assets.
• Interpretation: Bitcoin has a notably higher daily return than Nifty 50 and Gold,
indicating its strong growth potential but potentially higher risk.

Standard Deviation (σ\sigma)


• Nifty 50's daily returns have moderate volatility. This level of risk is typical for a stock
index.
• Gold is slightly lower than Nifty 50, indicating that Gold has lower daily volatility and
acts as a safe haven.
• LEGATRUU has the lowest volatility, indicating it to be relatively safest.
• Bitcoin has a high standard deviation, indicating that Bitcoin is much more volatile
than both Nifty 50 and Gold. Its price can fluctuate significantly on a daily basis.
• Interpretation: Bitcoin's high standard deviation shows it is a much riskier asset, while
LEGATRUU has the lowest volatility, aligning with its traditional stability.

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.

We can summarize that

• 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.

Nifty 50 Gold LEGATRUU Bitcoin


Approach
VaR-95% ES VaR-95% ES VaR-95% ES VaR-95% ES
Formula
-0.02171 -0.02731 -0.01802 -0.02267 -0.00541 -0.00681 -0.06001 -0.07563
based
Simulation
Normal -0.02169 -0.02714 -0.01801 -0.02253 -0.00541 -0.00676 -0.05994 -0.07515
Dist.
Simulation
Empirical -0.01929 -0.03260 -0.01790 -0.02664 -0.00533 -0.00751 -0.05908 -0.09257
Dist.
Student-t
-0.01847 -0.03126 -0.01602 -0.02188 -0.00534 -0.00702 -0.05202 -0.1056
Model

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.

Serial Correlation and Volatility Clustering

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.

Bitcoin’s Statistical Properties

• Normality: Bitcoin’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 and Gold, Bitcoin
shows no serial correlation (no predictive pattern in returns), but large price changes
tend to cluster, indicating 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)

# Removing data not available


sec_N <- [Link](sec)

# Filtering data from 01-01-2008


sec <- window(sec_N, start = [Link]("2007-12-31"), end = [Link]())

#displaying top 3 rows of data


head(sec,3)

#displaying bottom 3 rows of data


tail(sec,3)

#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]

#display top 3 rows of the return upto 6 decimals


round(head(logret,3),6)

#convert the log return to discrete return


discreteret <- exp(logret)-1

#display top 3 rows of the discrete return upto 6 decimals


round(head(discreteret,3),6)

#plot the log return of Nifty 50


plot(logret, main="Daily Log Returns of the Nifty 50 Index", ylab="Log
Return", xlab="Date", col="blue", type="l")

#Calculate weekly return and store it in object "logret.w"


logret_w <- [Link](logret,FUN = sum)

#display top 3 rows of the weekly log return upto 6 decimals


head(round(logret_w, 6), 3)

#convert the weekly log return to weekly discrete return


discreteret_w <- exp(logret_w) -1

#display top 3 rows of the discrete weekly return upto 6 decimals

92
head(round(discreteret_w, 6), 3)

#Topic 2: Risk Management in Normal Distribution


# claculate the mean of log return and store it in "mu"
mu<- round(mean(logret),8)

# claculate the standard deviation of log return and store it in "sig"


sig<- round(sd(logret),8)

# calculate the value at risk VaR @ 95% confidence interval and store it in
"var"
var<-qnorm(.05,mu,sig)

#Display VaR
var

# if portfolio exposure is USD 1000 million to Nifty 50


pf_VaR <- 1000* (exp(var)-1)

#calculate expected shortfall


es <- mu-sig*dnorm(qnorm(0.05,0,1),0,1)/0.05

#calculate Expected Loss


expected_loss <- (exp(es) -1) * 1000000000

# Set Alpha (significance level) for VaR


alpha <- 0.05

# Set seed for reproducibility


[Link](1234)

# Generate 100,000 random values from a normal distribution with mean Mu


and standard deviation Sig
rvec <- rnorm(100000, mean = mu, sd = sig)

# Estimate VaR as the 5th percentile (Alpha quantile)


VaR <- quantile(rvec, alpha)

# 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 VaR as the 5th percentile of the sampled data


VaR_empirical <- quantile(rvec_empirical, alpha)

# 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

#Topic 3: Risk Management in non-Normal Distribution

#install moments pacakge and use the library


library(moments)

#calculate the Coefficient of skewness of log return of Nifty 50


rvec <- [Link](logret)
round(skewness(rvec),3)

#calculate the Coefficient of kurtosis of log return of Nifty 50


rvec <- [Link](logret)
round(kurtosis(rvec),3)

#testing normality with jarque bera test


[Link](rvec)

######################################################################

#Plot distribution of log returns of Nifty 50


density_estimation <- density(logret)
plot(density_estimation, col = "blue", xlab = "Log Returns", lwd = 2, ylab
= "Density", main = "Distribution of Log Returns of Nifty 50")

######################################################################

#Plot t-distribution pdf with different degree of freedom


# Step 1: Define the range of x values
x <- seq(-4, 4, length=100)

# Step 2: Define the degrees of freedom for the t-distributions


df_values <- c(3, 5, 10)

# Step 3: Plot the first t-distribution for df = 3


plot(x, dt(x, df=df_values[1]), type="l", col="red", lwd=2,
main="t-Distribution PDF with Different Degrees of Freedom",
xlab="x", ylab="Density", ylim=c(0, 0.4))

# Step 4: Overlay t-distributions with different degrees of freedom


lines(x, dt(x, df=df_values[2]), col="blue", lwd=2)
lines(x, dt(x, df=df_values[3]), col="green", lwd=2)
lines(x, dnorm(x), col="black", lwd=2)

# Step 5: Add a legend


legend("topright", legend= c("df =3", "df =5", "df =10", "normal"),
col=c("red", "blue", "green", "black"), lwd=2)

######################################################################

#Plot distribution of log returns of Nifty 50

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)

#Plot fitted t-distribution of Nifty 50 log returns


# Fit t-distribution to the log returns
library(MASS)
fit <- fitdistr([Link](logret), "t", start=list(m=mean(logret),
s=sd(logret), df=3))

# Extract fitted parameters


mu_fitted <- fit$estimate["m"]
sigma_fitted <- fit$estimate["s"]
df_fitted <- fit$estimate["df"]

# Add the fitted t-distribution density line


x <- seq(min(logret), max(logret), length=4000)

# Density of the fitted t-distribution


lines(x, dt((x - mu_fitted) / sigma_fitted, df=df_fitted) / sigma_fitted,
col="red", lwd=2)

# Add a legend
legend("topright", legend= c("Logret", "fitted-t", "normal"),
col=c("blue", "red", "black"), lwd=2)

#####################################################################

#fitting the logret to t distribution


rvec <- [Link](logret)
[Link] <- fitdistr(rvec, "t")

#display three parameters of the rescaled t-distirbution


round([Link]$estimate,6)

library(metRology)
# Set Alpha (significance level) for VaR
alpha <- 0.05

# Set seed for reproducibility


[Link](1234)

# Generate 100,000 random values from the rescaled t-distribution with 3


paramenters (mu, sd and df)
rvec <-
[Link](100000,mean=[Link]$estimate[1],sd=[Link]$estimate[2],df=[Link]$estim
ate[3])

# Estimate VaR as the 5th percentile (Alpha quantile)


VaR_t <- quantile(rvec,alpha)

# 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

# Set seed for reproducibility


[Link](1234)

# Initialize a vector for the 100,000 simulated ten-day returns


rvec <- rep(0, 100000)

# 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])
}

# Calculate 5th percentile for VaR


VaR_10da <- quantile(rvec, 0.05)

# Calculate expected shortfall


ES_10da <- mean(rvec [rvec < VaR])

# Dispalay VaR and ES


VaR_10da
ES_10da

#Method B
# Set Alpha (significance level) for VaR
alpha <- 0.05

# Set seed for reproducibility


[Link](1234)

# Initialize a vector for the 100,000 simulated ten-day returns


rvec <- rep(0, 100000)

# 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)
}

# Calculate 5th percentile for VaR


VaR_10db <- quantile(rvec, 0.05)

# Calculate expected shortfall


ES_10db <- mean(rvec[rvec < VaR])

# Dispalay VaR and ES


VaR_10db
ES_10db

#Method C
# Set Alpha (significance level) for VaR
alpha <- 0.05

# Set seed for reproducibility


[Link](1234)

96
# Initialize a vector for the 100,000 simulated ten-day returns
rvec <- rep(0, 100000)

# Actual one-day log returns


RDAT <- [Link] (logret)

# Valid starting positions for 10-day blocks


POSN <- 1:(length(RDAT) - 9)

# Randomly sample starting positions


RPOS <- sample(POSN, 100000, replace=TRUE)

# Add the returns for 10 consecutive days


for (i in 0:9) {
rvec <- rvec + RDAT[RPOS + i]
}

# Calculate 5th percentile for VaR


VaR_10dc <- quantile(rvec, 0.05)

# Calculate expected shortfall


ES_10dc <- mean(rvec [rvec < VaR])

# Dispalay VaR and ES


VaR_10dc
ES_10dc

#Topic 4: Risk Management under volatility clustering


#checking for autocorrelation
acf(logret)

#checking volatility clustering


acf(abs(logret))

library(rugarch)

#GARCH(1,1) Model - Normal Distribution of residual


# Specify the GARCH(1,1) model
uspec <- ugarchspec([Link] = list(model = "sGARCH",garchOrder =
c(1,1)),
[Link] = list(armaOrder = c(0,0), [Link] =
TRUE), [Link] = "norm")

# Fit the GARCH model to the log return data


[Link] <- ugarchfit(spec = uspec, data = logret[,1])
print([Link])

# Save fitted values for analysis


save1 <- cbind(logret[,1], [Link]@fit$sigma, [Link]@fit$z )
names(save1) <- c("D", "logret", "s", "z")

# Disave1# Display summary statistic of z (residual term)


library(moments)
mean(save1$z)
sd(save1$z)
skewness(save1$z)
kurtosis(save1$z)

97
# jarque bera test for normality of z (residual term)
[Link]([Link](save1$z))

# testing for z (residual term) for SC & VC


acf(save1$z) # Check for serial correlation (SC)
acf(abs(save1$z)) # Check for volatility clustering (VC)

#GARCH(1,1) Model - t Distribution of residual


garch.t <- ugarchspec([Link] = list(model = "sGARCH",garchOrder =
c(1,1)),
[Link] = list(armaOrder = c(0,0), [Link] =
TRUE), [Link] = "std")

# Fit the GARCH model to the log return data


[Link].t <- ugarchfit(spec = garch.t, data = logret)
print([Link].t)

# Save fitted values and parameters for analysis


save1 <- cbind(logret[,1], [Link].t@fit$sigma, [Link].t@fit$z )
names(save1) <- c("D",'logret', 's', 'z' )

# Save estimated parameters


parm1 <- coef([Link].t)
head(parm1)

# Check for normality of residuals (save1$z)


mean(save1$z)
sd(save1$z)
skewness(save1$z)
kurtosis(save1$z)

# Check for serial correlation


acf(save1$z)

# Check for volatility clustering


acf(abs(save1$z))

#Estimating VaR & ES using GARCH


[Link](1234)
[Link] <- ugarchboot([Link].t, method="Partial", sampling="raw",
[Link]=1, [Link]=100000, solver="solnp")

#The simulated outcomes are then saved in the vector “rvec”


rvec <- [Link]@fseries

VaR_garch <- quantile(rvec,0.05)


ES_garch <- mean(rvec[rvec<VaR])

#Display VaR and ES


VaR_garch
ES_garch

#Estimating Rolling 1-day VaR


# Step 1: Identify the index for the last day of 2022
n2023 <- length(logret["2008-01-01/2022-12-31"])

# Step 2: Specify the GARCH model with Student-t errors


garch.t <- ugarchspec([Link] = list(model = "sGARCH",garchOrder =
c(1,1)),
[Link] = list(armaOrder = c(0,0), [Link] =
TRUE), [Link] = "std")

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)

# Step 5: Visualize the results


plot([Link], which = 3)

# Plot the first series (5% VaR) with red color


plot(var_rolling$`alpha(5%)`, type = "l", col = "red", lwd =1,
xlab = "Jan-23 to Dec-23", ylab = "Value", main = "Rolling VaR and Log
Returns",
ylim = range(c(var_rolling$`alpha(5%)`, logret["2023-01-01/2024-12-
31"])))

# Overlay the second series (log returns) with blue color


[Link](logret["2023-01-01/2024-12-31"], col = "blue", lwd =1)

legend("bottomleft", legend= c("Logret", "VaR"),


col=c("blue", "red"), lwd=1, bty = "n", bg = "transparent")

# Compare calculations of all approaches


# Tabulate results
results <- [Link](
Method = c("Formula based", "Simulation Normal Distribution", "Simulation
Empirical Distribution", "Fitted T-Distribution", "GARCH (1,1)"),
Value_at_Risk = c(var, VaR, VaR_empirical, VaR_t, VaR_garch),
Expected_Shortfall = c(es, ES, ES_empirical, ES_t, ES_garch)
)

# Print table
print(results)

# Count breaches (days when log returns < rolling VaR)


breaches <- logret["2023-01-01/2024-12-31"] < var_rolling$`alpha(5%)`
names(breaches) <- c("Breach")
num_breaches <- sum(breaches, [Link] = TRUE) # Total count of breaches

# 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
)

# View only rows where breaches occurred (Breach = TRUE)


breach_results <- var_breaches[var_breaches$Breach == TRUE, ]

# View the first 10 rows of breaches


head(breach_results, 10)

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

Common questions

Powered by AI

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 .

You might also like