Aan de slagGa gratis aan de slag

FUN arguments

Often, the function that you want to apply will have other optional arguments that you may want to tweak. Consider the percent_to_decimal() function that allows the user to specify the number of decimal places.

percent_to_decimal(5.4, digits = 3)
[1] 0.054

In the call to lapply() you can specify the named optional arguments after the FUN argument, and they will get passed to the function that you are applying.

my_list
$a
[1] 2.444 3.500

$b
[1] 1.100 2.678 3.450

lapply(my_list, FUN = percent_to_decimal, digits = 4)
$a
[1] 0.0244 0.0350

$b
[1] 0.0110 0.0268 0.0345

In the exercise, you will extend the capability of your sharpe ratio function to allow the user to input the risk free rate as an argument, and then use this with lapply(). A data frame of daily stock returns as decimals called stock_return is available.

Deze oefening maakt deel uit van de cursus

Intermediate R for Finance

Cursus bekijken

Oefeninstructies

  • Extend sharpe to allow the input of the risk free rate as an optional argument. The default should be set at .0003.
  • Use lapply() on stock_return to find the sharpe ratio if the risk free rate is .0004.
  • Use lapply() on stock_return to find the sharpe ratio if the risk free rate is .0009.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

# Extend sharpe() to allow optional argument
sharpe <- function(returns, rf = ___) {
    (mean(returns) - ___) / sd(returns)
}

# First lapply()
___

# Second lapply()
___
Code bewerken en uitvoeren