作者:徐瑞龙,量化分析师,R语言中文社区专栏作者
博客专栏:
https://www.cnblogs.com/xuruilong100
本文翻译自《Demo Week: Tidy Forecasting with sweep》
原文链接:
www.business-science.io/code-tools/2017/10/25/demo_week_sweep.html
sweep
的用途
正如 broom
包之于 stats
包,sweep
包用来简化使用 forecast
包的工作流。本教程将逐一介绍常用函数 sw_tidy
、sw_glance
、sw_augment
和 sw_sweep
的用法。
sweep
和 timetk
带来的额外好处是,如果 ts
对象是由 tbl
对象转换来的,那么在预测过程中日期和时间信息会以 timetk
索引的形式保留下来。一句话概括:这意味着我们最终可以在预测时使用日期,而不是 ts
类型数据使用的规则间隔数字日期。
加载包
本教程要使用到四个包:
sweep
:简化forecast
包的使用forecast
:提供 ARIMA、ETS 和其他流行的预测算法tidyquant
:获取数据并在后台加载tidyverse
系列工具timetk
:时间序列数据处理工具,用来将tbl
转换成ts
# Load libraries library(sweep) # Broom-style tidiers for the forecast package library(forecast) # Forecasting models and predictions package library(tidyquant) # Loads tidyverse, financial pkgs, used to get data library(timetk) # Functions working with time series
数据
我们使用 timetk
教程中数据——啤酒、红酒和蒸馏酒销售数据(https://fred.stlouisfed.org/series/S4248SM144NCEN),
用 tidyquant
中的 tq_get()
函数从 FRED 获取。
# Beer, Wine, Distilled Alcoholic Beverages, in Millions USD beer_sales_tbl <- tq_get( "S4248SM144NCEN", get = "economic.data", from = "2010-01-01", to = "2016-12-31") beer_sales_tbl
## # A tibble: 84 x 2 ## date price ## <date> <int> ## 1 2010-01-01 6558 ## 2 2010-02-01 7481 ## 3 2010-03-01 9475 ## 4 2010-04-01 9424 ## 5 2010-05-01 9351 ## 6 2010-06-01 10552 ## 7 2010-07-01 9077 ## 8 2010-08-01 9273 ## 9 2010-09-01 9420 ## 10 2010-10-01 9413 ## # ... with 74 more rows
可视化数据是一个好东西,这有助于帮助我们了解正在使用的是什么数据。可视化对于时间序列分析和预测尤为重要。我们将使用 tidyquant
画图工具:主要是用 geom_ma(ma_fun = SMA,n = 12)
来添加一个周期为 12 的简单移动平均线来了解趋势。我们还可以看到似乎同时存在着趋势性(移动平均线以近似线性的模式增长)和季节性(波峰和波谷倾向于在特定月份发生)。
# Plot Beer Sales beer_sales_tbl %>% ggplot(aes(date, price)) + geom_line(col = palette_light()[1]) + geom_point(col = palette_light()[1]) + geom_ma(ma_fun = SMA, n = 12, size = 1) + theme_tq() + scale_x_date(date_breaks = "1 year", date_labels = "%Y") + labs(title = "Beer Sales: 2007 through 2016")
现在你对我们要分析的时间序列有了直观的感受,那么让我们继续!
Demo:forecast
+ sweep
的简化预测工作流
我们将联合使用 forecast
和 sweep
来简化预测分析。