How To Calculate Simple Moving Average (SMA) using R?

by francisco , in category: Technical Analysis , 9 months ago

How To Calculate Simple Moving Average (SMA) using R?

Facebook Twitter LinkedIn Whatsapp

2 answers

by paris_marquardt , 9 months ago

@francisco 

To calculate the Simple Moving Average (SMA) using R, you can use the following code snippet:

1
2
3
4
5
6
7
8
# Create a vector of stock prices
stock_prices <- c(50, 55, 60, 65, 70, 75, 80, 85, 90, 95)

# Calculate the Simple Moving Average with a window size of 3
sma <- SMA(stock_prices, n = 3)

# Print the Simple Moving Average
print(sma)


In the code snippet above, replace the stock_prices vector with your own list of stock prices. The SMA() function calculates the Simple Moving Average with a specified window size (n parameter). In this example, the SMA is calculated with a window size of 3.


Make sure you have the TTR package installed in R to use the SMA() function. You can install the package using the following command:

1
install.packages("TTR")


After running the code snippet, you will get the Simple Moving Average values printed in the console.

by ray.hilll , 7 months ago

@francisco 

To calculate the Simple Moving Average (SMA) in R without using the TTR package, you can use the rollmean() function from the zoo package. Here is an example code snippet using rollmean() to calculate the SMA:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Load the zoo package
library(zoo)

# Create a vector of stock prices
stock_prices <- c(50, 55, 60, 65, 70, 75, 80, 85, 90, 95)

# Calculate the Simple Moving Average with a window size of 3
sma <- rollmean(stock_prices, k = 3, align = "right", fill = NA)

# Print the Simple Moving Average
print(sma)


In the code snippet above, we first load the zoo package and create a vector of stock prices. We then use the rollmean() function to calculate the Simple Moving Average with a window size of 3. The parameters k, align, and fill are used to specify the window size, alignment of the moving average, and how to handle missing values in the output.


After running the code snippet, you will see the Simple Moving Average values printed in the console.