Skip to content

Instantly share code, notes, and snippets.

@yogsp
Created May 8, 2017 12:23
Show Gist options
  • Save yogsp/f874e574a51f653b5479d3229eaa7580 to your computer and use it in GitHub Desktop.
Save yogsp/f874e574a51f653b5479d3229eaa7580 to your computer and use it in GitHub Desktop.
HoltWinters, confidence intervals, cumsum,
> #Filtering the noise the comes with timeseries objects as a way to find significant trends
> #First, we use Holt-Winter which fits an exponential model to a timeseries
> library(astsa)
> library(xts)
> data(jj)
> jj
Qtr1 Qtr2 Qtr3 Qtr4
1960 0.710000 0.630000 0.850000 0.440000
1961 0.610000 0.690000 0.920000 0.550000
1962 0.720000 0.770000 0.920000 0.600000
1963 0.830000 0.800000 1.000000 0.770000
1964 0.920000 1.000000 1.240000 1.000000
1965 1.160000 1.300000 1.450000 1.250000
1966 1.260000 1.380000 1.860000 1.560000
1967 1.530000 1.590000 1.830000 1.860000
1968 1.530000 2.070000 2.340000 2.250000
1969 2.160000 2.430000 2.700000 2.250000
1970 2.790000 3.420000 3.690000 3.600000
1971 3.600000 4.320000 4.320000 4.050000
1972 4.860000 5.040000 5.040000 4.410000
1973 5.580000 5.850000 6.570000 5.310000
1974 6.030000 6.390000 6.930000 5.850000
1975 6.930000 7.740000 7.830000 6.120000
1976 7.740000 8.910000 8.280000 6.840000
1977 9.540000 10.260000 9.540000 8.729999
1978 11.880000 12.060000 12.150000 8.910000
1979 14.040000 12.960000 14.850000 9.990000
1980 16.200000 14.670000 16.020000 11.610000
> hw <- HoltWinters(jj)
> hw
Holt-Winters exponential smoothing with trend and additive seasonal component.
Call:
HoltWinters(x = jj)
Smoothing parameters:
alpha: 0.06170719
beta : 1
gamma: 1
Coefficients:
[,1]
a 13.7617609
b 0.3993408
s1 3.6771272
s2 1.7105921
s3 2.6575800
s4 -2.1517609
> plot(hw)
> #The black line is the original series while the red line is the smoothened series
> #The plot looks like a good fit for the most part
> #We can use predict() in HoltWinters by using how many steps we want forecast using the n.ahead
> #n=12 or 3 years in the future
> forecast <- predict(hw, n.ahead=12)
> plot(hw, forecast)
> #Add confidence intervals
> forecast <- predict(hw, n.ahead=12, prediction.interval=T, level=.95)
> plot(hw, forecast)
> x <- cumsum(xts(rnorm(500), Sys.Date()-500:1))
> #In order to use xts on HW, set gamma=F
> hwx <- HoltWinters(x, gamma=F)
> hwx
Holt-Winters exponential smoothing with trend and without seasonal component.
Call:
HoltWinters(x = x, gamma = F)
Smoothing parameters:
alpha: 1
beta : 0.02541815
gamma: FALSE
Coefficients:
[,1]
a 10.04464147
b 0.09480688
> #
> forecastx <- predict(hwx, n.ahead=20, prediction.interval = T, level=.95)
> #Plot cumulative time series with forecast with CI
> plot(hwx, forecastx)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment