8 Exercises
8.1 Related to Chapters 1 to 6
1. Write an R code to determine the result of the following computation:
\[ e^{\pi}\left( \log_2(10) + \frac{5^2 + \sin(8)}{\sqrt{2}}\right)^{-3} \,. \]
2. Without using R, determine the result of the following logical computation
((!(4 == 3) | (abs(-3) <= 2)) & ((2^2 > 4) & (TRUE))) | ((!FALSE | (4+2) == 5) & (0.5 >= (1/2)))
Verify your result by typing the code in R.
3. Find the errors in the following lines of code:
- \(\,\)
2 + 3 *4 + sqrt[100]
- \(\,\)
(2 + i) / 3 + {1e1 + 4.0i}
- \(\,\)
time.To.Maturity <- 6
Interest.rate <- 0.05
{1e-0 + interest.rate}^{-time.To.Maturity}
4. Without using R, determine the result of the following computation:
x <- c(1, 2, 3)
x[2] / x[2]^2 - 1 + 3 * x[3] - x[2 - 1]
Verify your result by typing the code in R.
5. Write an R code to calculate the amount of money owed after \(n\) years, where \(n\) varies from \(1\) to \(10\) in yearly increments, assuming that the money lent originally is \(2350\) and the interest rate remains constant throughout the period at \(5\%\).
6. Consider the vector 1:N, where N is a positive integer. Write an R code that determines how many elements in the vector are exactly divisible by \(4\). Test your code with N <- 40.
7. Compute the mean of:
- \(v=(0, 1, NA, 2, 7).\)
- \(u=(-Inf, 0, 1, NA, 2, 7, Inf).\)
8. Create:
a vector with values \(e^x\cos(x)\) at \(x=3, 3.1, 3.2, \ldots, 6.\)
a vector with values \(\left(2,\frac{2^2}{2},\frac{2^3}{3}, \ldots, \frac{2^{25}}{25}\right).\)
9. Compute:
\[\sum_{j=10}^{100}{j^3+4j^2}.\]
\[\sum_{j=1}^{25}{\frac{2^j}{j}+\frac{3^j}{j^2}}.\]
10. Create the vectors:
- \((1,2,3,\ldots,19,20)\).
- \((20,19,\ldots,2,1)\).
- \((1,2,3,\ldots,19,20,19,18,\ldots,2,1)\).
- \((1,2,3, 1,2,3,\ldots,1,2,3)\) where there are 10 occurrences of 1.
- \((1,1,\ldots,1, 2,2,\ldots,2, 3,3,\ldots,3)\) where there are 10 occurrences of 1, 20 occurrences of 2 and 30 occurrences of 3.
- \((0.1^30.2^1,0.1^60.2^4,\ldots,0.1^{36}0.2^{34})\).
11. Use the function paste to create the following character vector of length 20:
\[ \left(\text{"label 1"},\text{"label 2"},\ldots,\text{"label 20"}\right) \]
12. Set the vector v2 equal to the following: “A” “A” “B” “B” “C” “C” “D” “D” “E” “E” (note the letters are all uppercase).
13. Set the vector v3 equal to the following: “a” “b” “c” “d” “e” “a” “b” “c” “d” “e” (note the letters are all lowercase).
14. Set the vector v4 equal to the words “dog” 10 times, “cat” 9 times, “fish” 6 times, and “fox” 1 time.
15. Run the following lines:
Explain the meaning of x and y.
Denote by \(x_i\) and \(y_i\) the entries of the vectors \(x\) and \(y\), respectively. Create vectors \((y_2-x_1,\ldots,y_n-x_{n-1})\) and \(\left(\frac{\sin(y_1)}{\cos(x_2)},\ldots,\frac{\sin(y_{n-1})}{\cos(x_n)}\right).\)
Compute \[ \sum_{i=1}^{n-1}\frac{e^{-x_{i+1}}}{x_i+10}.\]
Denote by \(\overline{x}\) the mean of the vector \(x\) and compute \[\sum_{i=1}^n|x_i-\bar{x}|^{1/2}.\]
Extract the values of \(x\) which correspond to the values of \(y\) which are \(> 500\).
How many values of \(x\) are above the mean of \(y\)?
How many values of \(x\) are smaller than the minimum value of \(y\)?
How many values of \(x\) are divisible by \(2\)?
Extract the 1st minimum value of \(x\), the 4th minimum value of \(x\), the 7th minimum value of \(x\), etc.
16. Create a random sequence of length 100 taking values “low”, “medium” and “high”. Consult the help of sample.
17. Create a vector containing the following student grades: 70, 80, 55, 67, 90, 92, 83, 74, 100, 87, 49. Using logical operators and vector functions, answer the following question:
- What is the average grade of the whole group?
- How many students have grades less than 65?
- What is the average grade of those students with grades between 60 and 80 (including 60 and 80)?
- Assume that we add three new students with grades 65, 98, 54. Repeat questions a)-c) with the new vector of grades.
18. Write an R program to compute the alternating harmonic series \[ 1 - \frac{1}{2} + \frac{1}{3} - \frac{1}{4} + \cdots = \sum_{n = 1}^{\infty } \frac{(-1)^{n-1}}{n} \,, \] up to a finite number of summands \(N\). Test your code with \(N = 100\) and compare with \(\log(2)\).
19. The function cov() computer the sample covariance of two vectors. Recall that for two vectors \(\mathbf{x} = (x_1, \dots, x_n)\) and \(\mathbf{y} = (y_1, \dots, y_n)\) the sample covariance is given by
\[
\mbox{Cov}(\mathbf{x}, \mathbf{y}) = \frac{1}{n-1} \sum_{i = 1}^{n} (x_i - \bar{x})(y_i - \bar{y})
\]
Write an R program to compute the sample correlation without using the cov() function.
Test your code with the following vectors: x <- c(1, 2, 3, 4) and y <- c(2, 2, 3, 5).
Verify your result using cov(x, y).
20. Create three vectors of length 3, with content and names of your choice. Next, combine the three vectors into a \(3 \times 3\) matrix where each column represents one of your vectors. Finally, compute the determinant (det() - is your matrix invertible?) and the transpose of your matrix.
21. Consider the following matrix:
## [,1] [,2] [,3]
## [1,] -4.0 2.0 1.0
## [2,] 0.0 -1.0 0.5
## [3,] 1.5 0.2 -2.0
Compute the sum of rows (that is, you have to return a vector of length three with first entry -1) via the following three methods:
- Using the
rowSums()function (see help for more information). - Using the
apply()function. - Using matrix multiplication. Hint: This can be done by multiplying the above matrix with an appropriate vector.
22. Write an R program to:
- Create a numeric vector called
rateswith values: 0.043, 0.045, 0.041, 0.049, 0.05, 0.055, 0.048, 0.0495, 0.051, 0.044, 0.045, 0.0455. - Create a character vector called
monthswith values: “Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec”. - Create a data frame called
monthly_ratesusingmonthsandrates. - Add a new column to your data frame called
yearwith values 2021 for all rows. - Extract the rows where the rates are above 5%.
- Extract the rows where the rates are below the mean of the whole year.
23. Assume a group of students with ages
and grades
Let us imagine that we want to compute the average grade by age. We can use the tapply() function to do so.
Look at the documentation of tapply() (?tapply) and solve the above problem.
24. Consider the matrix
\[A = \begin{bmatrix} 1 & 1 & 3 \\ 5 & 2 & 6 \\ -2 & -1 & -3 \end{bmatrix}\]
Verify that \(A^3=0\).
Replace the third column by the sum of column 1 and column 2.
25. Consider the matrix
\[ M = \begin{bmatrix} 33 & 51 & 60 \\[0.3em] 20 & 35 & 17 \\[0.3em] 15 & 27 & 24 \\[0.3em] 15 & 21 & 28 \\[0.3em] 14 & 25 & 29 \\[0.3em] 10 & 53 & 24 \\[0.3em] \end{bmatrix},\]
and replace even numbers by \(-1\).
26. Solve the linear system
\[\begin{cases} 2y+x-z=1\\ 2z-x-y=0\\ x+1+y+2z=1 \end{cases}\]
27. Run the following lines:
Explain the output.
Find the number of entries in each row which are greater than 4.
Which rows contain exactly two occurrences of the number 7?
Denote by \(M_{i,j}\) the entries of the \(n\times m\) matrix \(M\) and compute the following means and sums of squares: \[\begin{align*} \mu&=\frac{1}{n\times m}\sum_{i,j}M_{i,j}\\ \mu_i&=\frac{1}{m}\sum_{j}M_{i,j},\quad i=1,\ldots,n\\ SS_1&=\sum_i (\mu-\mu_i)^2\\ SS_2&=\sum_{i,j}(M_{i,j}-\mu_i)^2\\ SS_3&=\sum_{i,j}(M_{i,j}-\mu)^2 \end{align*}\]
28. Install and load the package DAAG. Execute:
Type
library(help="DAAG")to get the information on this package.Consider the dataset
carpriceand apply the convenientRcommand to check the structure of the dataset.Set a name for
carprice, sayx.Explain the meaning of
table(x$Type).Replace all column names.
Compute the mean, variance, standard deviation, range, maximum and minimum of the maximum price variable.
Drop all the rows with maximum price higher than 24.8 m.u.
Drop all the rows with minimum price lower than 14.0 m.u.
29. Create a list with information about 3 workers as follows:
The list should have 4 vectors as components: name, age, gender and a boolean variable (it assumes values 0 or 1 that defines whether the person works or not).
Create a data frame with the information from the previous list.
Add a vector to the previous data frame with information about the person’s job.
Compute the mean, variance, standard deviation, range, maximum and minimum of the age.
30. Run the following lines:
- Create a list whose elements are the vectors \(x\) and \(y\) with names “sample1” and “sample2”, respectively.
- Create a list with the mean and standard deviation of each sample.
31. Create a list:
- with years from 2005 to 2016, 12 months and 31 days.
- replace year by
c(2000:2010). - delete the value 4 of the month.
32. Write a function called my_add that adds two numbers (x and y) together and returns the results. Run my_add(5,7).
33. Copy the function my_add above and add an error message that returns “x and y must be numbers” if x or y are not both numbers.
34.
Write a function that accepts a numerical vector \((x_1,x_2,\ldots,x_n)\) as argument and returns the vector \[\left(x_1,\frac{x_2^2}{2},\ldots,\frac{x_n^n}{n}\right).\] Run for
1:4.Write a function that accepts a single number \(x\) and a positive integer \(n\) and returns the sum \[1+x+\frac{x^2}{2}+\frac{x^3}{3}+\cdots+\frac{x^n}{n}.\] Run for \(x=\sqrt{2}\) and \(n=5\).
Write a function which takes a matrix as single argument and returns a matrix which is the same as the function argument but every odd entry is doubled. Run for
matrix(sample(1:10),2,5).Write a function to convert the temperature measured in Celsius (°C) to Fahrenheit (°F). Check that
f.d(0) = 32andf.d(-40) = -40.Write a function that takes a single integer argument \(n\) and returns the sum of its divisors, e.g., if \(n=6\), then the function returns \(1+2+3+6\).
Write a function that takes arguments \(a,b,c\in\mathbb{R}\) and returns the roots of the polynomial \(ax^2+bx+c\). The output should be a list containing the two roots. In case the roots are complex conjugated, the output of each root should be a list of its real and imaginary parts. Find the solutions of \(x^2-4x+4=0\) and \(3x^2-x+4=0\).
35. Consider the function
\[ f(x)=\begin{cases} 2e^{-2x}, & x \geq 0 \\ 0, & x<0 \end{cases}. \]
Show that \(f\) is a density probability function (dpf).
Let \(X\) be a r.v. with dpf \(f\) and compute \(P(X>1)\). Show the value with 2 decimal places.
Compute \(P(0.3<X<0.7)\). Show the value with 3 decimal places.
Compute \(E[X]\). Show the value with 1 decimal place.
36. Plot a graphic of \(f(x)=1-\frac{1}{x}sin(x)\) for \(0<x<5\) and for \(0<x<50\).
37. Consider a random variable \(X\) with probability density function (pdf)
\[ f_X(x)=\frac{x}{4}e^{-\frac{x^2}{8}},\,\,\,x\geq 0 \]
- Write an R function to compute the above pdf.
- Check whether this function is indeed a pdf (i.e., that it integrates 1) by:
- A sum approximation of the form \(\sum f(x_i) \Delta(x)\), where \(\Delta(x)\) is a “small” increment. Hint: create a sequence vector (over a relatively large interval and with a small increment), evaluate your function in a) on the sequence vector, multiply the evaluation by the increment and finally sum.
- Using the
integrate(f, lower, upper)function. Note:$valuegives the value of the integral.
- Compute the expected value and the variance of \(X\).
- Modify your function in a) so that an error message is displayed if a negative value is given as input.
38. We know that
\[
1 + \frac{1}{2} + \frac{1}{4} + \frac{1}{8} + \cdots = \sum_{n=0}^{\infty} \frac{1}{2^n} = 2 \,.
\]
Using a while loop, find a value \(N\) such that
\[
2 - \sum_{n=0}^{N} \frac{1}{2^n} \leq \epsilon \,,
\]
where \(\epsilon = 0.00001\).
39. Write a function that performs the inner product of two vectors using for loops.
Using microbenchmark() compare the performance of your implementation with the inner product using the %*% operator. Try with large vectors, let’s say length 100, and times = 10000.
40. Consider the data set “EuStockMarkets” in R corresponding to the “Daily Closing Prices of Major European Stock Indices, 1991-1998”.
Write an R program to plot a histogram of “DAX”. Note: to access “DAX” use EuStockMarkets[, 1].
Compute the log-returns of “DAX”. Recall that the log-returns are computed as
\[ \log(P_t/P_{t-1}) \,, \] where \(P_t\) are the closing prices.
Compute the mean and standard deviation of the log-returns.
Plot a histogram of the log-returns.
In your plot in d), add the density function of a normal distributed random variable with mean and standard deviation the values computed in c).
Plot “DAX” versus “SMI” and compute their correlation.
41. Let \(X\) be a normal random variable with mean \(2\) and variance \(9\), that is, \(X\sim\mathcal{N}(2,9)\). Compute:
- \(\mathbb{P}(|X|\leq 2.4)\).
- The 95% quantile of the given distribution.
42. Consider the cars data set in R.
- Compute the correlation between
speedanddist, and create a scatter plot to comparespeedvsdist. Do you see any relationship? - Fit a linear regression model to explain distance in terms of speed.
- Add the regression line to your plot in a). Hint: this can be done using the
abline()function applied to your regression model in b). - Predict
distfor values ofspeedof 28 and 30. - Does the model seem to satisfy the assumptions of mean zero, constant variance, and normality for the residuals?
8.2 Related to Chapter 7
43. A stock price is currently 20. It is known that at the end of 1 year it will go up by 10% or down by 5%. The risk-free interest rate is 8% per annum with annual compounding. Write the R code to find the initial value of a 1-year European put option with a strike of 20.
44. A stock price is currently 40. It is known that at the end of 9 months, it will either be 45 or 35. The risk-free interest rate with continuous compounding is 10% per annum.
Write the R code to find the initial value of a 9-month European call option on the stock with an exercise price of 40.
Describe the hedging portfolio for the option.
45. A stock price is currently 30. Over each of the next two 4-month periods, it is expected to go up by 8% or down by 10%. The risk-free interest rate is 12% per annum with quarterly compounding. Write an R code to find the initial value of an 8-month European call option with a strike price of 34.
46. A stock price is currently 100. During each three-month period for the next six months, it will increase by 10% or decrease by 10%. The risk-free interest rate is 8% per annum with quarterly compounding.
- Write an R program that gives the binomial tree evolution of the stock price.
- Write an R code to find the initial value of a six-month European put option with strike K = 105.
47. A stock is currently priced at 30. Over each of the next two 2-month periods, it is expected to increase by 8% or decrease by 10%. The risk-free interest rate is 10% per annum with continuous compounding. What is the initial value of a 4-month derivative with strike \(K = 30\) and that pays off \(X = \max(S_T^2 -K,0)\), where \(S_T\) is the stock price in four months?
48. A stock price is currently 40. In two months, it will either be 42 or 38, and during this period, the risk-free interest rate is 6% per annum with monthly compounding. If it rises to 42 in two months, then it will either be 48 or 40 after another two months. If it drops to 38 after the first two months, then after another two months, it will either be 42 or 34. The risk-free interest rate is 10% per annum with monthly compounding during the second two-month period. Write an R program to calculate the initial value of a derivative that pays off \(\frac{1}{2}\left(\max(44 - S_T, 0 )\right)^2\), where \(S_T\) is the stock price in four months.
49. It is known that for any \(a \in \mathbb{R}\), the standard Brownian motion satisfies that \(W(t) > a\) with probability 1 for some \(t>0\). Note that in the lecture notes, we simulated a standard BM over a fixed time period \(T\). In this exercise, we let the time vary, and we fix a threshold \(a >0\), then simulate a standard BM until it reaches the given threshold. Write an R program to plot one trajectory of a standard Brownian motion until it reaches \(a = 1\). Hint: Use a while loop to generate normal distributed increments until the condition is satisfied.
50. Via simulations, approximate the probability that an arithmetic Brownian motion with drift 0.5 and volatility 0.1 is above 1 at time 2. Compare your result with the theoretical probability.
51. Consider a European put option on a non-dividend-paying stock with current price is 40. The strike price is 38, the risk-free interest rate is 12% per annum with continuous compounding, the volatility is 30% per annum, and the time to maturity is three months:
- Find the price of the option using the BS formula.
- Approximate the price of the option using simulations (10000).
- Approximate the option’s price using a binomial model with 1000 steps.
52. A stock has current price \(S(0) = 1416\). What is the value of an 8-month European call option on that stock with a strike price of \(1450\) if the volatility is 0.42 and the risk-free interest rate is 5% per annum with continuous compounding? Find the greeks for the corresponding option. Plot vega again the initial stock price \(S(0)\) ranging from 0.5 to 2000.
Copyright Notice: All rights reserved. No portion of this website’s content may be reproduced, copied, or distributed without the author’s prior written consent. This includes, but is not limited to, the text, code, and images, which may not be copied, downloaded, or reproduced in any form without explicit written permission.
2025 \(|\) Nuno M. Brites \(|\) nbrites@iseg.ulisboa.pt