ox代写-FINS5542
时间:2022-06-23
1Course Materials FINS5542
Jonathan J Reeves (Copyright, 2022)
University of New South Wales
May 20, 2022
2
Chapter 1
Introduction to Ox
In this part of the course we will use the Ox econometric/statistical
package for quantitative analysis. Ox is a very powerful tool
and allows complex issues in investment analysis to be solved
with ease.1
1.1 Running an Ox program
To run an Ox program one must first create a text file that
contains the Ox program. Our first Ox program shall be called
prog1.ox. To create this text file we shall run the text editor
called OxEdit.
In OxEdit we type:
#include // include the Ox standard
// library header
main()
{
}
The program is then saved and run through the editor (demon-
strated in the lecture)
1http://www.nuff.ox.ac.uk/Users/Doornik/ provides information on downloading Ox.
3
4 CHAPTER 1. INTRODUCTION TO OX
1.2 Comments in Ox
Comments should be included in programs to make it easier
to follow.
For blocks of comments use:
/* */
And for comments up to the end of a line use //
1.3 A First Ox Program
#include
main()
{
print("Hello Class");
}
Note that a statement is terminated with a semicolon(;)
1.4 Variables, Vectors and Matrices
Most programs will contain variables. A variable may be a real
number, vector or matrix. All variables must be declared in
the program.
#include
main()
{
decl a,x,y,z; // declaring variables
1.4. VARIABLES, VECTORS AND MATRICES 5
a=3; // assigns the number 3 to the variable a.
x=4;
y=5;
z=a+x+y;
print("z=", z);
}
This program produces z= 12
Vectors and matrices are also variables. A vector can be
thought of as a matrix. A matrix is an array of numbers.
A vector is a matrix that contains just one row or just one
column.
A 3× 1 vector contains three rows and one column.
e.g.

1
2
3

A 1× 3 vector contains one row but three columns.
e.g.
(
1 2 3
)
A 3× 3 matrix contains three rows and three columns.
e.g.
6 CHAPTER 1. INTRODUCTION TO OX

11 12 13
21 22 23
31 32 33

To create these matrices in Ox one could do the following.
#include
main()
{
decl c,d,e;
c=<1;2;3>; // assigns the column vector.
d=<1,2,3>; // assigns the row vector
e=<11,12,13;21,22,23;31,32,33> // assigns the 3X3 matrix
print("c=", c);
print("d=", d);
print("e=", e);
}
In most cases we will be reading portfolio data in from a disk.
The disk will contain a number of columns and a number of
rows. Each column will correspond to an asset. And each row
will correspond to a particular time period.
We will be reading in an ASCII matrix file. This has exten-
sion .mat and is just a text file containing rows and columns.
The first two numbers in the file give the number of rows and
columns in the matrix.
To load in this data we could write:
1.5. MATRIX OPERATIONS 7
#include
main()
{
decl px;
px = loadmat("pdata.mat");
print(px);
}
1.5 Matrix Operations
A matrix usually has two indices: [i][j] indexes element (i,j) of
a matrix, where [0][0] is the first top left element.
Either i or j may be replaced by a range, such as i1:i2
e.g.
If x =

1 2 3
4 5 6
7 8 9

then y = x[1 : 2][0 : 1] =
 4 5
7 8

The empty index [] selects all rows (when it is the first index)
or all columns (when it is the second index).
Standard matrix operators can be performed in Ox.
For matrix multiplication use *
To transpose a matrix use ’
To add or subtract two corresponding matrices or vectors
use + or -
8 CHAPTER 1. INTRODUCTION TO OX
1.6 The for loop
e.g.
#include
main()
{
decl j;
for (j=0; j<5; ++j)
{
print(" ", j);
}
}
will print 0 1 2 3 4
1.7 Conditional Statements
The syntax is:
if ( condition)
{
statements
}
else if ( condition)
{
statements
}
1.7. CONDITIONAL STATEMENTS 9
else
{
statements
}
e.g.
for (j=0; j< 100; j++)
{
if ( x[0][j] < -1 )
y[0][j] = -10 ;
else if ( x[0][j] > 1 )
y[0][j] = 10 ;
else
y[0][j] = 2 ;
}
10 CHAPTER 1. INTRODUCTION TO OX
1.8 Ordinary Least Squares Regression
result = olsc(y, x, &b);
This will regress the y vector onto the regressor matrix x
and place the co-efficient estimates in the vector b.
If the regression is successfully carried out a 1 will be placed
in the variable result.
1.9 Writing Output to a File
decl file = fopen("results", "a");
fprint(file, "\n " , " ", x[0][j] ," ", y[0][j]);
fclose(file);
1.10 A Portfolio Data Set
Our portfolio consists of nineteen US stocks. The data is at
the daily frequency and covers the period, from the beginning
of 1991 until the end of 1999. These particular equity claims
are selected on the basis of published positions held by highly-
capitalised US mutual funds.
1.11 Graphing in Excel
We will produce most of our graphs using Excel. Our portfolio
data set will have the date in the first column and then have
individual stocks in the other columns. To graph a stocks
1.11. GRAPHING IN EXCEL 11
against time one highlights the date column and the columns
in which the stocks are located, and then one clicks on the
Chart Wizard.
12 CHAPTER 1. INTRODUCTION TO OX
Chapter 2
Technical Analysis
2.1 Introduction
• In this chapter we will look at some of the commonly used
technical methods for predicting market direction.
• Basic idea: Use past prices and volume trading to determine
trends and the timing of market moves, which if detected early
enough, can be utilised to earn excess returns.
2.2 Plotting
• Technical analysis is also called charting.
• This graphical representation of prices etc. is very important.
2.3 Support and Resistance
• Resistance is a price level which an asset has difficulty rising
above.
• e.g. A previously realised highest value.
• e.g. A psychologically important (round) number.
• Support is a level below which an asset price seems to be
reluctant to fall.
13
14 CHAPTER 2. TECHNICAL ANALYSIS
• When a support or resistance level finally breaks, it often
does so quite dramatically.
2.4 Trendlines
• Formed by joining together successive peaks and or troughs
in the price history.
2.5 Moving Averages
• Calculated in many different ways.
• There are different possible time windows.
• Exponentially weighted averages can be used.
• Designed to distill out the basic trend in a prices by smooth-
ing the random noise.
• e.g. The 5-day moving average of an asset is given by:
M(5)t =
1
5
4∑
i=0
Pt−i
where Pt denotes the closing price of the asset at day t.
• Long moving averages will be smoother than short moving
averages.
• A typical moving average trading rule prescribes a buy (sell)
signal when a short moving average crosses a longer moving
average from below (above).
2.6 Relative Strength
• A relative strength index is the percentage of up moves in
the last N days.
2.7. OSCILLATORS 15
• A number higher than 70% is said to be overbought and
therefore likely to fall.
• A number below 30% is said to be oversold and should rise.
2.7 Oscillators
• e.g. The difference between two moving averages.
• Say, the 5-day moving average minus the 20-day moving
average.
• Oscillator rules suggest buying (selling) the asset when the
oscillator index takes an extremely low (high) value.
2.8 Bollinger Bands
• Plots of a specified number of standard deviations above and
below a specific moving average.
2.9 Other Patterns
• Practitioners say that certain patterns anticipate certain fu-
ture moves.
• Head and Shoulders
A common pattern.
There is a left and a right shoulder with the head rising above.
Following on from the right shoulder should be a dramatic
decline in the asset price.
16 CHAPTER 2. TECHNICAL ANALYSIS
2.10 Programs
// program prma.ox
// This program generates 5-day and
// 20-day moving averages
#include
main()
{
ranseed(967537412);
decl i, pdt, mv5av, j, k, mv20av, mvdifav;
pdt = new matrix[2275][19];
pdt = loadmat("pdatau.prn");
mv5av = new matrix[2275][19];
mv20av = new matrix[2275][19];
mvdifav = new matrix[2275][19];
for (i=0; i< 19; i++)
{
mv5av[0][i] = 0;
2.10. PROGRAMS 17
mv5av[1][i] = 0;
mv5av[2][i] = 0;
mv5av[3][i] = 0;
for (j=4; j< 2275; j++)
{
mv5av[j][i] = ( pdt[j][i] + pdt[j-1][i] +
pdt[j-2][i] + pdt[j-3][i] + pdt[j-4][i] )/5 ;
}
for (k=0; k< 19; k++)
{
mv20av[k][i] = 0;
}
for (j=19; j< 2275; j++)
{
mv20av[j][i] = pdt[j][i] ;
for (k=1; k< 20; k++)
{
mv20av[j][i] += pdt[j-k][i] ;
}
18 CHAPTER 2. TECHNICAL ANALYSIS
mv20av[j][i] = (mv20av[j][i])/20;
}
}
for (i=0; i< 19; i++)
{
mvdifav[][i] = mv5av[][i] - mv20av[][i];
}
for (i=0; i< 19; i++)
{
for (k=0; k< 19; k++)
{
mvdifav[k][i] = 0;
}
}
for (k=0; k< 2275; k++)
{
decl file = fopen("mv5ave.out","a");
2.10. PROGRAMS 19
fprint(file, "\n " , " ", mv5av[k][0] , " ",
mv5av[k][1] , " ",
mv5av[k][2] , " ",
mv5av[k][3] , " ",
mv5av[k][4] , " ",
mv5av[k][5] , " ",
mv5av[k][6] , " ",
mv5av[k][7] , " ",
mv5av[k][8] , " ",
mv5av[k][9] , " ",
mv5av[k][10] , " ",
mv5av[k][11] , " ",
mv5av[k][12] , " ",
mv5av[k][13] , " ",
mv5av[k][14] , " ",
mv5av[k][15] , " ",
mv5av[k][16] , " ",
mv5av[k][17] , " ",
mv5av[k][18] );
fclose(file);
}
for (k=0; k< 2275; k++)
{
decl file = fopen("mv20ave.out","a");
fprint(file, "\n " , " ", mv20av[k][0] , " ",
mv20av[k][1] , " ",
mv20av[k][2] , " ",
20 CHAPTER 2. TECHNICAL ANALYSIS
mv20av[k][3] , " ",
mv20av[k][4] , " ",
mv20av[k][5] , " ",
mv20av[k][6] , " ",
mv20av[k][7] , " ",
mv20av[k][8] , " ",
mv20av[k][9] , " ",
mv20av[k][10] , " ",
mv20av[k][11] , " ",
mv20av[k][12] , " ",
mv20av[k][13] , " ",
mv20av[k][14] , " ",
mv20av[k][15] , " ",
mv20av[k][16] , " ",
mv20av[k][17] , " ",
mv20av[k][18] );
fclose(file);
}
for (k=0; k< 2275; k++)
{
decl file = fopen("mvdifave.out","a");
fprint(file, "\n " , " ", mvdifav[k][0] , " ",
mvdifav[k][1] , " ",
mvdifav[k][2] , " ",
mvdifav[k][3] , " ",
mvdifav[k][4] , " ",
mvdifav[k][5] , " ",
2.10. PROGRAMS 21
mvdifav[k][6] , " ",
mvdifav[k][7] , " ",
mvdifav[k][8] , " ",
mvdifav[k][9] , " ",
mvdifav[k][10] , " ",
mvdifav[k][11] , " ",
mvdifav[k][12] , " ",
mvdifav[k][13] , " ",
mvdifav[k][14] , " ",
mvdifav[k][15] , " ",
mvdifav[k][16] , " ",
mvdifav[k][17] , " ",
mvdifav[k][18] );
fclose(file);
}
}
22 CHAPTER 2. TECHNICAL ANALYSIS
// program prrs.ox
// N day relative strength index
// Calculates the percentage of up moves
// in the last N days.
#include
main()
{
ranseed(967537412);
decl i, pdt, j, k, rs, dpdt, N, dpdtI;
pdt = new matrix[2275][19];
pdt = loadmat("pdatau.prn");
dpdt = new matrix[2275][19];
dpdt = diff0(pdt, 1);
dpdtI = new matrix[2275][19];
for (i=0; i< 19; i++)
{
for (j=0; j< 2275; j++)
2.10. PROGRAMS 23
{
if ( dpdt[j][i] > 0 )
{
dpdtI[j][i] = 1;
}
else
{
dpdtI[j][i] = 0;
}
}
}
rs = new matrix[2275][19];
N = 30;
for (i=0; i< 19; i++)
{
for (j=0; j< N; j++)
{
rs[j][i] = 0;
}
24 CHAPTER 2. TECHNICAL ANALYSIS
for (j=N; j< 2275; j++)
{
rs[j][i] = dpdtI[j][i];
for (k=1; k< N; k++)
{
rs[j][i] += dpdtI[j-k][i];
}
rs[j][i] = (rs[j][i])/N;
}
}
for (k=0; k< 2275; k++)
{
decl file = fopen("ralst.out","a");
fprint(file, "\n " , " ", rs[k][0] , " ",
rs[k][1] , " ",
rs[k][2] , " ",
rs[k][3] , " ",
rs[k][4] , " ",
rs[k][5] , " ",
rs[k][6] , " ",
rs[k][7] , " ",
rs[k][8] , " ",
rs[k][9] , " ",
2.10. PROGRAMS 25
rs[k][10] , " ",
rs[k][11] , " ",
rs[k][12] , " ",
rs[k][13] , " ",
rs[k][14] , " ",
rs[k][15] , " ",
rs[k][16] , " ",
rs[k][17] , " ",
rs[k][18] );
fclose(file);
}
}
26 CHAPTER 2. TECHNICAL ANALYSIS
Chapter 3
Value at Risk (VaR)
3.1 Definition of Value at Risk
• Value at Risk (VaR) is an estimate, with a given degree of
confidence, of how much one can lose from one’s portfolio over
a given time horizon, under normal market conditions.
•More formally: For a give time horizon n and confidence level
1−α, the VaR is the loss in the portfolio over the time horizon
that we expect we will not exceed with probability 1−α, with
the current asset mix.
• An example: The 10 day 99% VaR for our portfolio is 1
million.
• Interpretation: We are currently 99% confident that in 10
days the loss in our portfolio will not exceed 1 million.
• The level of confidence is most often set at 99% (α = 0.01).
Though 95% (α = 0.05) and 97.5% (α = 0.025) are also
common.
• Popular time horizons are 1 day, 1 week, 10 days, 2 weeks, 1
month, 2 months 3 months.
• The portfolio may include common stocks, bonds, foreign
27
28 CHAPTER 3. VALUE AT RISK (VAR)
exchange, options on any or all of the above, or other deriva-
tives.
• If the portfolio is that of a singe trader than calculating VaR
will be of interest in measuring trader efficiency. e.g.
daily P&L
daily VaR
• If the portfolio is that of the entire firm, the VaR will provide
information on the likely effect of stock market movements on
the entire firm.
•The Bank for International Settlements (BIS) http://www.bis.org/
sets 1−α = 0.99 and n to ten days for purposes of measuring
the adequacy of bank capital, and factors up the 99% VaR by
a multiple of three to get the adequate level of bank capital.
• The two popular methods to calculate VaR are the variance-
covariance approach and the historical simulation approach.
3.2 The Variance-Covariance Approach
• Assumes the change in market prices has a joint normal
distribution.
• Let
pt =

p1t
p2t
.
.
.
pNt

3.2. THE VARIANCE-COVARIANCE APPROACH 29
be the price vector for our N assets.
• Let
∆pt =

∆p1t
∆p2t
.
.
.
∆pNt

=

p1,t − p1,t−1
p2,t − p2,t−1
.
.
.
pN,t − pN,t−1

be the price change vector for our N assets.
• Let the expected value of the price change vector be µ. i.e.
E[∆pt] =

E[∆p1t]
E[∆p2t]
.
.
.
E[∆pNt]

= µ =

µ1
µ2
.
.
.
µN

• To estimate µ we use the sample average. i.e.
µ̂i =
1
T − 1
T∑
t=2
∆pi,t for i = 1, . . . , N
Note: T is the current time period. i.e. the date at which
we are computing a VaR estimate. Also note that the hat over
µi denotes an estimate.
• Let the variance-covariance matrix of the price change vector
be Σ.
30 CHAPTER 3. VALUE AT RISK (VAR)
Σ =

σ11 σ12 . . . σ1N
σ21 σ22 . . . σ2N
... ... ...
σN−1,1 σN−1,2 . . . σN−1,N
σN,1 σN,2 . . . σN,N

Note:
(i) Σ has elements σij = Cov[∆pi,∆pj], σii = Cov[∆pi,∆pi] =
Var[∆pi]
(ii) Σ is symmetric ΣT = Σ, σij = σji
(iii) Var[∆pi] = E[(∆pi − E[∆pi])2]
(iv) Cov[∆pi,∆pj] = E[(∆pi − E[∆pi])(∆pj − E[∆pj])].
• To estimate Σ we again use the sample average. i.e.
σ̂ij =
∑T
t=2(∆pi,t −∆pi)(∆pj,t −∆pj)
T − 2 for i = 1, . . . , N , j = 1, . . . , N
• We can estimate the distribution for the ∆p vector by:
N(µ̂, Σ̂)
• Note: The level of our portfolio n periods into the future
(WT+n) is given by:
WT+n = x
TpT + x
T∆pT+1 + x
T∆pT+2 . . . + x
T∆pT+n
where
3.3. THE HISTORICAL SIMULATION APPROACH 31
x =

x1
x2
.
.
.
xN

is the holdings vector for our N assets at time period T .
• To estimate the distribution of the level of our portfolio n
periods into the future (WT+n) we can use the following esti-
mate:
WT+n ∼ N(xTpT + nxT µ̂, nxT Σ̂x)
• The 100(1− α)% VaR for our porfolio is
−((xTpT + nxT µ̂ + Zα

nxT Σ̂x)− (xTpT ))
= −nxT µ̂− Zα

nxT Σ̂x
where Zα is the 100α percentile of the standard normal
distribution.
• Note:
Z0.01 = −2.3263479
Z0.025 = −1.959964
Z0.05 = −1.6448536
3.3 The Historical Simulation Approach
• a widely used approach to generate a VaR estimate is to use
the historical simulation approach.
32 CHAPTER 3. VALUE AT RISK (VAR)
• This involves resampling past returns to generate the distri-
bution of the level of our portfolio n periods into the future
(WT+n).
• Assume we have historical data from time period 1 up until
time period T . And we have N assets. Then we have T − 1
change in price vectors.
∆pt =

∆p1t
∆p2t
.
.
.
∆pNt

=

p1,t − p1,t−1
p2,t − p2,t−1
.
.
.
pN,t − pN,t−1

for t = 2, 3, . . . , T
• We now attach a 1T−1 probability that one of these price
change vectors occurs on any given day in the future.
• To estimate WT+n we take our current asset holdings and
we resample, with replacement, from our price change vectors.
• We draw n price change vectors. ∆∗p1,∆∗p2, . . . ,∆∗pn.
This produces one realisation of our portfolio in time period
T + n. The realisation is:
W ∗T+n = x
T (pT + ∆p

1 + ∆p

2 + . . . + ∆p

n)
•We repeat this process B times. B is usually chosen to be a
large number, at least as large as 1000.
• Assume we choose B = 1000. Then we will have 1000
realisations W ∗T+n. These should now be sorted from lowest to
highest. We can now graph a histogram for WT+n which will
show us a picture of the distribution of WT+n.
3.4. VAR FOR FIXED-INCOME SECURITIES 33
• Let the empirical quantile associated with α for our porfolio
be denoted by f ∗α. It’s interpretation is that 100α% of the
replications yielded W ∗T+n less than f

α.
• To calculate f ∗α we rank W ∗T+n from lowest to highest. As-
sume we have done B = 1000 replications. Then the lowest
value for W ∗T+n we denote as w

1, the second lowest as w

2, and
the largest value of W ∗T+n as w

1000. The f

0.01 is estimated by:
1
2
(w∗10 + w

11)
• The 100(1− α)% VaR for our porfolio is:
−(f ∗α − xTpT )
= xTpT − f ∗α
• The big advantage of this approach is that there is no distri-
butional assumption made. Historical price changes are often
non-normal, so this method takes this into account.
• Another big advantage is that no parameters, such as a
variance-covariance matrix have to be estimated.
• Note also that because we keep together in ∆pt all the price
changes that occur in time period t. By doing so, we capture
any correlation that there may be between assets.
• Sometimes this method is referred to as a bootstrap method.
3.4 VaR for Fixed-Income Securities
• Fixed-income securities form substantial portions of many
investment portfolios.
34 CHAPTER 3. VALUE AT RISK (VAR)
• A zero-coupon bond or discount bond will pay its face value
of PT at maturity after T periods. The value of the bond at
time 0 is
P0 =
PT
(1 + y)T
where y is the yield to maturity.
However, most bonds are coupon bonds
P0 =
T∑
t=1
Ct
(1 + y)t
+
PT
(1 + y)T
where Ct is the coupon payable in period t.
Assuming away default risk, the following relationship also
holds:
P0 =
C1
1 + R1
+
C2
(1 + R2)2
+ . . . +
CT + PT
(1 + RT )T
These rates (R1, R2, . . . , RT ) define the spot rate yield curve.
• We generally observe R1 because there are actual markets
for one year discount bonds.
•We also observe C1, C2, P2 and the current price P for a two
period coupon bond, so we can solve for R2 from the following
relationship:
P0 =
C1
1 + R1
+
C2
(1 + R2)2
•We can continue this process to estimate the spot yield curve
at time t.
• This can be done for many past time periods to produce
a historical time series of short-term, medium term and long-
term rates. e.g.
3.5. VAR FOR DERIVATIVES 35

R1t
R2t
R3t

for t = 1, . . . , 500
• Next we could model a relationship between changes in bond
prices and factors such as the change in the short term rate,
the change in the medium term rate, and the change in the
long term rate.
• We could then simulate future paths of bond prices, from
simulated changes in interst rates, which will provide future
realisations of our portfolio.
• The VaR could be computed from a lower quantile of this
distribution of future realisations.
3.5 VaR for Derivatives
• When estimating a VaR for a portfolio containing deriva-
tives, it is very important to realise that even if the change
in the underlying asset is normal, the non-linearity in deriva-
tives, means that the change in the derivarative can be far from
normal.
• VaR estimates can be generated by simulations, assuming
that one knows the behaviour of the underlying assets and has
accurate derivative pricing models.
• However, for large portfolios, computer simulation can be
expensive, so the delta-gamma approach is often useful.
• The Delta approach is approximately valid for small changes
in the price of the underlying asset.
• To demonstrate, assume that our portfolio just consists of an
36 CHAPTER 3. VALUE AT RISK (VAR)
option. The relationship between the change in the underlying
asset, δS, and the change in the value of the option, δV , can
be approximated by:
δV =
∂V
∂S
δS
• ∂V∂S is referred to as the delta (∆) of the option.
• For a call option valued by the Black-Scholes formula:
∂V
∂S
= Φ(d1)
where
d1 =
1
σ

T − t(log(S/K) + (r +
1
2
σ2)(T − t))
and K is the exercise price, r is the home risk-free rate at
time t, σ is the standard deviation of the underlying asset, Φ is
the cumulative probability distribution function for a standard
normal variable.
• For a put option valued by the Black-Scholes formula:
∂V
∂S
= Φ(d1)− 1
• If we hold a portfolio of options, with different strike prices
and different maturities, the change in the value of the port-
folio, due to a one dollar change in the price of the underlying
asset is given by:
N∑
i=1
∂Vi
∂S
xi
where xi is the holding in option i
3.6. EVALUATING VAR ESTIMATES 37
• This method is only approximately valid for small changes
in the price of the underlying asset, for a much more accu-
rate estimate of the change in the portfolio, the delta-gamma
approach is useful.
• In this approach the change in the value of the option, δV ,
can be approximated by:
δV =
∂V
∂S
δS +
1
2
∂2V
∂S2
(δS)2
• ∂2V
∂S2
is referred to as the gamma (Γ) of the option.
• For a call option valued by the Black-Scholes formula:
∂2V
∂S2
=
φ(d1)


T − t
where φ is the probability density function for a standard
normal variable.
• By assuming the change in the underlying asset has a normal
distribution, one can generate, using the delta-gamma approx-
imation, the distribution for the change in the option, and thus
estimate a lower quantile for a VaR estimate.
3.6 Evaluating VaR Estimates
• It is very important to run tests on how well our VaR esti-
mates perform over time.
• A very good approach is to take recent historical data and
to plot realised VaR versus estimated VaR.
• Over a long enough time horizon, the proportion of times the
loss in our portfolio exceeds the VaR, should approximately
equal α, if our VaR estimation procedure is performing well.
38 CHAPTER 3. VALUE AT RISK (VAR)
3.7 A Cautionary Note
•While VaR estimation has become very popular in the funds
management industry, there are times in which the VaR esti-
mate may fail. Namely:
• Historical data does not always provide accurate information
on future behavior. e.g. the relationship between assets may
change over time.
• VaR does not measure credit risk. The risk associated with
a default.
• If the holdings in the assets change during the period over
which the VaR is calculated, this can substantially change the
risk associated with the portfolio.
• One should also keep in mind that financial variables are sub-
ject to unexpected events. e.g. devaluations. The magnitude
and probability of these events are difficult to estimate.
3.8 Final Remarks
• In October 1994 the American bank, JP Morgan introduced
the system ”RiskMetrics” as a service to estimate VaR. See
http://www.riskmetrics.com/
• Another popular reference is Jorion, P. (1996), Value at Risk:
the New Benchmark for Controlling Market Risk, Chicago:
Irwin.
3.9. PROGRAMS 39
3.9 Programs
// program pgnor1.ox
// This program generates VaR calculations
// based on normality.
#include
main()
{
ranseed(967537412);
decl i, j, ww, meanp, meanpw, pdt, pdtdf;
decl pdtdfu, pdtdfuv, pdtdfuvf, varn;
pdt = new matrix[2275][19];
pdt = loadmat("pdatau.prn");
pdtdf = new matrix[2275][19];
pdtdf = diff0(pdt, 1);
pdtdfu = new matrix[1000][19];
ww = new matrix[19][1];
pdtdfuv = new matrix[19][19];
40 CHAPTER 3. VALUE AT RISK (VAR)
pdtdfuvf = new matrix[19][19];
meanp = new matrix[1][19];
varn = new matrix[1][1];
ww[0][0] = 100000/(pdt[2014][0]);
ww[1][0] = 100000/(pdt[2014][1]);
ww[2][0] = 100000/(pdt[2014][2]);
ww[3][0] = 100000/(pdt[2014][3]);
ww[4][0] = 100000/(pdt[2014][4]);
ww[5][0] = 100000/(pdt[2014][5]);
ww[6][0] = 100000/(pdt[2014][6]);
ww[7][0] = 100000/(pdt[2014][7]);
ww[8][0] = 100000/(pdt[2014][8]);
ww[9][0] = 100000/(pdt[2014][9]);
ww[10][0] = 100000/(pdt[2014][10]);
ww[11][0] = 100000/(pdt[2014][11]);
ww[12][0] = 100000/(pdt[2014][12]);
ww[13][0] = 100000/(pdt[2014][13]);
ww[14][0] = 100000/(pdt[2014][14]);
ww[15][0] = 100000/(pdt[2014][15]);
ww[16][0] = 100000/(pdt[2014][16]);
ww[17][0] = 100000/(pdt[2014][17]);
ww[18][0] = 100000/(pdt[2014][18]);
3.9. PROGRAMS 41
for (i=0; i< 252; i++)
{
pdtdfu = pdtdf[(1015+i):(2014+i)][];
pdtdfuv = variance(pdtdfu);
pdtdfuvf = ww’*pdtdfuv*ww;
meanp = meanc(pdtdfu);
varn[0][0]=-10*ww’*(meanp’)-(-2.3263*sqrt(10*pdtdfuvf));
decl file = fopen("varn.out", "a");
fprint(file, "\n " , varn[0][0]);
fclose(file);
}
}
42 CHAPTER 3. VALUE AT RISK (VAR)
// program pgrel1.ox
// This program generates VaR calculations
// based on normality and also generates the
// actual loss over the 10-day period.
#include
main()
{
ranseed(967537412);
decl i, j, ww, meanp, meanpw, pdt, pdtdf, pdtdfu;
decl pdtdfuv, pdtdfuvf, varn, realv;
pdt = new matrix[2275][19];
pdt = loadmat("pdatau.prn");
pdtdf = new matrix[2275][19];
pdtdf = diff0(pdt, 1);
pdtdfu = new matrix[1000][19];
ww = new matrix[19][1];
pdtdfuv = new matrix[19][19];
3.9. PROGRAMS 43
pdtdfuvf = new matrix[19][19];
meanp = new matrix[1][19];
varn = new matrix[1][1];
realv = new matrix[1][1];
ww[0][0] = 100000/(pdt[2013][0]);
ww[1][0] = 100000/(pdt[2013][1]);
ww[2][0] = 100000/(pdt[2013][2]);
ww[3][0] = 100000/(pdt[2013][3]);
ww[4][0] = 100000/(pdt[2013][4]);
ww[5][0] = 100000/(pdt[2013][5]);
ww[6][0] = 100000/(pdt[2013][6]);
ww[7][0] = 100000/(pdt[2013][7]);
ww[8][0] = 100000/(pdt[2013][8]);
ww[9][0] = 100000/(pdt[2013][9]);
ww[10][0] = 100000/(pdt[2013][10]);
ww[11][0] = 100000/(pdt[2013][11]);
ww[12][0] = 100000/(pdt[2013][12]);
ww[13][0] = 100000/(pdt[2013][13]);
ww[14][0] = 100000/(pdt[2013][14]);
ww[15][0] = 100000/(pdt[2013][15]);
ww[16][0] = 100000/(pdt[2013][16]);
ww[17][0] = 100000/(pdt[2013][17]);
ww[18][0] = 100000/(pdt[2013][18]);
44 CHAPTER 3. VALUE AT RISK (VAR)
for (i=0; i< 252; i++)
{
pdtdfu = pdtdf[(1014+i):(2013+i)][];
pdtdfuv = variance(pdtdfu);
pdtdfuvf = ww’*pdtdfuv*ww;
meanp = meanc(pdtdfu);
varn[0][0]=-10*ww’*(meanp’)-(-2.3263*sqrt(10*pdtdfuvf));
realv[0][0]=((pdt[2013+i][])*ww)-
((pdt[2013+i+10][])*ww);
decl file = fopen("varn.out", "a");
fprint(file, "\n " , varn[0][0],
" ", realv[0][0]);
fclose(file);
}
}
3.9. PROGRAMS 45
// program pghs.ox
// This program generates the 10 day ahead VaR
// based on historical simulation and also
// calculates the actual loss in the portfolio.
#include
main()
{
ranseed(967537412);
decl i, j, b, ww, pdt, pdtdf, portrl;
decl portrlv, portq, varhs, realv;
pdt = new matrix[2275][19];
pdt = loadmat("pdatau.prn");
pdtdf = new matrix[2275][19];
pdtdf = diff0(pdt, 1);
ww = new matrix[19][1];
portrl = new matrix[1][19];
portrlv = new matrix[1000][19];
46 CHAPTER 3. VALUE AT RISK (VAR)
portq = new matrix[4][1];
varhs = new matrix[1][1];
realv = new matrix[1][1];
ww[0][0] = 100000/(pdt[2013][0]);
ww[1][0] = 100000/(pdt[2013][1]);
ww[2][0] = 100000/(pdt[2013][2]);
ww[3][0] = 100000/(pdt[2013][3]);
ww[4][0] = 100000/(pdt[2013][4]);
ww[5][0] = 100000/(pdt[2013][5]);
ww[6][0] = 100000/(pdt[2013][6]);
ww[7][0] = 100000/(pdt[2013][7]);
ww[8][0] = 100000/(pdt[2013][8]);
ww[9][0] = 100000/(pdt[2013][9]);
ww[10][0] = 100000/(pdt[2013][10]);
ww[11][0] = 100000/(pdt[2013][11]);
ww[12][0] = 100000/(pdt[2013][12]);
ww[13][0] = 100000/(pdt[2013][13]);
ww[14][0] = 100000/(pdt[2013][14]);
ww[15][0] = 100000/(pdt[2013][15]);
ww[16][0] = 100000/(pdt[2013][16]);
ww[17][0] = 100000/(pdt[2013][17]);
ww[18][0] = 100000/(pdt[2013][18]);
for (i=0; i< 252; i++)
{
for (b=0; b< 1000; b++)
3.9. PROGRAMS 47
{
portrl=pdt[2013+i][]+
pdtdf[(1014+i+(ranu(1,1)*(999)))][];
for (j=0; j< 9; j++)
{
portrl=portrl+pdtdf[(1014+i+(ranu(1,1)*(999)))][];
}
portrlv[b][0] = ww’*(portrl)’;
}
portq = quantilec(portrlv, <0.01, 0.025 , 0.05, 0.1>);
varhs[0][0] = ((pdt[2013+i][])*ww) - portq[0][0];
realv[0][0]=((pdt[2013+i][])*ww)-
((pdt[2013+i+10][])*ww);
decl file = fopen("varhs.out", "a");
fprint(file, "\n " , varhs[0][0], " ",
realv[0][0]);
fclose(file);
}
48 CHAPTER 3. VALUE AT RISK (VAR)
}
3.9. PROGRAMS 49
// program optvard.ox
// This program calculates the VaR for a
// European call option based on the delta method.
#include
// Delta method. S = 32. K = 30. T-t = 40
// Daily r_f = 0.0002
// Daily volatilty i.e.sigma = s.d(change S / S) = 0.01
// s.d(change S) = 0.32
main()
{
decl r, S, K, sd, d1, d2, sdV, delta, varotd;
r = 0.0002;
S = 32;
K = 30;
sd = 0.01;
d1 = ( log(S/K) + ( r + ((sd^2)/2) )*40 ) / (sd*40);
d2 = d1 - sd*40;
delta = probn(d1);
sdV = delta * 0.32;
50 CHAPTER 3. VALUE AT RISK (VAR)
varotd = -1*(-2.3263479)*sdV;
print("The 99 percent VaR for our option is ",
varotd);
}
3.9. PROGRAMS 51
// program optvarg.ox
// This program calculates the VaR for a
// European call option based on the gamma method.
#include
// Gamma method. S = 32. K = 30. T-t = 40
// Daily r_f = 0.0002
// Daily volatility i.e.sigma = s.d(change S / S) =0.01
// s.d(change S) = 0.32
main()
{
ranseed(967537412);
decl r, S, K, sd, d1, d2, delta, varotg;
decl gamma, optrl, b, sr, optqu;
r = 0.0002;
S = 32;
K = 30;
sd = 0.01;
d1 = ( log(S/K) + ( r + ((sd^2)/2) )*40 ) / (sd*40);
d2 = d1 - sd*40;
52 CHAPTER 3. VALUE AT RISK (VAR)
delta = probn(d1);
gamma = (densn(d1))/(S*sd*40);
optrl = new matrix[1000][1];
for (b=0; b< 1000; b++)
{
sr = (rann(1,1))*0.32;
optrl[b][0] = delta*sr + ( 0.5*gamma*(sr^2) ) ;
}
optqu = new matrix[4][1];
optqu = quantilec(optrl, <0.01, 0.025 , 0.05, 0.1>);
varotg = -1*optqu[0][0];
print("The 99 percent VaR for our option is ",
varotg );
}
essay、essay代写