Patio
Patio

Reputation: 23

How to calculate several moving averages in R

I have 10 years of daily closing prices for the stock: BNS.TO. I want to calculate several moving averages.

If MA n = (P t-1 + P t-2 + P t-3 + … + P t-n) / n

Where P = the closing prices and n = number of periods to be averaged

I would need n to be all values ranging from 3 to 200. How should I go about this?

Here is where the data can be downloaded if need be: https://ca.finance.yahoo.com/quote/BNS.TO/history?p=BNS.TO

Thank you

Upvotes: 0

Views: 1035

Answers (3)

Lennyy
Lennyy

Reputation: 6132

MA <- sample(30:70, 2500, T)

library(zoo)
rollingmeans <- lapply(3:200, function(x) {rollmean(MA, x)})

This generates a list with rolling means of widths 3 until widths of 200.

Upvotes: 0

SatZ
SatZ

Reputation: 450

You can use the pracma package in R. You could have landed on these pages with a simple google search.

Reference: https://www.rdocumentation.org/packages/pracma/versions/1.9.9/topics/movavg

if (!require("pracma", character.only=T, quietly=T)) {
  install.packages("pracma")
  library("pracma", character.only=T)
}

MySeries<-1:300 #sample data
df<-data.frame(lapply(3:200, function(x){movavg(MySeries,n=x,"s")}))
names(df)<-paste0("MA",3:200)

You can read more about the function on the R documentation page for that package

Upvotes: 0

MSW Data
MSW Data

Reputation: 461

You can use SMA function from TTR package.

library(TTR);
data(ttrc);

# Assume mydata is ttrc    
mydata = ttrc;

# SMA for 5 days - you can also loop thru to vary from 3 days to 200 days
n = paste("day",5,sep="")

# To assign to mydata use !!
mydata = mutate(mydata,!!n := SMA(Close,5) )

Upvotes: 0

Related Questions