Reputation: 87
I am running AR on this data.
Date Price YOY Quarter
2000-01-15 2.385368 -312362 Q1
2000-02-15 2.614250 -442117 Q1
2000-03-15 2.828261 -252596 Q1
2000-04-15 3.028842 -292756 Q2
2000-05-15 3.596409 -401578 Q2
......
The model is
price.fit<-lm(log(Price)~+(YOY)+log(lag(Price))+relevel(Quarter,ref="Q4"),subset(Data,Year>=2000))
Now I need to forecast for the next 12 periods. A made-up data frame "newdata" includes estimate(a range) for the variable YOY.
newdata
high mean low
.....
How to use predict function or other method to forecast the price range(high, mean, low)for the next 12 months? Or maybe using loops?
Upvotes: 3
Views: 994
Reputation: 1417
There is a generic function predict()
and it can be used for prediction. Although predict.lm()
is used below for clarification, predict()
should work. Given a lm object and new data, it returns forecasted values.
As regression returns numeric values, converting into a factor (high, medium, low) has to be mapped manually and sapply()
is used for that.
library(lubridate)
dates <- ymd(19990115) + months(0:71)
df <- data.frame(date = dates,
price = sample(100:150, 72, replace = T),
YOY = sample(-40000:-20000, 72, replace = T),
Qtr = as.factor(quarter(dates)))
price.fit <- lm(log(price) ~ +(YOY) + log(lag(price)) + relevel(Qtr, ref = "4"),
data = df[year(df$date) >= 2000,])
pred <- predict.lm(price.fit, newdata = df[year(df$date) < 2000,])
pred
#1 2 3 4 5 6
#4.976734 4.653960 4.605170 4.691348 4.663439 4.969813
#7 8 9 10 11 12
#4.927254 4.727388 4.634729 4.875197 4.700480 4.700480
sapply(pred, function(x) {
if(x < 4.56) "low"
else if(x < 4.75) "medium"
else "high"
})
#1 2 3 4 5 6 7 8
#"high" "medium" "medium" "medium" "medium" "high" "high" "medium"
#9 10 11 12
#"medium" "high" "medium" "medium"
Upvotes: 1