How can I implement a moving standard deviation for a time series?



I imported the following dataset and converted it into a time series.

dataSet = 
  Import["", "HeaderLines" -> 1 , "DateStringFormat" -> {"Year", "-", "Month"}]; 
ts = TimeSeries[dataSet];

Because I didn't find a built-in function function for a moving standard deviation, I implemented one with the following code.

A = Table[dataSet[[i ;; i + 11, 2]], {i, 1, Length[dataSet] - 11}];
B = TimeSeries[N[StandardDeviation @ Transpose[A]]];

  DateListPlot[ts, ImageSize -> Medium, PlotLegends -> {"Original"}], 
  ListLinePlot[MovingAverage[ts, 12], 
    PlotLegends -> {"Rolling Mean"}, PlotStyle -> {{Red, Dashing[Tiny]}}],
    PlotLegends -> {"Rolling STD"}, PlotStyle -> {{Green, Dashing[Large]}}]]

enter image description here

Please feel free to comment about implementing a moving standard deviation for a time series.


Dear Alexey Golyshev, m_goldberg, Yves Klett, Mr.Wizard Thanks for your reply.

  1. I applied the function "MovingMap", it works with list or vector, however, it doesn't accept timeseries(ts) as an argument.

    MovingMap[StandardDeviation, ts, 12]

  2. The "Moving STD" cannot be shown correctly; it is because I cannot find a function "MovingStandardDeviation" which is accepted the same arguments as MovingAverage.

  3. Source of data has been updated.""


Posted 2016-02-12T04:21:50.813

Reputation: 449

Since you don't give us data that allows to experiment with your code, alll I can do is give you some general advice: before trying to plot B, validate that it actually contains the numbers you want to plot. – m_goldberg – 2016-02-12T08:48:48.877

What exactly is the question here? Is this a request for a code-review? If so it should be tagged accordingly. Questions of the form “I use ______ for ______, what do you use?" are specifically off-topic. See: What types of questions should I avoid asking?

– Mr.Wizard – 2016-02-12T12:41:03.300

I think I misread your question. So you do not have a working solution, and you do not have code that you wish to debug? If this is the case then I suggest you rewrite the question removing things that are irrelevant, e.g. MovingAverage, and instead focus I a clear description of what you need. Example data would be useful as well; for example is it uniformly sampled or irregular? – Mr.Wizard – 2016-02-12T13:41:50.060




ma = MovingMap[Mean, ts, Quantity[12, "Months"]];    
sd = MovingMap[StandardDeviation, ts, Quantity[12, "Months"]];

 {ts, ma, ma + sd , ma - sd}, 
 PlotLegends -> {"Original", "Moving Mean", "+ Moving STD", "- Moving STD"}

enter image description here

Alexey Golyshev

Posted 2016-02-12T04:21:50.813

Reputation: 8 434

Dear Alexey Golyshev, Thank you. – madeinQuant – 2016-02-13T02:30:25.440