R Time series - there are problems with creating bolling lines - you need a simple example, please

Learning the R language - I know how to make a moving average, but I need to do more - but I'm not statisticians - unfortunately, all the documents seem to be written for statisticians.

I do this in large numbers, it is really useful for the analysis of operational activities.

Here are the fields on each line to make bellinger stripes :

Value may be # calls, complaint ratio, nothing

TimeStamp | Value | Moving Average | Moving STDEVP | Lower management | Top control

In short, moving avg and stdevP point to the previous 8 or so values ​​in the series. Lower control at a given point in time = moving average - 2 * moving stdevP and upper control = moving average + 2 * moving stdevP

This can easily be done in excel for a single file, but if I can find a way to make R-work R better for my needs. I hope that faster and more reliable in automatic mode.

Links or tips will be appreciated.

+4
source share
2 answers

You can use the rollapply() function from the zoo package, providing you with a series of zoos:

 TimeSeries <- cumsum(rnorm(1000)) ZooSeries <- as.zoo(TimeSeries) BollLines <- rollapply(ZooSeries,9,function(x){ M <- mean(x) SD <- sd(x) c(M,M+SD*2,M-SD*2) }) 

Now you must remember that rollapply uses a centered frame, that is, it takes values ​​to the left and right of the current day. This is also more convenient and more true for determining the Bollinger band than your assumption of accepting x previous values.

If you do not want to convert to a zoo, you can also use vectors and write your own function. I added an S3-based build function, which also makes it easy to build calculations. Using these functions, you can do something like:

 TimeSeries <- cumsum(rnorm(1000)) X <- BollingerBands(TimeSeries,80) plot(X,TimeSeries,type="l",main="An Example") 

To obtain:

enter image description here

Function Codes:

 BollingerBands <- function(x,width){ Start <- width +1 Stop <- length(x) Trail <- rep(NA,ceiling(width/2)) Tail <- rep(NA,floor(width/2)) Lines <- sapply(Start:Stop,function(i){ M <- mean(x[(i-width):i]) SD <- sd(x[(i-width):i]) c(M,M+2*SD,M-2*SD) }) Lines <- apply(Lines,1,function(i)c(Trail,i,Tail)) Out <- data.frame(Lines) names(Out) <- c("Mean","Upper","Lower") class(Out) <- c("BollingerBands",class(Out)) Out } plot.BollingerBands <- function(x,data,lcol=c("red","blue","blue"),...){ plot(data,...) for(i in 1:3){ lines(x[,i],col=lcol[i]) } } 
+3
source

The R Graph Gallery (65) has an illustration giving a code for both calculating bands and calculating stock prices.

The 2005 code seems to work six years later and will give the current IBM stock price and come back in a few months.

Ibm bollinger bands

The most obvious mistake is the width of the narrow-band and voluminous lower charts that have been narrowed; there may be another number of days.

+1
source

All Articles