# GM(1,1) model
# x0 is the original data sequence
x0 <- c(2350,2465,2557,2577,2689,2739,2797,2885,2937,2996)
# Calculate AGO
x1 <- cumsum(x0)
# Determine length of x0
n <- length(x0)
# Generate background value sequence Z
b <- numeric(n)
for (i in 1:n){
b[i] <- -(0.5*x1[i + 1] + 0.5*x1[i])
}
b1 <- b[1:n-1]
# Create a matrix B
B <- matrix(1,nrow=n-1,ncol=2)
B[,1] <- t(t(b1[1:n-1]))
# Create matrix yn
yn <- matrix(c(x0),ncol=1)
yn <- t(t(x0[2:n]))
# Estimate parameters a and b by ordinary least squares method (OLS)
xcap <- solve (t(B)%*% B)%*% t(B) %*% yn
a <- xcap[1,1]
b <- xcap[2,1]
# Calculate fitted values
scale_with <- function(k)
{
(x0[1] - (b/a)) * exp(-a*k) * (1 - exp(a))
}
fitted <- scale_with(1:n)
x0cap <- c(x0[1],fitted[1:n-1])
x0cap
# A is the number of forecast values
A <- 4
# Predicted values
x0cap4 <- scale_with(1 : n+A-1)
x0cap5 <- tail(x0cap4,A)
x0cap5
# Fitted and predicted values
x0cap2 <- c(x0cap,x0cap5)
x0cap2
Run the code above in your browser using DataLab