Search code examples
rplotquantmodmoving-averagetechnical-indicator

How to create custom indicator? Slope of the line of 50 day EMA


I have been creating a few technical indicators using Quantmod's NewTa function. I've been trying to create a custom indicator that ideally should be charted using ChartSeries. This indicator should show the slope of the line of the 50 day EMA of the adjusted closing price.

getSymbols("NOVO-B.CO")
p <- na.omit('NOVO-B.CO')
FiftyEMA <- function(x){


MA <- removeNA((EMA(p[,6],n=50)))

}
SlopeFiftyEMA <- function(x){
  run=(FiftyEMA(y)/FiftyEMA(x))
}
Slope.Indicator <- newTA(SlopeFiftyEMA,legend.name = "50 Day EMA Slope of Line Indicator")
Slope.Indicator()

This gives me the error: Error in get.current.chob() : improperly set or missing graphics device

I also tried a new code that gives me an actual INDICATOR! Please let me know what you think (if you think it looks correct or not):

First I export the data to excel: (the stock data is still denoted as p)

write.csv(p,"data")

import data

x <- data[,1]
y <- data[,7]
MA <- removeNA(EMA(y,n=50))
length(MA)

length of MA = 1923

l=1:1923
SlopeFiftyEMA <- function(x){
(diff(MA)/diff(l))
}
Slope.Indicator <- newTA(SlopeFiftyEMA,legend.name = "50 Day EMA Slope of Line Indicator")
twelvemonths="last 12 months"
chartSeries(p,subset = twelvemonths,theme = 'white',up.col = 'blue',dn.col = 'grey',name ="Custom Indicators")
Slope.Indicator()

Custom Indicator on the Chart

Any Input anyone? Last time I posted there was no indicator

Thanks in advance!


Solution

  • Your first error seems to exist because you don't call chartSeries before calling Slope.indicator(). But your code is a bit messy, including not defining y (maybe you introduce it later in import data).

    The approach presented here will plot the slope of the MA according to linear regression, using chart_Series (arguably cleaner plots than the original chartSeries). Two types of slopes are computed, including the one you proposed, which is the differences of the EMA.

    getSymbols(c("NOVO-B.CO"))
    
    x <- `NOVO-B.CO`
    x[, c(1:4, 6)] <- na.locf(x[, c(1:4, 6)])
    x$EMA <- EMA(Cl(x), n = 50)
    x <- merge(x, rollSFM(Ra = x[, "EMA"], Rb = 1:NROW(x), n = 20))
    
    x <- merge(x, setNames(diff(x$EMA), "diff1"))
    
    chart_Series(x, subset = "2016/")
    add_TA(x$EMA, on = 1, col = "purple")
    # Plot the slope of the MA:
    add_TA(x$beta, col = "green")
    # Plot the 1 lag diff of the moving average:
    add_TA(x$diff1, lty = 2)
    

    enter image description here