# R function - calculate forecast

Hello,

I do have time series data for 20 quarters and need to calculate forecast by using the exponential smoothing backcasting method. Based on the criteria, I do need to use last 13 dataset out of 20. I wrote a function to calculate forecast. However, the function is still getting all 20 historical observation instead of 13 (fence value).

test data.pdf (13.5 KB)

#Exponential smoothing with backcasting with a fence
ESBC_with_fence_2 <- function(x, alpha = 0.2, fence = 20){
#TODO: Check that x is a vector
#TODO: check for if the fence is longer than the data and what to do with that situation

print("fence:")
print(fence)
print("length(x):")
print(length(x))
print("(length(x) - fence + 1):")
print(length(x) - fence + 1)

#seed the forecast with the most recent element
forecast = x[length(x)]

#special case
if (fence == 1){
return(forecast)
}

#backcast
for (i in (length(x) - 1): (length(x) - fence + 1)){
forecast = forecast * (1 - alpha) + x[i] * alpha
# print("backcast")
# print("x[i]")
# print(x[i])
}
#forecast
for (i in (length(x) - fence + 1):length(x)){
forecast = forecast * (1 - alpha) + x[i] * alpha
# print("forecast")
# print("x[i]")
# print(x[i])
}
return(forecast)
}

#use function to calculate forecast with fence
forecasts_fence_alpha_0.2 <- test_data %>%
group_by(MATERIAL) %>%
do(fcst_list = ESBC_with_fence_2(.\$demand))

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.