In the second part in a series on Tidy Time Series Analysis, we’ll again use
tidyquant to investigate CRAN downloads this time focusing on Rolling Functions. If you haven’t checked out the previous post on period apply functions, you may want to review it to get up to speed. Both
TTR have a number of “roll” and “run” functions, respectively, that are integrated with
tidyquant. In this post, we’ll focus on the
rollapply function from
zoo because of its flexibility with applying custom functions across rolling windows. If you like what you read, please follow us on social media to stay up on the latest Business Science news, events and information! As always, we are interested in both expanding our network of data scientists and seeking new clients interested in applying data science to business and finance.
An example of the visualization we can create using the
rollapply function with
We’ll primarily be using two libraries today.
CRAN tidyverse Downloads
We’ll be using the same “tidyverse” dataset as the last post. The script below gets the package downloads for the first half of 2017. The data is very noisy, meaning it’s difficult to identify trends. We’ll see how rolling functions can help shortly.
Rolling Window Calculations
What are rolling window calculations, and why do we care? In time series analysis, nothing is static. A correlation may exist for a subset of time or an average may vary from one day to the next. Rolling calculations simply apply functions to a fixed width subset of this data (aka a window), indexing one observation each calculation. There are a few common reasons you may want to use a rolling calculation in time series analysis:
- Measuring the central tendency over time (
- Measuring the volatility over time (
- Detecting changes in trend (fast vs slow moving averages)
- Measuring a relationship between two time series over time (
A moving average allows us to visualize how an average changes over time, which is very useful in cutting through the noise to detect a trend in a time series dataset. Further, by varying the window (the number of observations included in the rolling calculation), we can vary the sensitivity of the window calculation. This is useful in comparing fast and slow moving averages (shown later).
Combining a rolling mean with a rolling standard deviation can help detect regions of abnormal volatility and consolidation. This is the concept behind Bollinger Bands in the financial industry. The bands can be useful in detecting breakouts in trend for many time series, not just financial.
Time Series Functions
TTR packages have some great functions that enable working with time series. Today, we’ll take a look at the Rolling or Running Functions from the
TTR packages. The roll apply functions are helper functions that enable the application of other functions across a rolling window. What “other functions” can be supplied? Any function that returns a numeric vector such as scalars (
max, etc) or vectors (
summary, and custom functions). The rolling (or running) functions are in the format
roll[apply or fun name] for
TTR. You can see which functions are integrated into
tidyquant package below:
We’ll investigate the
rollapply function from the
zoo package because it allows us to use custom functions that we create!
Tidy Implementation of Time Series Functions
We’ll be using the
tq_mutate() function to apply time series functions in a “tidy” way. The
tq_mutate() function always adds columns to the existing data frame (rather than returning a new data frame like
tq_transmute()). It’s well suited for tasks that result in column-wise dimension changes (not row-wise such as periodicity changes, use
tq_transmute for those!). It comes with a bunch of integrated financial and time series package integrations. We can see which apply functions will work by investigating the list of available functions returned by
Tidy Application of Rolling Functions
As we saw in the tidyverse daily download graph above, it can be difficult to understand changes in trends just by visualizing the data. We can use rolling functions to better understand how trends are changing over time.
Rolling Mean: Inspecting Fast and Slow Moving Averages
Suppose we’d like to investigate if significant changes in trend are taking place among the package downloads such that future downloads are likely to continue to increase, decrease or stay the same. One way to do this is to use moving averages. Rather than try to sift through the noise, we can use a combination of a fast and slow moving average to detect momentum.
We’ll create a fast moving average with
width = 30 days (just enough to detrend the data) and a slow moving average with
width = 90 days (slow window = 3X fast window). To do this we apply two calls to
tq_mutate(), the first for the 30 day (fast) and the second for the 90 day (slow) moving average. There are three groups of arguments we need to supply:
selectthe column to apply the mutation to (“count”) and the mutation function (
mutate_fun) to apply (
rollapplyargs: These set the
align = "right"(aligns with end of data frame), and the
FUNwe wish to apply (
meanin this case).
FUNargs: These are arguments that get passed to the function. In this case we want to set
na.rm = TRUEso
NAvalues are skipped if present.
I add an additional
col_rename, at the end to rename the column. This is my preference, but it can be placed with the other
tq_mutate args above.
The output is a little difficult to see. We’ll need to zoom in a little more to detect momentum. Let’s drop the “count” data from the plots and inspect just the moving averages. What we are looking for are points where the fast trend is above (has momentum) or below (is slowing) the slow trend. In addition, we want to inspect for cross-over, which indicates shifts in trend.
We can see that several packages have strong upward momentum (
lubridate). Others such as
tidyr seem to be cycling in a range. Others such as
stringr have short term downward trends (keep in mind these packages are getting the most downloads of the bunch). The last point is this is only a six month window of data. The long term trends may be much different than short term, but we’ll leave that for another day.
Rolling Custom Functions: Useful for multiple statistics
You may find in your analytic endeavors that you want more than one statistic. Well you’re in luck with custom functions! In this example, we’ll create a custom function,
custom_stat_fun_2(), that returns four statistics:
- standard deviation
- 95% confidence interval (mean +/- 2SD)
The custom function can then be applied in the same way that
mean was applied.
Now for the fun part: performing the “tidy” rollapply. Let’s apply the
custom_stat_fun_2() to groups using
tq_mutate() and the rolling function
rollapply(). The process is almost identical to the process of applying
mean() with the main exception that we need to set
by.column = FALSE to prevent a “length of dimnames ” error. The output returned is a “tidy” data frame with each statistic in its own column.
We now have the data needed to visualize the rolling average (trend) and the 95% confidence bands (volatility). If you’re familiar with finance, this is actually the concept of the Bollinger Bands. While we’re not trading stocks here, we can see some similarities. We can see periods of consolidation and periods of high variability. Many of the high variability periods are when the package downloads are rapidly increasing. For example,
tidyquant all had spikes in downloads causing the 95% Confidence Interval (CI) bands to widen.
The rollapply functions from
TTR can be used to apply rolling window calculations. The
tq_mutate() function from
tidyquant enables efficient and “tidy” application of the functions. We were able to use the
rollapply functions to visualize averages and standard deviations on a rolling basis, which gave us a better perspective of the dynamic trends. Using custom functions, we are unlimited to the statistics we can apply to rolling windows. In fact, rolling correlations, regressions, and more complicated statistics can be applied, which will be the subject of the next posts. Stay tuned! 😉
We have a full suite of data science services to supercharge your organizations financial and business performance! For example, our experienced data scientists reduced a manufacturer’s sales forecasting error by 50%, which led to improved personnel planning, material purchasing and inventory management.
How do we do it? With team-based data science: Using our network of data science consultants with expertise in Marketing, Forecasting, Finance and more, we pull together the right team to get custom projects done on time, within budget, and of the highest quality. Learn about our data science services or contact us!
We’re super excited to announce four new data scientists have joined our network!
- Max, a data science expert in Marketing Analytics
- Robert, a data scientist with background in causal inference, Bayesian statistics, and STAN
- Mary, an expert in Anti-Money Laundering (AML)
- Nana, a data scientist with a background in applied statistics
We are growing! Let us know if you are interested in joining our network of data scientist consultants. If you have expertise in Marketing Analytics, Data Science for Business, Financial Analytics, Forecasting or data science in general, we’d love to talk. Contact us!
- Connect with @bizScienc on twitter!
- Like us on Facebook!!!
- Follow us on LinkedIn!
- Sign up for our insights blog to stay updated!
- If you like our software, star our GitHub packages 🙂