youtube video link with explanations for these examples https://youtu.be/rfpK7YxJTOA https://i9.ytimg.com/vi_webp/rfpK7YxJTOA/mqdefault.webp?time=1611977700000&sqp=COSn04AG&rs=AOn4CLCky0oDkizn7UzAtga04ZoXqi-Ghw
Imagine you have closing prices of a share for the last one year. SMA or simple moving average is an arithmetic moving average calculated by adding the recent prices and then dividing that value by the number of time periods in the calculation average.
Moving averages are important to show the current price trends and the potential for a change in trend.
5-20 period SMA are generally used for short-term trends.
The Moving average can also be used to show other trends, eg. daily sales, daily customer numbers, daily incoming patients etc.
We will be using the following libraries ggplot2 for plotting our chart quantmod for getting the share price data automatically.
# We would need the following libraries
# Uncomment the following two lines to install the packages( if not already installed)
# install.packages("ggplot2")
# install.packages("quantmod")
library(ggplot2)
library(quantmod)
# We have defined the variables so that you can change the
# share ticker symbol and the date range here
myShare <- "IBM"
myStartDate <- '2020-01-01'
myEndDate <- Sys.Date()
# Get the data in df
# We want the stock prices to be loaded in our object called df, hence we set auto.assign = FALSE
# If we set auto.assign =TRUE then the data gets loaded to an object which is the same
# as the name(symbol) of the stock
df <- getSymbols(myShare
, from = myStartDate
, to = myEndDate
, warnings = FALSE
, auto.assign = FALSE)
df <- data.frame(df)
#Change the names in the data frame
names(df) <- c('Open', 'High', 'Low', 'Close','Volume','Adjusted')
# Convert the row names to a column
df$Date <- as.Date(rownames(df))
The folowing commands produce the SMA. You can change the value of n to the desired value. eg. n = 20 will produce 20 days simple moving avarage (SMA)
# Calculate 5 day moving average
df$MA5 <- TTR::SMA( df$Close, n = 5)
# Calculate 10 days moving average
df$MA10 <- TTR::SMA( df$Close, n = 10)
Let us plot the chart with the closing prices of the share, MA5 amd MA10.
# Now we plot the values in ggplot
pl <- ggplot(df , aes(x = Date))
pl <- pl + geom_line(aes(y = Close, color = "Close"), group = 1)
pl <- pl + geom_line(aes(y = MA5, color = "MA5"),group = 1)
pl <- pl + geom_line(aes(y = MA10, color = "MA10"), group = 1)
pl <- pl + theme_minimal()
#pl <- pl + theme(legend.title = "Moving Ave." )
pl <- pl + theme(legend.position = "top")
pl <- pl + labs(title ="Moving averages")
pl <- pl + labs(color="Prices")
pl
Here is the link to the youtube video which explains the above examples.
techanswers88