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

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

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

Facebook Twitter LinkedIn Whatsapp

1 answer

by paris_marquardt , 2 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.