Data Structure: XTS

Exercises Using sample_xts

Extract the data from January 3, 2007, to January 15, 2007, from the sample_xts object.

Solution:

# Extract data from January 3, 2007, to January 15, 2007
sample_xts["2007-01-03/2007-01-15"]

Calculate the weekly average of each column in the sample_xts object using the apply.weekly() function.

Solution:

# Calculate the weekly average for each column
weekly_avg <- apply.weekly(x = sample_xts, FUN = colMeans)
weekly_avg

Check if there are any missing dates in the sample_xts object. If there are, fill them in by forward-filling the previous values.

Solution:

# Check for missing dates
missing_dates <- !all(seq(start(sample_xts), end(sample_xts), by = "days") %in% index(sample_xts))

if (missing_dates) {
  # Fill missing dates with NA and then forward-fill
  sample_xts <- merge(x = sample_xts, 
                      y = zoo(, seq(start(sample_xts), 
                                    end(sample_xts), 
                                    by = "days")))
  sample_xts <- na.locf(sample_xts)
}
sample_xts

Extract only the data from Fridays in the sample_xts object. This will involve subsetting by day of the week.

Solution:

# Extract only Fridays from the sample_xts data
fridays_data <- sample_xts[.indexwday(sample_xts) == 5]
fridays_data

Create a new xts object with the same date range as sample_xts but with different data, and merge it with sample_xts so that both time series are aligned by date.

Solution:

# Create a new xts object with random data and same dates as sample_xts
new_data <- xts(  rnorm(nrow(sample_xts)), order.by = index(sample_xts))
colnames(new_data) <- "New_Series"

# Merge sample_xts with new_data
merged_data <- merge(x = sample_xts, y = new_data)
merged_data

Calculate a 10-day rolling mean for each column in sample_xts.

Solution:

# Calculate a 10-day rolling mean for each column
rolling_mean_10 <- rollapply(sample_xts, width = 10, FUN = mean, align = "right", fill = NA)
rolling_mean_10

Aggregate the data by month and calculate the sum of each column using apply.monthly().

Solution:

# Calculate the monthly sum for each column
monthly_sum <- apply.monthly(x = sample_xts, FUN = colSums)
monthly_sum

Find the highest and lowest values for each column in sample_xts, and determine the dates on which these values occurred.

Solution:

# Find the highest and lowest values for each column
highest_values <- apply(X = sample_xts, MARGIN = 2, FUN = max)
lowest_values <- apply(X = sample_xts, MARGIN = 2, FUN = min)

# Find the dates for highest and lowest values
highest_dates <- apply(X = sample_xts, MARGIN = 2, FUN = function(col){index(sample_xts)[which.max(col)]})
lowest_dates <- apply(X = sample_xts, MARGIN = 2, FUN = function(col){ index(sample_xts)[which.min(col)]})

list(
  highest_values = highest_values,
  highest_dates = highest_dates,
  lowest_values = lowest_values,
  lowest_dates = lowest_dates
)