Add dates to simple return vector
The vector sbux_ret
now contains the simple returns of Starbucks (well done!). It would be convenient to have the dates as names for the elements of that vector. Remember that the trading dates were in the first column of the sbux_df
data frame. To set the names of a vector, you can use names(vector) <- some_names
.
Remember that we are dealing with closing prices. The first return in sbux_df
is thus realized on the second day, or sbux_prices_df[2,1]
.
This exercise is part of the course
Intro to Computational Finance with R
Exercise instructions
- Assign the correct dates as names to all elements of the return vector
sbux_ret
. - Use the
head()
function to display the first elements ofsbux_ret
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# The sbux_df data frame is already loaded in your work space
sbux_prices_df <- sbux_df[, "Adj.Close", drop = FALSE]
# Denote n the number of time periods:
n <- nrow(sbux_prices_df)
sbux_ret <- (sbux_prices_df[2:n, 1] - sbux_prices_df[1:(n - 1), 1]) / sbux_prices_df[1:(n - 1), 1]
# Notice that sbux_ret is not a data frame object
class(sbux_ret)
# Now add dates as names to the vector and print the first elements of sbux_ret to the console to check