'One-Step ahead Forecasting with Prophet in R
I have built a custom function to do one-step-ahead forecasting using Prophet in R. But my code is not working don't know what is the problem. I have taken the rolling window size of 100 and trained the data with 60 days to forecast the next 1 entry in the data. But, my model is not working as it supposes to, please help me.
# loading the data:
s <- read.csv(url('https://ondemand.websol.barchart.com/getHistory.csv?apikey=c3122f072488a29c5279680b9a2cf88e&symbol=zs*1&type=dailyNearest&backAdjust=false&startDate=20100201'))
data <- s[c(3, 7)]
data <- as_tibble(data) %>%
mutate(tradingDay = as_date(tradingDay))
Here is my code:
# One-step ahead forecasting with Prophet
Prophet_prediction <- function(k) {
range_validation <- 100
n_ahead <- 1
train_tbl <- data %>% slice((1 + k):(60 + k))
valid_tbl <- data %>% slice((60 + 1 + k):(60 + k + range_validation))
test_tbl <- data %>% slice((60 + k + range_validation + 1):(60 + k + range_validation + n_ahead))
train_df <- bind_rows(train_tbl, valid_tbl) %>% select(1:2)
test_df <- test_tbl %>% select(1:2)
# Prophet model:
my_prophet <- prophet(train_df[,2] %>% ts(start = 1))
# Use the model for forecasting:
predict.prophet <- forecast(my_prophet, h = 1)$yhat %>% as.vector()
actual_predicted_df_test <- test_df %>%
mutate(predicted = predict.prophet)
return(actual_predicted_df_test)
}
lapply(0:50, Prophet_prediction) ->> Prophet_prediction
Prophet_prediction <- do.call("bind_rows", Prophet_prediction)
view(Prophet_prediction)
But it gives me this error:
Error in attr(data, "tsp") <- c(start, end, frequency) :
object is not a matrix
Solution 1:[1]
I can see at least a few errors. First, you are missing the closing bracket of your function. Second, you did not specify what k is. Additionally, the function has some issues.
First, this is wrong:
my_prophet <- prophet(train_df[,2] %>% ts(start = 1))
According to ?prophet, you need a
Dataframe containing the history. Must have columns ds (date type) and y, the time series.
This is also wrong
predicted_prophet <- forecast(my_prophet, h = 1)$mean %>% as.vector()
Use function predict.prophet to predict using a prophet model. The object returned by predict.prophet does not have column mean. You might be looking for $yhat instead.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Otto Kässi |
