ERROR in R: decompose(y) : time series has no or less than 2 periods - r

I have a time series data of daily transactions, starting from 2017-06-28 till 2018-11-26.
The data looks like this:
I am interested to use decompose() or stl() function in R. But I am getting
error:
decompose(y) : time series has no or less than 2 periods
when I am trying to use decompose()
and
Error in stl(y, "periodic") :
series is not periodic or has less than two periods
when I am trying to use stl().
I have understood that I have to specify the period, but I am not able to understand what should be the period in my case? I have tried with the following toy example:
dat <- cumsum(rnorm(51.7*10))
y <- ts(dat, frequency = 517)
plot.ts(y)
stl(y, "periodic")
But I couldn't succeed. Any help will be highly appreciated.

The frequency parameter reflects the number of observations before the seasonal pattern repeats. As your data is daily, you may want to set frequency equal to 7 or 365.25 (depending on your business seasonality).
Of course, the larger the business seasonality, the more data you need (i.e. more than 2 periods) in order to decompose your time series. In your case, you set the frequency to 517, but have data available for less than two periods. Thus, the seasonal decomposition cannot happen.
For more info, please see: Rob Hyndman's Forecasting Principles and Practice book

Related

How to create and analyze a time series with variable test frequency in R

Here is a short description of the problem I am trying to solve: I have test data for multiple variables (weight, thickness, absorption, etc.) that are taken at varying intervals over time - no set schedule, sometimes a test a day, sometimes days might go between tests. I want to detect trends in each of these and alert stake holders when any parameter is trending up/down more than a certain amount. I first did a linear model between each variable's raw data and test time (I converted the test time to days or weeks since a fixed date) and create a table with slopes for each variable - so the stake holders can view one table for all variables and quickly see if any of them is raising concern. The issue was that the data for most variables is very noisy. Someone suggested using time series functions, separating noise and seasonality from the trends, and studying the trend component for a cleaner analysis. I started to look into this and see a couple concerns/questions already:
Time series analysis seems to require specifying a frequency - how do you handle this if your test data is not taken at regular intervals
If one gets over the issue in #1 above, decomposes the data, and gets the trend separated out (ie. take out particularly the random variation/noise), how would you then get a slope metric from that? Namely, if I wanted to then fit a linear model to the trend component of the raw data (after decomposing), what would be the x (independent) variable? Is there a way to connect the trend component of the ts-decompose function with the original data's x-axis data (in this case the actual test date/times, say converted to weeks or days from a fixed date)?
Finally, is there a better way of accomplishing what I explained above? I am only looking for general trends over time - say over 3 months of data, not day to day trends.
Time series are generally used to see if previous observations of a variable have influence on future observations. You would model under the assumption that the previous observations are able to predict the future observations. That is the reason for that most (not all) time series models require evenly spaced instances of training data. If your data is not only very noisy, but also not collected on a regular basis, then you should seriously consider if time series is the appropriate choice of modelling.
Time series analysis seems to require specifying a frequency - how do you handle this if your test data is not taken at regular intervals.
What you can do, is creating an aggregate by increasing the time bucket (shift from daily data to a weekly average for instance) such that every unit of time has an instance of training data. Following your final comment, you could create the average of the observations of the last 3 months of data instead from the observations.
If one gets over the issue in #1 above, decomposes the data, and gets the trend separated out (ie. take out particularly the random variation/noise), how would you then get a slope metric from that? Namely, if I wanted to then fit a linear model to the trend component of the raw data (after decomposing), what would be the x (independent) variable?
In the simplest case of a linear model, the independent variable is the unit of time corresponding to the prediction you are trying to make. However this is not always regarded a time series model.
In the case of an autoregressive model, this would be the previous observation of what you are trying to predict, something similar to y(t) = x(t-1), for instance multiplied by a smoothing factor. I encourage you to read Forecasting: principles and practice which is an excellent book on the matter.
Is there a way to connect the trend component of the ts-decompose function with the original data's x-axis data (in this case the actual test date/times, say converted to weeks or days from a fixed date)?
The function decompose.ts returns a list which includes trend. Trend is a vector of the estimated trend components corresponding to it's respective time value.
Let's create an example time series with linear trend
df <- data.frame(
date = seq(from = as.Date("2021-01-01"), to = as.Date("2021-01-10"), by=1)
)
df$value <- jitter(seq(from = 1, to = nrow(df), by=1))
time_series <- ts(df$value, frequency = 5)
df$trend <- decompose(time_series)$trend
> df
date value trend
1 2021-01-01 0.9170296 NA
2 2021-01-02 1.8899565 NA
3 2021-01-03 3.0816892 2.992256
4 2021-01-04 4.0075589 4.042486
5 2021-01-05 5.0650478 5.046874
6 2021-01-06 6.1681775 6.051641
7 2021-01-07 6.9118942 7.074260
8 2021-01-08 8.1055282 8.041628
9 2021-01-09 9.1206522 NA
10 2021-01-10 9.9018900 NA
As you see, the trend component already is an estimate of the dependent variable at the corresponding time. In decompose the estimate of trend is based on a moving average.

Time series - detecting seasonality to set frequency

I have daily level data for time series, and i am trying to understand whether it has a trend or seasonal component. The data i have is only for 699 days, so less than 2 years. To convert it to time series what frequency should be set? I have read about it and suggested value is 7, but looking at the data i feel there isn't a seasonal component in it at all. Below is the plot of the time series.
Please suggest how can i go about it. Thanks!

setting the parameter "frequency" for the multi-year average of hourly ozone data

I am trying to decompose a time series which is the monthly multi-year average of hourly ozone data. There are 288 data points (24 hours * 12 months). STL needs ts object to extract the components of time series. And ts has the parameter "frequency". As far as I know, it is the number of observations in one period. For example, it is 12 for monthly averaged temperature data.
What is the frequency for my case since If I use 288
data_ts=stl(ts(data,frequency = 288),s.window = "per"))
As expected, it throws the error "series is not periodic or has less than two periods".
BTW, I am aware of other methods to extract seasonality, but I also need to check the results with STL.
Best
Assuming you have hourly data, there are 24 periods per day, and 24*365.25 periods per year on average. Months would appear to be irrelevant for a natural phenomenon such as ozone. Similarly, weeks are irrelevant. So you just need seasonal periods of 24 and 24*265.35.
The mstl() function from the forecast package can handle multiple seasonal periods.
library(forecast)
data_ts <- mstl(msts(data, seasonal.periods = c(24, 24*365.25)))
However, if you actually have monthly data, then the frequency is 12.
data_ts <- mstl(ts(data, frequency = 12))
As you can see in the picture ACF, the ACF of your data clearly shows an annual seasonal trend.
it peaks at yearly lag at about 12, 24, etc.
If I am behalf on you, I will use freq=12 to decompose my time series data.

Predicting multivariate time series with RNN

I have been experimenting with a R package called RNN.
The following is the code site:
https://github.com/bquast/rnn
It has a very nice example for financial time series prediction.
I have read the code and I understand it uses the sequence of the time series to predict in advance the value of next day instrument.
The following is an example of run with 10 hidden nodes and 200 epochs
RNN financial time series prediction
What I would expect as result is that the algorithm succeed, at least in part, to predict in advance the value of the instrument.
From what I can see, apparently is only approximating the value of the time series at the current day, not giving any prediction on the next day.
Is my expectation wrong?
This code is very simple, how would you improve it?
y <- X[,1:input$training_amount+input$prediction_gap,as.numeric(input$target)]
matrix(y, ncol=input$training_amount)
y.train moves all the data forward by a day so that is what is being trained on - next day data for the currency pair you care about. With ncol = training_amount when there are too many columns (with them now equal to training_amount + prediction_gap), the first data points fall off; hence all the data gets moved forward by the prediction_gap.

R - Trend estimation for short time series

I have very short time series of data from a climatic experiment that I did back in 2012. The data consists of daily water solution flux and daily CO2 flux data. The CO2 flux data comprises 52 days and the water solution flux data is only 7 days long. I have several measurements a day for the CO2 flux data but I calculated daily averages.
Now, I would like to know if there is a trend in these time series. I have figured out that I can use the Kendall trend test or a Theil-Sen trend estimator. I used the Kendall test before for a time series spanning several years. I don't know how to use the Theil-Sen trend estimator.
I put my data into an ts object in R, but when I tried doing a decompositon (using the function decompose) I get the error that the time series is spanning less than 2 periods. I would like to extract the trend data and then do a Mann-Kendall test on it.
Here is the code that I got so far:
myexample <- structure(c(624.27, 682.06, 672.77,
765.96, 759.52, 760.38, 742.81
), .Names = c("Day1", "Day2", "Day3", "Day4", "Day5", "Day6",
"Day7"))
ts.object <- ts(myexample, frequency = 365, start = 1)
decomp.ts.obj <- decompose(ts.obj, type = "mult", filter=NULL)
# Error in decompose(ts.obj, type = "mult", filter = NULL)
Can anyone help me on how to do a trend analysis with my very short time series? Any google-fu was to no avail. And, can someone tell me what the size of the Kendall tau means? It spans values from -1 to 1. Is a tau=0.5 a strong or a weak trend?
Thanks,
Stefan
I would be tempted to do something simple like
d <- data.frame(val=myexample,ind=seq(myexample))
summary(lm(val~ind,d))
or
library(lmPerm)
summary(lmp(val~ind,d))
or
cor.test(~val+ind,data=d,method="kendall")
Whether tau=0.5 is strong or weak depends a lot on context. In this case the p-value is 0.24, which says at least that this signal (based on rank alone) is not distinguishable from an appropriate null signal.

Resources