0% found this document useful (0 votes)
2 views

Lec1.Introduction

The document outlines a course on Stochastic Simulation and its applications in finance, covering topics such as Monte Carlo simulation, random variable generation, and variance reduction techniques. It includes detailed explanations of R programming basics, including variable types, vectors, and operations on vectors. The course emphasizes practical applications and examples to illustrate the concepts.

Uploaded by

pptforwork3011
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lec1.Introduction

The document outlines a course on Stochastic Simulation and its applications in finance, covering topics such as Monte Carlo simulation, random variable generation, and variance reduction techniques. It includes detailed explanations of R programming basics, including variable types, vectors, and operations on vectors. The course emphasizes practical applications and examples to illustrate the concepts.

Uploaded by

pptforwork3011
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

COURSE

Stochastic Simulation
and Applications in Finance

1 / 58
Course outline

1. Basics of : Vectors, Control flow, Loops, Functions,...


2. Monte Carlo simulation and applications
3. Generating random variables
4. Variance reduction techniques
5. Importance Sampling
6. Simulation of multivariate distributions
7. Simulation of stochastic processes and applications
8. Discretization schemes to simulate SDEs
9. Simulation of jump processes
10. Sensitivity Analysis

2 / 58
Lecture 1
Basics of : Vectors,
Control flow, Loops, Functions

3 / 58
What is ?

4 / 58
What is ?

5 / 58
Basics of - variable assignment
We can use “<-” or “=” for assigning value to a variable
x<-3.25 # variable name is x
x

[1] 3.25
x^2+exp(x)-3

[1] 33.35284
y=2
x^y

[1] 10.5625
Variable names can contain any combination of alphanumeric characters
along with periods (.) and underscores (_). However, they cannot start
with a number or an underscore.
6 / 58
Basics of - removing variables

123x<-3.25
# check if there is an error
_x<-3.25
# check if there is an error

To remove a variable, we use function rm()


x<-3.25
x

[1] 3.25
rm(x)
x

Error: object 'x' not found

7 / 58
Basics of - numerical variables
• There are 4 main types of variables: numeric, character (string),
Date/Time and logical.
Numeric is similar to float or double in other languages.
x<-5
is.numeric(x)

[1] TRUE
x<-5
is.integer(x)

[1] FALSE
To assign an integer value to variable x:
x<-5L
is.integer(x)

[1] TRUE
8 / 58
Basics of - numerical variables

Operator Description
+ Addition
− Subtraction
∗ Multiplication
/ Division
̂ Exponent
𝑒𝑥𝑝() Natural Exponent
%% Modulus (Remainder from division)
%/% Integer Division

9 / 58
Basics of - numerical variables
6.5 %/% 2

[1] 3
6.5 %% 2

[1] 0.5
((-1)/0)*(1/0)

[1] -Inf
log(-2)

[1] NaN
log(-2)*(1/0)

[1] NaN

10 / 58
Basics of - logical variables
• Logical variables can be either TRUE or FALSE.
• Numerically, TRUE == 1 and FALSE == 0.
• Logical variables are results from relational operations
x<-TRUE
x

[1] TRUE
x*2

[1] 2
y<-FALSE
x + y

[1] 1

11 / 58
Basics of - logical variables

Operator Description
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
! Not
& And
| Or

12 / 58
Basics of - logical variables
x<-(1>=2)
x

[1] FALSE
y<-(x==0)
y

[1] TRUE
x+y

[1] 1
x&y

[1] FALSE
x|y

[1] TRUE
13 / 58
Basics of - character variables

• In any language, character variables should be use with care.


x<-"Ice cream"
is.character(x)

[1] TRUE
• Capital letter “I” and normal letter “i” are different.
x == "ice cream" # capital letter

[1] FALSE
• Funtion nchar(x) count the characters in string 𝑥
nchar(x) # number of characters

[1] 9

14 / 58
Basics of - character variables

• Function paste() concatenate number of strings into a single string


x<-paste("We", "are", "the champion", sep = " ")
x

[1] "We are the champion"


• Function substr() extract a substrings in a character vector.
substr("abcdefgh",3,4)

[1] "cd"

15 / 58
Vectors in

16 / 58
Basics of R - vertors (1)
• A vector is a collection of elements, all of the same type.
• Vectors play a crucial and helpful role in so it is also call a
vectorized language.
• There are many ways to create a vector in .
x<-c(2,3,5,7,11,13) # 1st way to create a vector
x

[1] 2 3 5 7 11 13
length(x)

[1] 6
s<-c("R", "VBA", "Python","C++")
s

[1] "R" "VBA" "Python" "C++"


17 / 58
Basics of R - vertors (2)
• To access elements of a vector, we uses []
x<-5:10 # 2nd way to create a vector
x[5]

[1] 9
x[2:4]

[1] 6 7 8
• The 3rd way to create a vector
x<-seq(1, 2, by=0.2) # from 1 to 2 with jumps = 0.2
length(x)

[1] 6
x<-seq(1, 2, length=11) # from 1 to 2 with length 11
x

[1] 1.0 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2.0 18 / 58
Basics of R - vertors (3)
• Calculations with vectors
x<-1:5
x*2

[1] 2 4 6 8 10
x^2

[1] 1 4 9 16 25
100 1
Example 1: Calculate ∑ . We do not need a for loop, indeed,
𝑘=1 𝑘2
n=100
x<-1:n
sum(1/x^2)

[1] 1.634984

19 / 58
Basics of R - vertors (4)
100 1
Example 2: Calculate ∑ .
𝑘=0 𝑘!
n=100
x<-0:n
sum(1/factorial(x))

[1] 2.718282
2
Example 3: Calculate ∫ 𝑒𝑥 𝑑𝑥 and compare the result to 𝑒2 − 1. Note
0
𝑏
that ∫ 𝑓(𝑥) 𝑑𝑥 is approximated by
𝑎

𝑏
𝑛
𝑏−𝑎
∫ 𝑓(𝑥) 𝑑𝑥 ∼ ∑ × 𝑓 (𝑥𝑖 ) with large n
𝑖=1
𝑛
𝑎

20 / 58
Basics of R - vertors (5)
n=10^4
x<-seq(0, 2, 2/n)
sum((2/n)*exp(x)) #Summing up area of small rectangles

[1] 6.389895
exp(2)-1 # Exact solution

[1] 6.389056

21 / 58
Basics of R - vertors (5)
n=10^4
x<-seq(0, 2, 2/n)
sum((2/n)*exp(x)) #Summing up area of small rectangles

[1] 6.389895
exp(2)-1 # Exact solution

[1] 6.389056

Example 4: Let 𝑋 ∼ 𝑁 (0, 1). Calculate ℙ(−0.5 < 𝑋 ≤ 1).

21 / 58
Basics of R - vertors (5)
n=10^4
x<-seq(0, 2, 2/n)
sum((2/n)*exp(x)) #Summing up area of small rectangles

[1] 6.389895
exp(2)-1 # Exact solution

[1] 6.389056

Example 4: Let 𝑋 ∼ 𝑁 (0, 1). Calculate ℙ(−0.5 < 𝑋 ≤ 1).


n = 1e4
x <- seq(-0.5, 1, length=n)
sum((1.5/n) * 1/sqrt(2*pi)*exp(-x^2/2))

[1] 0.5327985

21 / 58
Basics of R - vertors (6)
• Logical operations on vectors result in a logical vector:
x <- 1:7
x

[1] 1 2 3 4 5 6 7
x <= 3

[1] TRUE TRUE TRUE FALSE FALSE FALSE FALSE


sum(x<=3)

[1] 3
any(x==1)

[1] TRUE
all(x==1)

[1] FALSE
22 / 58
Basics of R - vertors (7)

Example 5: AirPassengers is a built-in dataset (in vector) in R.


• Is there any month that the average number of passengers is more
than 650 ?
• What is the proportion of months that the average number of
passengers are less than 300 ?

23 / 58
Basics of R - vertors (7)

Example 5: AirPassengers is a built-in dataset (in vector) in R.


• Is there any month that the average number of passengers is more
than 650 ?
• What is the proportion of months that the average number of
passengers are less than 300 ?
Solution:
any(AirPassengers>650)

[1] FALSE
sum(AirPassengers<300)/length(AirPassengers)

[1] 0.5694444

23 / 58
Basics of R - operations between vectors (1)

• Combine vectors
x<-1:3
y<-4:8
z<-9:10
c(x,y,z)

[1] 1 2 3 4 5 6 7 8 9 10
x<-seq(1,2,0.5)
y<-c(3,4)
z<-seq(5,6,length=3)
c(x,y,z)

[1] 1.0 1.5 2.0 3.0 4.0 5.0 5.5 6.0

24 / 58
Basics of R - operations between vectors (2)

x<-"I am an actuary, "


y<-"what is your talent ?"
c(x,y)

[1] "I am an actuary, " "what is your talent ?"


z<-paste(x,y)
z

[1] "I am an actuary, what is your talent ?"

25 / 58
Basics of R - operations between vectors (3)

• Subtract vector
x<-c(2,3,5,7,11,13,17,19,23,29)
x %% 2 == 1

[1] FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TR
y<-(x %% 2 == 1)
x[y]

[1] 3 5 7 11 13 17 19 23 29
y<-c(10,1,4)
x[y]

[1] 29 2 7

26 / 58
Basics of R - operations between vectors (4)
Example 6: Taking the numbers of passengers in months of June in the
AirPassengers dataset.

27 / 58
Basics of R - operations between vectors (4)
Example 6: Taking the numbers of passengers in months of June in the
AirPassengers dataset.
# Retrieve the June months for 12 years (from 1949 to 1960)
Junes <- (0:11)*12 + 6 #or Junes <- seq(6, 144, by = 12)
AirPassengers[Junes]

[1] 135 149 178 218 243 264 315 374 422 435 472 535
• Which month had the lowest average number of passengers during
those 12 years?

27 / 58
Basics of R - operations between vectors (4)
Example 6: Taking the numbers of passengers in months of June in the
AirPassengers dataset.
# Retrieve the June months for 12 years (from 1949 to 1960)
Junes <- (0:11)*12 + 6 #or Junes <- seq(6, 144, by = 12)
AirPassengers[Junes]

[1] 135 149 178 218 243 264 315 374 422 435 472 535
• Which month had the lowest average number of passengers during
those 12 years?
# Initialize a blank numeric vector of length 12
AverageNumber<-numeric(12)
for (i in 1:12){
month_id <- 0:11*12 + i
# Assign the average number of passengers for each month
AverageNumber[i] <- mean(AirPassengers[month_id])
}
27 / 58
Basics of R - operations between vectors (5)
min(AverageNumber)

[1] 232.8333
which.min(AverageNumber)

[1] 11
Draw an illustrative graph:
plot(x=1:12, y=AverageNumber, col="blue", type="b")
320
AverageNumber

280
240

2 4 6 8 10 12

1:12
28 / 58
Basics of R - operations between vectors (6)

• Operation between vectors with the same length:


x<-1:7
y<-7:1
x*y

[1] 7 12 15 16 15 12 7
x<y

[1] TRUE TRUE TRUE FALSE FALSE FALSE FALSE


round(x/y,2)

[1] 0.14 0.33 0.60 1.00 1.67 3.00 7.00

29 / 58
Basics of R - missing data
• Missing data plays a critical role in both statistics and computing.
• uses NA to denote missing data.
x<-c(1,2,3,NA,5,NA)
is.na(x)

[1] FALSE FALSE FALSE TRUE FALSE TRUE


x*2

[1] 2 4 6 NA 10 NA
x>3

[1] FALSE FALSE FALSE NA TRUE NA


y<-c(NA,2,NA,4,5,6)
x*y

[1] NA 4 NA NA 25 NA
30 / 58
Basics of R - often used functions with vectors

length(x) number of elements in vector x


sum(x) sum of all elements in vector x
mean(x) average of all elements in vector x
sd(x) standard deviation of all elements in x
prod(x) product of all elements in vector x
min(x) minimum value of all elements in vector x
max(x) maximum value of all elements in vector x
which(x) determine the TRUE indices in a logical vector x
sort(x, decreasing=T) sort vector x in decreasing order
sort(x, decreasing=F) sort vector x in increasing order

31 / 58
Addtional exercises
• Exer1: Calculate from AirPassengers dataset, the proportion of
months with average number of passengers is
∘ More than 300 but less than 400 ?
∘ More than 400 but less than 450 or more than 500 but less than 550 ?
• Exer2: Using the Nile dataset. Let x = Nile (measurements of the
annual flow of the river Nile, in 102 𝑘𝑚2 , from 1871 to 1970).
∘ What is the smallest and the largest values of annual flow?
∘ In which year the annual flow is the smallest, is the largest?
∘ In which year the annual flow is the 20𝑡ℎ largest?
• Exer3: Using the presidents dataset. Let x = presidents.
∘ How many NA values are in x?
∘ Which years there are no observation?
• Exer4: Given x = (31, 2, 11, 37, 5, 13, 17, 29, 23, 19, 3, 7). Assigning
to vector y values in vector x but in reserve order. 32 / 58
Control flow, Loops and Functions

33 / 58
Control statements in R
• Allow us to control the flow of our programming and cause different
things to happen depending on the values of tests.
• Tests result in a logical, “TRUE”, or “FALSE”.
• The main control statements are “if”, “else” and “ifelse”.

34 / 58
Control statements in R

• List of tests in R (which result in TRUE or FALSE)

Check meaning
== equal to
!= not equal to
< less than
<= less than or equal to
> greater than
>= greater than or equal to

35 / 58
Control statements “If”
Let try the following codes
x<-5
if (x < 10){
print("less than 10")
}

[1] "less than 10"


x<-5
if (x == 10){
print("equal to 10")
}

if (sum(is.na(Nile))==0){
print("There isn't any NA value in data Nile")
}

[1] "There isn't any NA value in data Nile"


36 / 58
Control statements “If”

”President” dataset provides quarterly approval rating for the President of


the United States from the first quarter of 1945 to the last quarter of 1974.
• Is there any NA value in the dataset?
• If yes, replace all NA value by 50.
• Calculate the mean of quarterly rating for the President.

37 / 58
Control statements “If”

”President” dataset provides quarterly approval rating for the President of


the United States from the first quarter of 1945 to the last quarter of 1974.
• Is there any NA value in the dataset?
• If yes, replace all NA value by 50.
• Calculate the mean of quarterly rating for the President.
x <- presidents
if (any(is.na(x))){
print("There isn't any NA value in data presidents")
} else {
print("There are NA values in data presidents")
}

[1] "There isn't any NA value in data presidents"

37 / 58
Control statements “If” and “else”
if (any(is.na(x))){
NA_index <- is.na(x)
x[NA_index] <- 50
}
mean(x)

[1] 55.99167
Example 1 Write a R code, result in “Yes” or “No”, to check if there is at
least a value in AirPassengers less than 125}

38 / 58
Control statements “If” and “else”
if (any(is.na(x))){
NA_index <- is.na(x)
x[NA_index] <- 50
}
mean(x)

[1] 55.99167
Example 1 Write a R code, result in “Yes” or “No”, to check if there is at
least a value in AirPassengers less than 125}
if (sum(AirPassengers<125) > 0){
print("Yes")
} else {
print("No")
}

[1] "Yes"
38 / 58
Control statements “Ifelse”
Similar to “If” statement in excel.
ifelse (sum(AirPassengers<125)>0,"Yes","No")

[1] "Yes"
Example 2 Vector x consists of values 0 and 1.
Create vector y identifying 1 is ”Head” and 0 is ”Tail”.

39 / 58
Control statements “Ifelse”
Similar to “If” statement in excel.
ifelse (sum(AirPassengers<125)>0,"Yes","No")

[1] "Yes"
Example 2 Vector x consists of values 0 and 1.
Create vector y identifying 1 is ”Head” and 0 is ”Tail”.
x<-c(0,0,1,1,0,1,1)
y<-ifelse(x==0,"Tail","Head")
x

[1] 0 0 1 1 0 1 1
y

[1] "Tail" "Tail" "Head" "Head" "Tail" "Head" "Head"

39 / 58
Control statements: Compound test

Symbol “&” stands for and while “|” stands for or operations in R.
Compound test result
TRUE & TRUE TRUE
TRUE & FALSE FALSE
FALSE & FALSE FALSE
TRUE | TRUE TRUE
TRUE | FALSE TRUE
FALSE | FALSE FALSE
(1==1)&(2>3)

[1] FALSE
(1==1)|(2>3)

[1] TRUE

40 / 58
For Loops

When we want to iterate over elements of a vector, list, or data.frame. To


print numbers from 1 to 8, we could use for loops as follows:
for (i in 1:8) {
print(i)
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8

41 / 58
For Loops

Example 1: Using for loops to calculate the following sums. Compare to


the one calculated by the vector forms.
1000
1
∑ = ?
𝑘=1
𝑘2
1000
1
∑ = ?
𝑘=1
𝑘!

42 / 58
For Loops

The vector in for loops does not have to be sequential; it can be any
vector.
myvector1 <- c("pie","banana","apple","mango")
for (s in myvector1) {
print(s)
}

[1] "pie"
[1] "banana"
[1] "apple"
[1] "mango"

43 / 58
While Loops

The code inside the braces runs repeatedly as long as the tested condition
is true.
x<-1
while(x<=5) {
print(x)
x<-x+1
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

44 / 58
Controlling Loops

A next statement is used inside a loop to skip the iterations and flow the
control to next step.
myvector1 <- c("pie","banana","apple","mango")
myvector2 <- vector(mode="numeric",length(myvector1))
for (i in 1:length(myvector1)) {
if (i==2){next}
myvector2[i] <- nchar(myvector1[i])
}
myvector2

[1] 3 0 5 5

45 / 58
Controlling Loops

A break statement is used inside a loop to stop the iterations and flow the
control outside of the loop.
myvector1 <- c("pie","banana","apple","mango")
myvector2 <- vector(mode="numeric",length(myvector1))

for (i in 1:length(myvector1)) {
if (i==2){break}
myvector2[i]<-nchar(myvector1[i])
}

myvector2

[1] 3 0 0 0

46 / 58
Controlling Loops

Using for loops to verify if 105 + 101 is a prime number ?


# Check if a number is prime
num <- 10^5+101
check <- TRUE
for (i in 2:(num-1)) {
if (num %% i == 0){
check <- FALSE
break}
}
if (check) {print("It is a prime number.")
} else {print("It isn't a prime number.")}

[1] "It isn't a prime number."

47 / 58
Writing functions
If we have to run the same code repeatedly, it is a good idea to turn it
into a function.
f <- function(x){ #h is a function of variable x
f <- x^3
}
print(f(3))

[1] 27
We can assign a value to the function or using return.
g <- function(x,y){ #g is a function of variables x, y
z = 2*x+y
return(z^2)
}
print(g(1,2))

[1] 16
48 / 58
Writing functions

Write functions of variable 𝑛, then evaluate them for 𝑛 = 5, 10, 15.


𝑛
1
𝑓1 (𝑛) = ∑
𝑘=1
𝑘2
𝑛
1
𝑓2 (𝑛) = ∑
𝑘=1
𝑘!

49 / 58
Writing functions
f1 <- function(n){
sum = 0 # Initialization
for (i in 1:n){
sum <- sum + 1/i^2
}
f1 <- sum # Always end by assigning a value to the function
}
print(f1(5))

[1] 1.463611
print(f1(10))

[1] 1.549768
print(f1(15))

[1] 1.58044
50 / 58
Writing functions

f2 <- function(n){
x <- 1:n
f2 <- sum(1/factorial(x))
}
print(f2(5))

[1] 1.716667

51 / 58
Writing functions - multivariable
Writing a function of 𝑛 and 𝑘
1𝑘 + 2𝑘 + 3𝑘 + ⋯ + 𝑛𝑘

f3 <- function(n,k){
sum=0
for (i in 1:n){
sum <- sum + i^k
}
return(sum)
}
print(f3(10,2))

[1] 385
system.time(f3(1e8,2))

user system elapsed


1.797 0.010 1.817
52 / 58
Writing functions - multivariable

Using vector class.


f4 <- function(n,k){
x <- 1:n
return(sum(x^k))
}
print(f4(10,2))

[1] 385
system.time(f4(1e8,2))

user system elapsed


0.359 0.342 0.885

53 / 58
Writing functions
𝑛 𝜋2
Example 1: Let 𝑓(𝑛) = ∑ 𝑘−2 . Show that lim 𝑓(𝑛) = by
𝑘=1 𝑛→∞ 6
calculating 𝑓(5),𝑓(10), 𝑓(15),⋯, 𝑓(100).

54 / 58
Writing functions
𝑛 𝜋2
Example 1: Let 𝑓(𝑛) = ∑ 𝑘−2 . Show that lim 𝑓(𝑛) = by
𝑘=1 𝑛→∞ 6
calculating 𝑓(5),𝑓(10), 𝑓(15),⋯, 𝑓(100).
f5 <- function(n){
tg=0
for (k in 1:n){tg <- tg+k^(-2)}
f5 <- tg
}
x <- 5*(1:20)
y <- vector(mode="numeric",length(x))
for (i in 1:length(x)){y[i]=f5(x[i])}
print(y[15:20])

[1] 1.631689 1.632512 1.633238 1.633884 1.634463 1.634984

54 / 58
Writing functions
plot(x,y,ylim = c(1.4,1.7),type="b")
abline(h=pi^2/6,col=2)
1.70
1.65
1.60
1.55
y

1.50
1.45
1.40

20 40 60 80 100
55 / 58
Writing functions

𝑛 1
Example 2: Let 𝑓(𝑛) = ∑ . Show that lim 𝑓(𝑛) = 𝑒 by calculating
𝑘=0 𝑘! 𝑛→∞
𝑓(1),𝑓(2), 𝑓(3),⋯, 𝑓(10).

56 / 58
Writing functions

𝑛 1
Example 2: Let 𝑓(𝑛) = ∑ . Show that lim 𝑓(𝑛) = 𝑒 by calculating
𝑘=0 𝑘! 𝑛→∞
𝑓(1),𝑓(2), 𝑓(3),⋯, 𝑓(10).
f6 <- Vectorize(function(n){
x <- 0:n
f6 <- sum(1/factorial(x))
})
x <- 1:10
y <- f6(x)
print(y)

[1] 2.000000 2.500000 2.666667 2.708333 2.716667 2.718056 2.7


[9] 2.718282 2.718282

56 / 58
Writing functions
plot(x, y, ylim = c(1.8,3), type="b")
abline(h=exp(1), col=2)
3.0
2.8
2.6
2.4
y

2.2
2.0
1.8

2 4 6 8 10
57 / 58
Writing functions
Example 3: Write a function to solve the equation 𝑎𝑥2 + 𝑏𝑥 + 𝑐 = 0.

58 / 58
Writing functions
Example 3: Write a function to solve the equation 𝑎𝑥2 + 𝑏𝑥 + 𝑐 = 0.
f<-function(a, b, c){
D <- b^2 - 4*a*c
if (D < 0){tg <- "No solution"}
if (D == 0){tg <- -b/(2*a)}
if (D > 0){tg <- c((-b-sqrt(D))/(2*a), (-b+sqrt(D))/(2*a))
f <- tg
}
print(f(1,1,1))#x^2+x+1 = 0

[1] "No solution"


print(f(1,-2,1))#x^2-2x+1 = 0

[1] 1
print(f(1,-4,3))#x^2-4x+3 = 0

[1] 1 3
58 / 58

You might also like