R applying growth rate backwards - r

I have a data with two different monthly series and a one year overlap
ts1 <- ts(cumsum(rnorm(120,.1,1)), start = 1995, frequency = 12)
ts2 <- ts(cumsum(rnorm(120,.2,1)), start = 2004, frequency = 12)
They do not have the same levels (there was a rebasing in 2004) but with the overlap one can use the monthly growth rate of the first one to back-project the second one until 1995.
I would like to create a variable ts_series which has the levels of ts2 after 2004 and then uses the monthly growth rates of ts1 to back-project it. I have several such series in a zoo object, so I can either use a zoo method or group them in list and use mapply.
Many thanks

Here is one approach, using a simple linear regression on the overlapping bits to identify the relationship between the two series and then applying that model to the non-overlapping part of ts1 to estimate earlier values of ts2. The last step gives you a new ts object that represents the predicted values of ts2 for the non-overlapping period.
# Make the toy data
set.seed(1)
ts1 <- ts(cumsum(rnorm(120,.1,1)), start = 1995, frequency = 12)
ts2 <- ts(cumsum(rnorm(120,.2,1)), start = 2004, frequency = 12)
# Now do the estimation
x <- as.vector(window(ts1, start = c(2004,1), end = c(2004,12)))
y <- as.vector(window(ts2, start = c(2004,1), end = c(2004,12)))
tsmod <- lm(y ~ x)
ts2preds <- predict(tsmod, newdata = as.data.frame(window(ts1, start = c(1995,1), end = c(2003,12))))
ts2prior <- ts(data = ts2preds, start = c(1995, 1), end = c(2003, 12), frequency = 12)
If you want instead to backcast ts2 on its own, though, Rob Hyndman's got you covered with the forecast() function in his forecast package. Following an example from his blog:
library(forecast)
f <- frequency(ts2) # Identify the frequency of your ts
h <- (start(ts2)[1] - start(ts1)[1]) * f # Set the number of periods you want to backcast
revx <- ts(rev(ts2), frequency = f) # Reverse time in the series you want to backcast
ts2plus <- forecast(auto.arima(revx), h) # Do the backcasting
# Reverse its elements
ts2plus$mean <- ts(rev(ts2plus$mean), end=tsp(ts2)[1] - 1/f, frequency=f)
ts2plus$upper <- ts2plus$upper[h:1,]
ts2plus$lower <- ts2plus$lower[h:1,]
ts2plus$x <- ts2 # Replace the reversed reference series in the prediction object with the original one
# Plot it
plot(ts2plus, xlim=c(tsp(ts2)[1]-h/f, tsp(ts2)[2]))
Here's the plot that produces:
And here's how the two series compare:
> cor(ts2plus$mean, ts2preds)
[1] 0.9760174
If your main goal is to get the best possible point predictions of those earlier values, you might consider running both versions and averaging their results. Then this becomes a very simple multi-model ensemble forecast (or backcast).

Related

How to forecast and fit the optimal model for multiple time series?

I want to do batch forecasting among multiple series, for example, if I want to forecast time series with IDs that end with 1(1,11,21,31...), how can I do that?
Since you did not provide detailed information, I was not sure which forecasting method you want to use hence I give here an example of a univariate time series model:
Load required packages:
library(forecast)
library(dplyr)
We use example data from Rob Hyndman:
dta <- read.csv("https://robjhyndman.com/data/ausretail.csv")
Now change the column names:
colnames(dta) <- c("date", paste0("tsname_", seq_len(ncol(dta[,-1]))))
Select timeseries which end with 1:
dta_ends_with1 <- dplyr::select(dta, dplyr::ends_with("1"))
Create a ts object:
dta_ends_with1 <- ts(dta_ends_with1, start = c(1982,5), frequency = 12)
Specify how many steps ahead you want to forecast, here I set it to 6 steps ahead,
h <- 6
Now we prepare a matrix to save the forecast:
fc <- matrix(NA, ncol = ncol(dta_ends_with1), nrow = h)
Forecasting loop.
for (i in seq_len(ncol(dta_ends_with1))) {
fc[,i] <- forecast::forecast(forecast::auto.arima(dta_ends_with1[,i]),
h = h)$mean
}
Set the column names:
colnames(fc) <- colnames(dta_ends_with1)
head(fc)

Weekly and Yearly Seasonality in R

I have daily electric load data from 1-1-2007 till 31-12-2016. I use ts() function to load the data like so
ts_load <- ts(data, start = c(2007,1), end = c(2016,12),frequency = 365)
I want to remove the yearly and weekly seasonality from my data, to decompose the data and remove the seasonality, I use the following code
decompose_load = decompose(ts_load, "additive")
deseasonalized = ts_load - decompose_load$seasonal
My question is, am I doing it right? is this the right way to remove the yearly seasonality? and what is the right way to remove the weekly seasonality?
A few points:
a ts series must have regularly spaced points and the same number of points in each cycle. In the question a frequency of 365 is specified but some years, i.e. leap years, would have 366 points. In particular, if you want the frequency to be a year then you can't use daily or weekly data without adjustment since different years have different numbers of days and the number of weeks in a year is not integer.
decompose does not handle multiple seasonalities. If by weekly you mean remove the effect of Monday, of Tuesday, etc. and if by yearly you mean remove the effect of being 1st of the year, 2nd of the year, etc. then you are asking for multiple seasonalities.
end = c(2017, 12) means the 12th day of 2017 since frequency is 365.
The msts function in the forecast package can handle multiple and non-integer seasonalities.
Staying with base R, another approach is to approximate it by a linear model avoiding all the above problems (but ignoring correlations) and we will discuss that.
Assuming the data shown reproducibly in the Note at the end we define the day of week, dow, and day of year, doy, variables and regress on those with an intercept and trend and then construct just the intercept plus trend plus residuals in the last line of code to deseasonalize. This isn't absolutely necessary but we have used scale to remove the mean of trend in order that the three terms defining data.ds are mutually orthogonal -- Whether or not we do this the third term will be orthogonal to the other 2 by the properties of linear models.
trend <- scale(seq_along(d), TRUE, FALSE)
dow <- format(d, "%a")
doy <- format(d, "%j")
fm <- lm(data ~ trend + dow + doy)
data.ds <- coef(fm)[1] + coef(fm)[2] * trend + resid(fm)
Note
Test data used in reproducible form:
set.seed(123)
d <- seq(as.Date("2007-01-01"), as.Date("2016-12-31"), "day")
n <- length(d)
trend <- 1:n
seas_week <- rep(1:7, length = n)
seas_year <- rep(1:365, length = n)
noise <- rnorm(n)
data <- trend + seas_week + seas_year + noise
you can use the dsa function in the dsa package to adjust a daily time series. The advantage over the regression solution is, that it takes into account that the impact of the season can change over time, which is usually the case.
In order to use that function, your data should be in the xts format (from the xts package). Because in that case the leap year is not ignored.
The code will then look something like this:
install.packages(c("xts", "dsa"))
data = rnorm(365.25*10, 100, 1)
data_xts <- xts::xts(data, seq.Date(as.Date("2007-01-01"), by="days", length.out = length(data)))
sa = dsa::dsa(data_xts, fourier_number = 24)
# the fourier_number is used to model monthly recurring seasonal patterns in the regARIMA part
data_adjusted <- sa$output[,1]

STL ts frequency = 1

I am using the stats::stl function for first time in order to identify and delete the tecnological signal of a crop yields serie. I am not familiar with this method and I am a newbie on programming, in advance I apologize for any mistaken.
These are the original data I am working with:
dat <- data.frame(year= seq(1962,2014,1),yields=c(1100,1040,1130,1174,1250,1350,1450,1226,1070,1474,1526,1719,1849,1766,1342,2000,1750,1750,2270,1550,1220,2400,2750,3200,2125,3125,3737,2297,3665,2859,3574,4519,3616,3247,3624,2964,4326,4321,4219,2818,4052,3770,4170,2854,3598,4767,4657,3564,4340,4573,3834,4700,4168))
This is the ts with frequency =1 (annual) created as input for STL function:
time.series <- ts(data=dat$yields, frequency = 1, start=c(1962, 1), end=c(2014, 1))
plot(time.series, xlab="Years", ylab="Kg/ha", main="Crop yields")
When I try to run the function I get the following error message:
decomposed <- stl(time.series, s.window='periodic')
> Error in stl(time.series, s.window = "periodic") : series is not periodic or has less than two periods
I know that my serie is annual and therefore I can not vary the frequency in the ts which it is seems what causes the error because when I change the frequency I get the seasonal, trend and remainder signals:
time.series <- ts(data=dat$yields, frequency = 12, start=c(1962, 1), end=c(2014, 1))
decomposed <- stl(time.series, s.window='periodic')
plot(decomposed)
I would like to know if there is a method to apply STL function with annual data with a frequency of observation per unit of time = 1.
On the other hand, to remove the tecnological signal, it is only necessary to obviate the trend and remainder signal from the original serie or I am mistaken?
Many thanks for your help.
Since your using annual data, there is no seasonal component, therefore seasonal decomposition of time series would not be appropriate. However, the stats::stl function calls the loess function to estimate trend, which is a local polynomial regression you can adjust to your liking. You can call loess directly and estimate your own trend as followings.
dat <- data.frame(year= seq(1962,2014,1),yields=c(1100,1040,1130,1174,1250,1350,1450,1226,1070,1474,1526,1719,1849,1766,1342,2000,1750,1750,2270,1550,1220,2400,2750,3200,2125,3125,3737,2297,3665,2859,3574,4519,3616,3247,3624,2964,4326,4321,4219,2818,4052,3770,4170,2854,3598,4767,4657,3564,4340,4573,3834,4700,4168))
dat$trend <- loess(yields ~ year, data = dat)$fitted
plot(y = dat$yields, x = dat$year, type = "l", xlab="Years", ylab="Kg/ha", main="Crop yields")
lines(y = dat$trend, x = dat$year, col = "blue", type = "l")

Input format for functions in package strucchange?

I'm trying to do change point detection with ´monitor´ from the strucchange package, but I have trouble getting a useful output.
My input is a time stamped dataframe, and I would like the breaks to be returned as dates, but they are returned as observation number:
cDF1 <- myDF[1:80,]
> cDF1[1:3,]
Year Month Value
2000-10 2000 Oct 1
2001-01 2001 Jan 1
2001-04 2001 Apr 1
me.mefp <- mefp(Value~1, type="ME", rescale=TRUE,
+ data=cDF1, alpha=0.05)
cDF1 <- myDF[1:104,]
> me.mefp <- monitor(me.mefp)
Break detected at observation # 98
In the strucchange manual, there are examples in which the time stamps are kept, but I can't figure out what they difference in format is.
It makes no difference if I make the data frame into a time series.
Can anybody help?
Thanks!
The mefp/monitor functions can only deal with ts time series. Hence, you can either supply a data argument that is a (multivariate) ts, a data.frame where the response variable is a ts or a standalone ts without a data argument. In your case, the data appears to be quarterly and as there are no regressors (except a constant) a standalone time series is probably most convenient.
As an artificial example, I simulate 100 observations from a quarterly time series:
set.seed(1)
Value <- ts(rnorm(100, mean = rep(0:1, c(70, 30)), sd = 0.5),
start = c(1990, 1), freq = 4)
plot(Value)
Then I select the data up to the end of 1999 as the history period and initialize the monitoring process:
val <- window(Value, end = c(1999, 4))
m <- mefp(val ~ 1, type = "ME", rescale = TRUE, alpha = 0.05)
Then the data can arrive, say until the end of 2009:
val <- window(Value, end = c(2009, 4))
m <- monitor(m)
And then finally until the end of 2014:
val <- window(Value, end = c(2014, 4))
m <- monitor(m)
## Break detected at observation # 81
plot(m)
Here, a break is finally detected and also brought out graphically.
P.S.: In your example, it appears as if the data were positive counts. If so, taking logs may (or may not) be useful.

How to forecast using ragged edge data in a MIDAS model using the MIDASR package?

I am trying to generate a 1-step-ahead forecast of a quarterly variable using a monthly variable with the midasr package. The trouble I am having is that I can only estimate a MIDAS model when the number of monthly observations in the sample is exactly 3 times as much the number of quarterly observations.
How can I forecast in the midasr package when the number of monthly observations is not an exact multiple of the quarterly observations (e.g. when I have a new monthly data point that I want to use to update the forecast)?
As an example, suppose I run the following code to generate a 1-step-ahead forecast when I have (n) quarterly observations and (3*n) monthly observations:
#first I create the quarterly and monthly variables
n <- 20
qrt <- rnorm(n)
mth <- rnorm(3*n)
#I convert the data to time series format
qrt <- ts(qrt, start = c(2009, 1), frequency = 4)
mth <- ts(mth, start = c(2009, 1), frequency = 12)
#now I estimate the midas model and generate a 1-step ahead forecast
library(midasr)
reg <- midas_r(qrt ~ mls(qrt, 1, 1) + mls(mth, 3:6, m = 3, nealmon), start = list(mth = c(1, 1, -1)))
forecast(reg, newdata = list(qrt = c(NA), mth =c(NA, NA, NA)))
This code works fine. Now suppose I have a new monthly data point that I want to include, so that the new monthly data is:
nmth <- rnorm(3*n +1)
I tried running the following code to estimate the new model:
reg <- midas_r(qrt ~ mls(qrt, 1, 1) + mls(nmth, 2:7, m = 3, nealmon), start = list(mth = c(1, 1, -1))) #I now use 2 lags instead 3 with the new monthly data
However I get an error message saying: 'Error in mls(nmth, 2:7, m = 3, nealmon) : Incomplete high frequency data'
I could not find anything online on how to deal with this problem.
A while ago I had to do with similar question. If I remember correctly, you first need to estimate the model using the old dataset with reduced lag, so insted of using 3:6 lags you should use 2:6 lags:
reg <- midas_r(qrt ~ mls(qrt, 1, 1) + mls(mth, 2:6, m = 3, nealmon), start = list(mth = c(1, 1, -1)))
Then suppose you observe a new value of the higher frequency data - new_value
new_value <- rnorm(1)
Then you can use this newly observed value for the forecasting of the lower frequency valiable as follows:
forecast(reg, newdata = list(mth = c(new_value, rep(NA, 2))))

Resources