# NOT RUN {
# Fix seed for reproducible simulations:
set.seed(1)
# Example 1
# Simulate independent normal time series of same lengths
x <- rnorm(100)
y <- rnorm(100)
ccf(x, y) # default CCF with parametric confidence band
tmp <- ccf_boot(x, y) # CCF with bootstrap
tmp$rP; tmp$rS # can always extract results for both Pearson and Spearman correlations
# Example 2
# Simulated ts objects of different lengths and starts (incomplete overlap)
x <- arima.sim(list(order = c(1, 0, 0), ar = 0.5), n = 30)
x <- ts(x, start = 2001)
y <- arima.sim(list(order = c(2, 0, 0), ar = c(0.5, 0.2)), n = 40)
y <- ts(y, start = 2020)
ts.plot(x, y, col = 1:2, lty = 1:2) # show how x and y are aligned
ccf(x, y)
ccf_boot(x, y, plot = "Spearman") # CCF with bootstrap
# Notice that only +-7 lags can be calculated in both cases because of the small
# overlap of the time series. If save these time series as plain vectors, the time
# information would be lost, and time series will be misaligned.
ccf(as.numeric(x), as.numeric(y))
# Example 3
# Box & Jenkins time series of sales and a leading indicator, see ?BJsales
plot.ts(cbind(BJsales.lead, BJsales))
# Each of the BJ time series looks as having a stochastic linear trend, so apply differences:
plot.ts(cbind(diff(BJsales.lead), diff(BJsales)))
# Get cross-correlation of the differenced series:
ccf_boot(diff(BJsales.lead), diff(BJsales), plot = "Spearman")
# The leading indicator "stands out" with significant correlations at negative lags,
# showing it can be used to predict the sales 2-3 time steps ahead (that is,
# diff(BJsales.lead) at times t-2 and t-3 is strongly correlated with diff(BJsales) at
# current time t).
# }
# NOT RUN {
# }
Run the code above in your browser using DataLab