Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

Introduction to R for

Finance

Profesor: Juan Manuel Gómez González


What is computational finance?

Computational finance is a branch of applied


computer science that deals with problems of
practical interest in finance. Some slightly different
definitions are the study of data and algorithms
currently used in finance and the mathematics of
computer programs that realize financial models or
systems.
Computational finance VS Quantitative finance

Computational finance as a discipline emerged in the


1980s. It is also sometimes referred to as
"financial engineering," "financial mathematics,"
"mathematical finance," or "quantitative
finance." It uses the tools of mathematics, statistics,
and computing to solve problems in finance.
What are the computational tools?

Computational tools are the implemented


techniques in computers to solve problems by
either step-wise, repeated, and iterative solution
methods; also known as in-silico methods.
What else are the computational tools?
Introduction to R for Finance
Objective:
▪ You will master the basics of this widely used open-source language,
including vectors, factors, lists, and data frames.

▪ With the coding skills you'll gain in this introduction, you'll be ready to
undertake your own data analysis for finance in R.

What do we need?:

▪ R and R Studio.
Installation of R

▪ R is a free software environment for


statistical computing and graphics. It
compiles and runs on a wide variety of
UNIX platforms, Windows and MacOS.
https://www.r-project.org/
Installation of R Studio

▪ RStudio is an integrated development


environment for R, a programming
language for statistical computing and graphics. It
is available in two formats: RStudio Desktop is a
regular desktop application while RStudio Server
runs on a remote server and allows accessing
RStudio using a web browser.

https://posit.co/download/rstudio-desktop/
Source of Information

▪ Introducción a R. Notas sobre R: Un entorno de


programación para Análisis de Datos y Gráficos.
(https://cran.r-project.org/doc/contrib/R-intro-1.1.0-
espanol.1.pdf).

▪ R for Data Science.


https://r4ds.had.co.nz/

▪ Würtz et al. (2010). Basic R for finance. R metrics


Association & Finance Online.
(https://genes.bibli.fr/doc_num.php?explnum_id=17689)
Programming in R
Tools - Functions

Raw material– Data

Package selected –
library( )

Instructive - Script

Artboard – R Console

Tool Boxes - Packages


Introduction to R for Finance
Intro to basics: Scripts and Consoles

▪ R makes use of the # sign to add comments.

▪ There are two consoles: Editor(Scripts) and output


Introduction to R for Finance
Intro to basics: Arithmetic with R

▪ In its most basic form, R can be used as a simple calculator..

o Addition: +
o Subtraction: -
o Multiplication: *
o Division: /
o Exponentiation: ^
o Modulo: %%
Introduction to R for Finance
Intro to basics: Variable assignment

▪ A basic concept in (statistical) programming is called a variable.

▪ A variable allows you to store a value (e.g., 4) or an object (e.g., a function


description) in R.

▪ You can then later use this variable's name to easily access the value or the
object that is stored within this variable.
Introduction to R for Finance
Intro to basics: Assignment 1

▪ Suppose you have a fruit basket with five apples. As a data analyst in
training, you want to store the number of apples in a variable.

▪ Every tasty fruit basket needs oranges, so you decide to add six oranges.
As a data analyst. Next, you want to calculate how many pieces of fruit you
have in total.

▪ Common knowledge tells you not to add apples and oranges. If you really
tried to add "apples" and "oranges" and assigned a text value (“six”) to the
variable oranges, you would be trying to assign the addition of a numeric
and a character variable.
Introduction to R for Finance
Intro to basics: Basic data types in R

▪ R works with numerous data types. Some of the most basic types to get
started are:
o Decimal values like 4.5 are called numerics.
o Whole numbers like 4 are called integers. Integers are also numerics.
o Text (or string) values are called characters.

▪ You can do this with the class() function, as the code in the editor shows.
Introduction to R for Finance
A little more advance: Interest Rate

Define: Suppose we have a nominal interest rate of 2% per month that is compounded monthly. In this case,
the frequency of compounding is n=12 (12 months in a year). Then, the above formula can be used to calculate R:

Create a function to
switch from annual
effective rates to
nominal or periodic
rates
Introduction to R for Finance
Vectors

▪ Vectors are one-dimension arrays that can hold numeric data, character
data, or logical data.

▪ In R, you create a vector with the combine function c(). You place the vector
elements separated by a comma between the parentheses.
Introduction to R for Finance
Vectors: Arithmetic calculations on vectors.

▪ It is important to know that if you sum two vectors in R, it takes the element-
wise sum. For example, the following three statements are completely
equivalent:

▪ You can also do the calculations with variables that represent vectors:

▪ The function sum() calculates the sum of all elements of a vector.


Introduction to R for Finance
Vectors: Assignment 2
▪ After one week in Las Vegas, you decide that it is time to start using your data analytical
superpowers. Before doing a first analysis, you decide to first collect all the winnings and losses for
the last week:

o For poker: On Monday you won $140, Tuesday you lost $50, Wednesday you won $20, Thursday
you lost $120, and Friday you won $240

o For roulette: On Monday you lost $24, Tuesday you lost $50, Wednesday you won $100,
Thursday you lost $350, Friday you won $10

▪ Give a name to the elements of each vector with the names() function.

▪ How much did you win or lose each day (poker and roulette combined)?

▪ Calculate the total amount of money that you have won/lost with roulette and poker and the totals for
both.

▪ Check if you realized higher total gains in poker than in roulette


Introduction to R for Finance
Vectors - select specific elements of the vector

▪ To select elements of a vector, you can use square brackets. Between the
square brackets, you indicate what elements to select.

▪ To select multiple elements from a vector, you can add parentheses in the
middle of the square brackets. You must indicate between the parentheses
what elements should be selected.
Introduction to R for Finance
Vectors - Select specific elements of the vector

▪ Another way to tackle the previous exercise is by using the names of the
vector elements (Monday, Tuesday, …) instead of their numeric positions.

▪ You can calculate the mean of the vector or a selection using the function
mean().
Introduction to R for Finance
Vectors - Selection by comparison

▪ The (logical) comparison operators known to R are:


o < for less than
o > for greater than
o <= for less than or equal to
o >= for greater than or equal to
o == for equal to each other
o != not equal to each other

▪ You can use these comparison operators also on vectors. This command
tests for every element of the vector if the condition stated by the
comparison operator is TRUE or FALSE.
Introduction to R for Finance
Vectors - Selection by comparison

▪ Additionally, you can simply ask R to return only those days where you
realized an effective comparison.

▪ You can select the desired elements, by putting a selection vector between
the square brackets that follow interest vector.

▪ R knows what to do when you pass a logical vector in square brackets: it


will only select the elements that correspond to TRUE in selection vector.
Introduction to R for Finance
Vectors: Assignment 3

▪ Check which elements in poker and roulette vector are positive and assign
this to a selection vector.

▪ Use a selection vector in square brackets to assign the amounts that you
won on the profitable days to a variable that indicate the poker and roulette
winning days.
Introduction to R for Finance
Matrix

▪ In R, a matrix is a collection of elements of the same data type (numeric,


character, or logical) arranged into a fixed number of rows and columns.

▪ Since you are only working with rows and columns, a matrix is called two-
dimensional.

▪ You can construct a matrix in R with the matrix() function.


Introduction to R for Finance
Matrix

▪ Consider the following example:

o The first argument is the collection of elements that R will arrange into the rows and
columns of the matrix. Here, we use 1:9 which is a shortcut for c(1, 2, 3, 4, 5, 6, 7, 8, 9).

o The argument byrow indicates that the matrix is filled by the rows. If we want the matrix
to be filled by the columns, we just place byrow = FALSE.

o The third argument nrow indicates that the matrix should have three rows.
Introduction to R for Finance
Matrix – naming, sum rows and column.
▪ Similar to vectors, you can add names for the rows and the columns of a matrix:

▪ In R, the function rowSums() conveniently calculates the totals for each row of a matrix.
This function creates a new vector:

▪ In the same way, the function colSums() calculates the totals for each column of a matrix.
This function creates a new matrix of one row and n columns.
Introduction to R for Finance
Matrix – Adding rows and Selection of matrix elements
▪ You can add a column or multiple columns to a matrix with the cbind() function, which merges matrices
and/or vectors together by column. For example:

▪ You can add a row or multiple rows to a matrix with the rbind() function, which merges matrices and/or
rows together.

▪ You can use the square brackets [ ] to select one or multiple elements from a matrix. Whereas vectors
have one dimension, matrices have two dimensions. You should therefore use a comma to separate the
rows you want to select from the columns. For example:

o My_matrix[1,2] selects the element at the first row and second column.
o my_matrix[1:3,2:4] results in a matrix with the data on the rows 1, 2, 3 and columns 2, 3, 4.

▪ If you want to select all elements of a row or a column, no number is needed before or after the comma,
respectively:

o My_matrix[,1] selects all elements of the first column.


o My_matrix[1,] selects all elements of the first row.
Introduction to R for Finance
Matrix – arithmetic with matrices.
▪ Similar to what you have learned with vectors, the standard operators like +,
-, /, *, etc. work in an element-wise way on matrices in R.

o For example, 2 * my_matrix multiplies each element of my_matrix by two.

▪ my_matrix1 * my_matrix2 creates a matrix where each element is the


product of the corresponding elements in my_matrix1 and my_matrix2.

o Those who are familiar with matrices should note that this is not the standard matrix
multiplication for which you should use %*% in R.
Introduction to R for Finance
Matrix - Assignment 4
▪ Consider the box office numbers from the first three Star Wars movies. New Hope (460.9, 314.4),
Empire Strikes (290.4, 247.9), and Return Jedi (309.3, 165.8).

▪ The first element indicates the US box office revenue, the second element refers to the Non-US
box office (source: Wikipedia).

o Combine all these figures into a single vector.


o Build a matrix from this vector.

▪ Construct two vectors with for region and title.

▪ Name the columns and rows of star wars matrix

▪ Calculate the worldwide box office figures for the three movies and put these in a vector.

▪ Add the worldwide box office as a new column to the star wars matrix and assign the result a new
name.
Introduction to R for Finance
Matrix - Assignment 4
▪ Now, Consider the box office with similar data for the prequel's trilogy. The Phantom Menace (474.5,
552.5), Attack of the Clones (310.7 , 338.7), and Revenge of the Sith (380.3 , 468.5).

▪ The first element indicates the US box office revenue, the second element refers to the Non-US
box office (source: Wikipedia).

o Combine all these figures into a single vector.


o Build a matrix from this vector.
o Construct two vectors with for region and title.
o Name the columns and rows of star wars matrix.

▪ Paste together both star wars matrices.

▪ Calculate the total revenue for the US and the non-US region.

▪ Select the non-US revenue for all movies and calculate its average.

▪ Select the non-US revenue for the first two movies and calculate its average.
Introduction to R for Finance
Matrix - Assignment 4
▪ How many visitors went to each movie for each geographical area. Assume that the price of a ticket
was 5 dollars.

▪ Prices were not the same for each movie and region. Prices for each movie and region were:

o A New Hope 5.0 5.0


o The Empire Strikes Back 6.0 6.0
o Return of the Jedi 7.0 7.0
o The Phantom Menace 4.0 4.0
o Attack of the Clones 4.5 4.5
o Revenge of the Sith 4.9 4.9

▪ Find the actual number of visitors by movie

▪ Generate a matrix with the US visitors

▪ Calculate the average US visitors


Time Value of Money (TVM)
Time Value of Money (TVM)

The TVM is a fundamental concept in finance and economics


that recognizes the relationship between time, money, and the
earning power of money. It is based on the idea that a sum of
money available today is worth more than the same amount
of money at some point in the future.

The concept of the time value of money is used to analyze a


wide range of financial decisions, including investments,
loans, and savings.
Estimate Present Value
Estimate Present Value
Calculate the present value of a cash flow stream with an annual
interest rate of 5%, a cash flow of $100 per year for 5 years, and a
discount rate of 5%:
Estimate Future Value
Estimate Future Value
Suppose you want to calculate the future value of an investment
that you plan to make. You have $10,000 to invest, and you expect
to receive an annual interest rate of 5% over a period of 10 years.
You want to know the future value of this investment after 10 years.
Estimate Period Payment
Estimate the Number of Periods
Computing the Rate of Return

You might also like