The Moving Average Convergence Divergence (MACD) is a popular technical indicator used by traders to identify trends in stock prices. The MACD consists of two lines – the MACD line and the signal line. The MACD line is calculated by subtracting the 26-day exponential moving average (EMA) from the 12-day EMA. The signal line is a 9-day EMA of the MACD line. Calculate MACD in R is an extension from one of an earlier post, MACD in Excel. By using R Programming, the same output as 273 lines of VBA code can be achieved within 20 lines.
To calculate MACD with signal line and histogram in R, we can use the TTR
package. Here’s how to install and load the package:
1 2 |
install.packages("TTR") library(TTR) |
To pull the last 90 days of closing prices for TSLA stock, we can use the quantmod
package. Here’s how to install and load the package, and pull the data:
1 2 3 4 5 6 |
install.packages("quantmod") library(quantmod) # Pull TSLA data for the last 90 days tsla <- getSymbols("TSLA", auto.assign = FALSE, from = Sys.Date() - 90) tsla_close <- Cl(tsla) |
Now that we have the closing prices for TSLA, we can calculate the MACD with signal line and histogram using the MACD
function from the TTR
package:
1 2 |
# Calculate MACD with signal line and histogram macd <- MACD(tsla_close) |
The MACD
function returns a list with three elements: macd
(the MACD line), signal
(the signal line), and hist
(the histogram). To account for missing values, it’s possible to initialize the histogram with zeros. This can be achieved by first identifying the missing values in the macd$hist object using the is.na() function. We can plot MACD and signal lines, and the histogram using the plot
function:
1 2 3 4 5 6 7 8 |
# Identify missing values in macd$hist missing_values <- is.na(macd$hist) # Replace missing values with zeros macd$hist[missing_values] <- 0 # Plot histogram barplot(macd$hist, col = "green", main = "TSLA MACD Histogram", xlab = "Date", ylab = "Histogram") |
Here’s the complete code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# Install and load packages install.packages("TTR") library(TTR) install.packages("quantmod") library(quantmod) # Pull TSLA data for the last 90 days tsla <- getSymbols("TSLA", auto.assign = FALSE, from = Sys.Date() - 90) tsla_close <- Cl(tsla) # Calculate MACD with signal line and histogram macd <- MACD(tsla_close) # Plot MACD and signal lines plot(macd$macd, type = "l", col = "blue", main = "TSLA MACD") lines(macd$signal, col = "red") # Plot histogram barplot(macd$hist, col = "green", main = "TSLA MACD Histogram", xlab = "Date", ylab = "Histogram") |
That’s it! Now you know how to calculate MACD with signal line and histogram in R!