0% found this document useful (0 votes)
9 views61 pages

R Programming Basics for Finance

Uploaded by

Syed Shafiulla
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)
9 views61 pages

R Programming Basics for Finance

Uploaded by

Syed Shafiulla
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

A Probability and Statistics Primer

for Quantitative Finance

Week 1: R Usage

Kjell Konis
Acting Assistant Professor, Computational Finance and Risk Management
University of Washington

1 / 61
Outline

Installing R and R Studio

Basic R Usage
R is an Array Programming Language
Subsetting Vectors

Installing and Loading R Packages

The R Help System

Plotting

Additional Resources

2 / 61
Outline

Installing R and R Studio

Basic R Usage
R is an Array Programming Language
Subsetting Vectors

Installing and Loading R Packages

The R Help System

Plotting

Additional Resources

3 / 61
What is R?
R is a language and environment for statistical computing and graphics

R provides . . .
I a wide variety of statistical (linear and nonlinear modeling, classical statistical
tests, time-series analysis, classification, clustering, . . . ) techniques
I a wide variety of graphical techniques
I and is highly extensible

R is available as Free Software under the terms of the Free Software Foundation’s GNU
General Public License (either Version 2 or Version 3)

R runs on Linux, Windows, and Mac OS

4 / 61
Installing R
The R installer is available from the R Project website
[Link]

After installing R, run the command


> demo("graphics")
in the R Console as a quick check that things are working

5 / 61
What is R Studio?
R Studio is an integrated development environment (IDE) for R

R Studio includes . . .
I a console
I a syntax-highlighting editor that supports direct code execution
I tools for plotting, history, debugging and workspace management

R Studio is available in an open source (i.e., free) edition – license = AGPL v3

R Studio also runs on Linux, Windows, and Mac OS

6 / 61
Installing R Studio
The R Studio installer is available from the R Studio website
[Link]

After installing R Studio, run the command


> demo("graphics")
in the R Studio Console as a quick check that things are working

7 / 61
Outline

Installing R and R Studio

Basic R Usage
R is an Array Programming Language
Subsetting Vectors

Installing and Loading R Packages

The R Help System

Plotting

Additional Resources

8 / 61
The R Console
The > symbol is called the prompt: R is prompting you to enter a command
R as a calculator: input the command 1 + 1 at the prompt and press return
> 1 + 1

The result appears on the next line


[1] 2

R can replace your 4 function calculator (R follows the usual order of operations)
+ addition - subtraction ^ power
* multiplication / division

Comments: any input following a # is ignored (until the next new line)

9 / 61
Mathematical Functions
R includes a wide variety of mathematical functions
For example, the log function returns the natural logarithm of its argument
> log(5)
[1] 1.609438

Some commonly used functions are given in the following table

log logarithm exp exponential


sin sine asin inverse sine
cos cosine acos inverse cosine
tan tangent atan inverse tangent
sqrt square root

Note: trigonometric functions use radians

10 / 61
Constants and Special Values

Constants Special Values

Exponential base: e 1 Plus and minus infinity


> exp(1) > 1/0
[1] 2.718282 [1] Inf

π > log(0)

> pi [1] -Inf

[1] 3.141593 Not a Number


> 0/0
[1] NaN

11 / 61
Caveats
Numerical calculations in R are done using double precision arithmetic
Double precision arithmetic is not real arithmetic
I There are a finite number of double precision numbers
I Input numbers are coerced to the most appropriate double precision number

Leads to unexpected behavior


> (1/3)^2 - 1 / (3^2)
[1] 0

But . . .
> (1/3)^3 - 1 / (3^3)
[1] -6.938894e-18
12 / 61
Variables
Values (e.g., the output of a function) can be saved in memory, this chunk of memory
is called a variable
For example, suppose we want to evaluate sin( π2 )
π
First, evaluate 2 and store the result
> u <- pi / 2
The assignment operator in R is <-, it assigns the value on the right to the variable on
the left
Second, compute the value of sin(u)
> (v <- sin(u))
[1] 1

13 / 61
Variable Names
Variable names need/should conform to the following guidelines
I Variable names need to start with a character
I Variable names can contain characters, numbers, periods, and underscores
I Variable names cannot be an R reserved word
if else repeat while function
for in next break TRUE
FALSE NULL Inf NaN NA
...

I Best practice: variable names should not be the name of a common R function
I Some common collisions are c, t, mean, var, and cov

14 / 61
Workspace Management
Variables are stored in R’s workspace
Use the ls function to list the variables in the workspace
> ls()
[1] "u" "v"
Use the rm function to remove variables from the workspace
> rm(u)
> ls()
[1] "v"

R asks to save the workspace when quitting, saved workspaces are automatically
restored the next time R starts

15 / 61
Outline

Installing R and R Studio

Basic R Usage
R is an Array Programming Language
Subsetting Vectors

Installing and Loading R Packages

The R Help System

Plotting

Additional Resources

16 / 61
What is an Array Programming Language?
An array programming language generalizes operations to apply transparently to single
and multi-dimensional arrays
In R . . .
I a one dimensional array is called a vector
I a two dimensional array is called a matrix
I Higher dimensional arrays are possible but we are not going to use them

A goal of array programming is to provide a syntax similar to mathematical notation


I Very useful for programming with data

17 / 61
Vectors
A vector is an ordered collection of n values with the same underlying type

Example: suppose the vector u = (u1 , u2 ) describes a point in the xy -plane


I Both u1 and u1 should be real numbers
I Since the first value defines the x coordinate and the second value the y
coordinate, the vector (u1 , u2 ) is (in general) different than the vector (u2 , u1 )

The number of values in the vector is called the length of the vector

Supported types include


I numeric
I character
I ...

18 / 61
Creating Vectors
The function c combines values into a vector
> (primes <- c(2, 3, 5, 7))
[1] 2 3 5 7

The function length returns the length of the input vector


> length(primes)
[1] 4

The function seq creates sequences of equally-space values


> seq(-1, 1, 0.5)
[1] -1.0 -0.5 0.0 0.5 1.0

19 / 61
Naming Vector Components
The = operator assigns a name to a value
Names can be given to the components of a vector
> [Link] <- c(houses = 3, cars = 5, boats = 2)
> [Link]
houses cars boats
3 5 2

The names function returns the names of the components of a vector


> names([Link])
[1] "houses" "cars" "boats"

Remark: assigning a name to a value (=) often has the same effect as assigning a value
to a variable (<-) =⇒ = and <- can be used interchangeably
20 / 61
Matrices
A matrix is a two dimensional array of values (of the same type) described by a
number of rows and a number of columns
The function cbind combines vectors (with the same length) into a matrix
> col1 <- c(11, 21, 31, 41)
> col2 <- c(12, 22, 32, 42)
> (mat <- cbind(col1, col2))
col1 col2
[1,] 11 12
[2,] 21 22
[3,] 31 32
[4,] 41 42

21 / 61
Component-wise Operations on Vectors
What does it mean to
. . . generalize operations to apply transparently to single and
multi-dimensional arrays

When a vector is provided as the argument of a function, the output is a vector


containing the function applied to each component of the input vector

> (x <- 1:9) # x <- seq(1, 9, 1)


[1] 1 2 3 4 5 6 7 8 9
> sqrt(x)
[1] 1.000 1.414 1.732 2.000 2.236 2.449 2.646 2.828 3.000

22 / 61
Component-wise Composite Functions
Shifting: adding a length n vector and a length 1 vector
> x
[1] 1 2 3 4 5 6 7 8 9
> x + 2
[1] 3 4 5 6 7 8 9 10 11

Scaling: multiplying a length n vector by a length 1 vector

> 3*x
[1] 3 6 9 12 15 18 21 24 27

23 / 61
Element-wise Composite Functions
Functions act element-wise on matrices
> mat
col1 col2
[1,] 11 12
[2,] 21 22
[3,] 31 32
[4,] 41 42

> 3*mat + 2
col1 col2
[1,] 35 38
[2,] 65 68
[3,] 95 98
[4,] 125 128
24 / 61
Outline

Installing R and R Studio

Basic R Usage
R is an Array Programming Language
Subsetting Vectors

Installing and Loading R Packages

The R Help System

Plotting

Additional Resources

25 / 61
Logical-Valued Functions
Logical values in R are TRUE and FALSE
Functions with a yes/no output generally return logical values

> x
[1] 1 2 3 4 5 6 7 8 9

> x > 4
[1] FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE

> ([Link].4 <- x >= 4)


[1] FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE TRUE

> x == 4 # Remember the double precision caveat


[1] FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE
26 / 61
Logical Vectors
The variable [Link].4 is a logical vector, that is
I it is a vector
I the underlying type of value is logical

Lets create a second logical vector


> ([Link].7 <- x <= 7)
[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE

27 / 61
Operations on Logical Vectors
Three key operations for logical vectors: & (AND), | (OR), and ! (NOT)
Suppose that x and y are logical vectors with the same length

AND: ans <- x & y


ansi is TRUE if both xi and yi are TRUE, otherwise ansi is FALSE
> [Link].4
[1] FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE TRUE
> [Link].7
[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE

> [Link].4 & [Link].7


[1] FALSE FALSE FALSE TRUE TRUE TRUE TRUE FALSE FALSE

28 / 61
Operations on Logical Vectors (continued)
OR: ans <- x | y
ansi is FALSE if both xi and yi are FALSE, otherwise ansi is TRUE

> [Link].4
[1] FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE TRUE
> [Link].7
[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE

> [Link].4 | [Link].7


[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE

29 / 61
Operations on Logical Vectors (continued)
NOT: ans <- !x
ansi is FALSE if xi is TRUE, otherwise ansi is TRUE

> [Link].4
[1] FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE TRUE

> ![Link].4
[1] TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE

30 / 61
Subsetting Vectors
The subset operator in R is square brackets: []
If
I x is a vector (with any underlying type)
I idx is a logical vector the same length as x
then x[idx] is a vector (with the same underlying type as x) containing the
components of x for which idx is TRUE

> x[[Link].4]
[1] 4 5 6 7 8 9

> x[[Link].7]
[1] 1 2 3 4 5 6 7

31 / 61
Subsetting Vectors – More Examples
> x[x < 6]
[1] 1 2 3 4 5

> x[x > 2 & x < 8]


[1] 3 4 5 6 7

> x[x <= 2 | x >= 8]


[1] 1 2 8 9

> x[!(x == 3 | x == 6)]


[1] 1 2 4 5 7 8 9

32 / 61
Subsetting Vectors by Index
Suppose that x is a vector of length n
Let idx be a vector of values from the set {1, 2, . . . , n}
The vector ans <- x[idx] is the same length as idx and has components
ansi = xidxi

> primes
[1] 2 3 5 7

> primes[c(2, 4)]


[1] 3 7

From now on: write ans[i] to mean ansi

33 / 61
Outline

Installing R and R Studio

Basic R Usage
R is an Array Programming Language
Subsetting Vectors

Installing and Loading R Packages

The R Help System

Plotting

Additional Resources

34 / 61
R Packages
An R package is a collection of functions and data (and . . . )
=⇒ loading a package into your R session extends the capabilities of R

Packages loaded by default


> search()
[1] ".GlobalEnv" "package:stats" "package:graphics"
[4] "package:grDevices" "package:utils" "package:datasets"
[7] "package:methods" "Autoloads" "package:base"

For the curious: use the find function to see what package provides an object
> find("log")
[1] "package:base"

35 / 61
Loading R Packages
Later in the course, we will use the fitdistr function from the MASS package
MASS is a recommended package, it is already installed on your computer
The library function loads and attaches packages to the R session
> library(MASS)
The functions and data provided by the MASS package are now available to the R
session
> search()
[1] ".GlobalEnv" "package:MASS" "package:stats"
[4] "package:graphics" "package:grDevices" "package:utils"
[7] "package:datasets" "package:methods" "Autoloads"
[10] "package:base"
> find("fitdistr")
[1] "package:MASS"
36 / 61
Installing R Packages
The extensive collection of user-contributed packages is one of the reasons for the
popularity of R
The Comprehensive R Archive Network (CRAN) is a clearing house for
user-contributed packages
The [Link] function downloads packages from CRAN and installs them
on your computer
The getSymbols function on the quantmod package will be the primary source of
price data used in this course
> [Link]("quantmod")
The package must be loaded and attached to the R session
> library("quantmod")
> find("getSymbols")
[1] "package:quantmod"
37 / 61
Summary R Packages
Installing a package means downloading the package from CRAN and installing it on
the computer
Installing only needs to be done once (per computer)

Loading and attaching a package means telling the R session to look for functions
(data, etc.) in the package
Loading and attaching needs to be done in each R session

38 / 61
Outline

Installing R and R Studio

Basic R Usage
R is an Array Programming Language
Subsetting Vectors

Installing and Loading R Packages

The R Help System

Plotting

Additional Resources

39 / 61
Getting Help
The log function returns the natural logarithm of its argument
How were we supposed to know that?
The help function displays the documentation associated with an object
> help(log)

Documentation is divided into sections including


Description a description of the function or functions
Usage how to call the function
Arguments supported types of arguments
Details additional explanation if needed
Value a description of the returned object
See Also related functions
Examples
40 / 61
Description

`log' computes logarithms, by default natural logarithms, `log10'


computes common (i.e., base 10) logarithms, and `log2' computes
binary (i.e., base 2) logarithms. The general form `log(x, base)'
computes logarithms with base `base'.

`log1p(x)' computes log(1+x) accurately also for |x| << 1.

`exp' computes the exponential function.

`expm1(x)' computes exp(x) - 1 accurately also for |x| << 1.

41 / 61
Usage

log(x, base = exp(1))


logb(x, base = exp(1))
log10(x)
log2(x)

log1p(x)

exp(x)
expm1(x)

42 / 61
Arguments

x: a numeric or complex vector.

base: a positive or complex number: the base with respect to which


logarithms are computed. Defaults to e=`exp(1)'.

43 / 61
Details

All except `logb' are generic functions: methods can be defined


for them individually or via the `Math' group generic.

`log10' and `log2' are only convenience wrappers, but logs to


bases 10 and 2 (whether computed _via_ `log' or the wrappers) will
be computed more efficiently and accurately where supported by the
OS. Methods can be set for them individually (and otherwise
methods for `log' will be used).

`logb' is a wrapper for `log' for compatibility with S. If (S3 or


S4) methods are set for `log' they will be dispatched. Do not set
S4 methods on `logb' itself.

All except `log' are primitive functions.

44 / 61
Value

A vector of the same length as `x' containing the transformed


values. `log(0)' gives `-Inf', and `log(x)' for negative values
of `x' is `NaN'. `exp(-Inf)' is `0'.

For complex inputs to the log functions, the value is a complex


number with imaginary part in the range [-pi, pi]: which end of
the range is used might be platform-specific.

45 / 61
Outline

Installing R and R Studio

Basic R Usage
R is an Array Programming Language
Subsetting Vectors

Installing and Loading R Packages

The R Help System

Plotting

Additional Resources

46 / 61
The plot Function
The plot function produces scatter plots

Usage:

plot(x, y, ...)

The points are (xi , yi ), the argument x is a vector containing the x values and y is a
vector (the same length as x) containing the y values
The ... is a placeholder for optional arguments

Example:
> x <- seq(0.1, 5, 0.1)
> y <- log(x)

47 / 61
Plot with Defaults
> plot(x, y)

1
0
y

−1
−2

0 1 2 3 4 5

x 48 / 61
Optional Arguments: type
> plot(x, y, type = "l")

1
0
y

−1
−2

0 1 2 3 4 5

x 49 / 61
Optional Arguments: Axis Labels
> plot(x, y, xlab = "x-axis label", ylab = "y-axis label")

1
y−axis label

0
−1
−2

0 1 2 3 4 5

x−axis label 50 / 61
Optional Arguments: Title
> plot(x, y, main = "Plot Main Title")

Plot Main Title


1
0
y

−1
−2

0 1 2 3 4 5

x 51 / 61
Optional Arguments: Plotting Region
> plot(x, y, xlim = c(-1, 6), ylim = c(-3, 3))

3
2
1
0
y

−3 −2 −1

−1 0 1 2 3 4 5 6

x 52 / 61
Optional Arguments: Setting the Aspect Ratio
> plot(x, y, asp = 1)

1
0
y

−1
−2

−2 0 2 4 6

x 53 / 61
Optional Arguments: Plotting Symbol
> plot(x, y, pch = 16)

1
0
y

−1
−2

0 1 2 3 4 5

x 54 / 61
Optional Arguments: Color
> plot(x, y, col = "blue")

1
0
y

−1
−2

0 1 2 3 4 5

x 55 / 61
Square Plotting Region
> par(pty = "s")
> plot(x, y)

1
0
y

−1
−2

0 1 2 3 4 5
56 / 61
Object-Oriented Plotting
R is an object-oriented programming language =⇒ behavior of the plot function
depends on what x is
If x is a vector then we get a scatter plot
If x is a financial prices series
> getSymbols("SBUX")
[1] "SBUX"
The variable SBUX contains 10 years of price data for Starbucks

57 / 61
Plotting a Price Series
> plot(SBUX)

SBUX
100
80
60
40
20

Jan 03 Jul 01 Jan 04 Jul 01 Jan 02 Jul 01 Dec 31


2007 2008 2010 2011 2013 2014 2015
58 / 61
Outline

Installing R and R Studio

Basic R Usage
R is an Array Programming Language
Subsetting Vectors

Installing and Loading R Packages

The R Help System

Plotting

Additional Resources

59 / 61
Additional Resources for Learning R
CFRM 463: R Programming for Quantitative Finance course materials
[Link]

DataCamp: The easiest way to learn R programming and data science


[Link]

60 / 61
[Link]

61 / 61

You might also like