R: left one-sided moving average for periods (months)

I have a question that might be trivial for most of you guys. I tried a lot, did not come to a solution, so I would be glad if someone could give me a hint. The starting point is the weekly xts series.

  Month Week Value Goal
 Dec 2011 W50 aa
 Dec 2011 W51 b mean (a, b)
 Dec 2011 W52 c mean (a, b, c)
 Dec 2011 W53 d mean (a, b, c, d)
 Jan 2012 W01 ee
 Jan 2012 W02 f mean (e, f)
 Jan 2012 W03 g mean (e, f, g)
 Jan 2012 W04 h mean (e, f, g, h)
 Feb 2012 W05 ii
 Feb 2012 W06 j mean (i, j)

Please excuse the Excel notation, but I think it’s pretty clear what I want to do: I want to calculate the left-side moving average for the β€œValue” column, but only for the corresponding month, since it is displayed in the Target column. I experimented with apply.monthly () and period.apply () . But I did not understand what I want. Can any of you give me a hint how to solve the problem? Just a hint which function should I use will be enough!

Many thanks!

Yours faithfully,

Andreas

+4
source share
2 answers

apply.monthly will not work, because it assigns only one value to the endpoint of the period, while you want to assign many values ​​to each monthly period.

You can do this quite easily by dividing your xts data by months, applying a cumulative average function to each and again compiling the list.

 library(quantmod) # Sample data getSymbols("SPY") spy <- to.weekly(SPY) # Cumulative mean function cummean <- function(x) cumsum(x)/seq_along(x) # Expanding average calculation spy$EA <- do.call(rbind, lapply(split(Cl(spy),'months'), cummean)) 
+2
source

I hope I understood your question correctly. but this is what you are looking for:

  require(plyr) require(PerformanceAnalytics) ddply(data, .(Week), summarize, Goal=apply.fromstart(Value,fun="mean")) 

this should work - although a reproducible example would be nice.

that's what he does.

 df <- data.frame(Week=rep(1:5, each=5), Value=c(1:25)*runif(25)) #sample data require(plyr) require(PerformanceAnalytics) df$Goal <- ddply(df, .(Week), summarize, Goal=apply.fromstart(Value,FUN="mean"))[,2] 

result:

  Week Value Goal 1 1 0.7528037 0.7528037 2 1 1.9622622 1.3575330 3 1 0.3367802 1.0172820 4 1 2.5177284 1.3923936 

?ddply course, you can get additional information through the help ?ddply or ?apply.fromstart .

+2
source

Source: https://habr.com/ru/post/1395379/


All Articles