Aggregate to weekly, ending on Wednesdays
In this exercise, you will learn a general aggregation technique to aggregate daily data to weekly, but with weeks ending on Wednesdays. This is often done in stock market research to avoid intra-week seasonality.
The period.apply()
function takes an xts object, time period end points, and an aggregation function. Then it applies the function to each group of data between the end points.
The endpoints()
function can calculate the time period end points for period.apply()
, and you can use custom end points too. But your custom end points vector must start with zero and end with the total number of observations you're going to aggregate, just like the output of endpoints()
.
You'll use .indexwday()
to find the Wednesday of each week. It returns a number between 0-6, where Sunday=0.
This exercise will use the daily Fed Funds data (DFF
) from prior exercises.
This exercise is part of the course
Importing and Managing Financial Data in R
Exercise instructions
- Use
.indexwday()
to get the week days from theDFF
index. Assign the result toindex_weekdays
. - Use the
which()
function to find the locations of the Wednesdays inindex_weekdays
. Store the result inwednesdays
. - Complete the command to make the
end_points
start with 0 and end with the total number of rows, like the output ofendpoints()
. - Use
period.apply()
andend_points
to aggregateDFF
to weekly averages. Assign the result toweekly_mean
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Extract index weekdays (Sunday = 0)
# Find locations of Wednesdays
wednesdays <- ___(index_weekdays == 3)
# Create custom end points
end_points <- c(___, wednesdays, ___)
# Calculate weekly mean using custom end points