Search code examples
linedifflmquantmod

How to calculate slope of the line


I am trying to calculate the slope of the line for a 50 day EMA I created from the adjusted closing price on a few stocks I downloaded using the getSymbols function.

My EMA looks like this :

getSymbols("COLUM.CO")
COLUM.CO$EMA <- EMA(COLUM.CO[,6],n=50)

This gives me an extra column that contains the 50 day EMA on the adjusted closing price. Now I would like to include an additional column that contains the slope of this line. I'm sure it's a fairly easy answer, but I would really appreciate some help on this. Thank you in advance.


Solution

  • A good way to do this is with rolling least squares regression. rollSFM does a fast and efficient job for computing the slope of a series. It usually makes sense to look at the slope in relation to units of price activity in time (bars), so x can simply be equally spaced points.

    The only tricky part is working out an effective value of n, the length of the window over which you fit the slope.

    library(quantmod)
    getSymbols("AAPL")
    AAPL$EMA <- EMA(Ad(AAPL),n=50)
    # Compute slope over 50 bar lookback:
    AAPL <- merge(AAPL, rollSFM(Ra = AAPL[, "EMA"], 
                                Rb = 1:nrow(AAPL), n = 50))
    

    The column labeled beta contains the rolling window value of the slope (alpha contains the intercept, r.squared contains the R2 value).