Lec1.Introduction
Lec1.Introduction
Stochastic Simulation
and Applications in Finance
1 / 58
Course outline
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
[1] 3.25
rm(x)
x
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
[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
[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] 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
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
[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] 3
any(x==1)
[1] TRUE
all(x==1)
[1] FALSE
22 / 58
Basics of R - vertors (7)
23 / 58
Basics of R - vertors (7)
[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)
24 / 58
Basics of R - operations between vectors (2)
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)
[1] 7 12 15 16 15 12 7
x<y
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] 2 4 6 NA 10 NA
x>3
[1] NA 4 NA NA 25 NA
30 / 58
Basics of R - often used functions with vectors
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
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")
}
if (sum(is.na(Nile))==0){
print("There isn't any NA value in data Nile")
}
37 / 58
Control statements “If”
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
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
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
41 / 58
For Loops
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
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
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))
[1] 385
system.time(f4(1e8,2))
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])
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)
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] 1
print(f(1,-4,3))#x^2-4x+3 = 0
[1] 1 3
58 / 58