1

I have the following data:

enter image description here

I plotted the points of that data and then smoothed it on the plot using the following code :

scatter.smooth(x=1:length(Ticker$ROIC[!is.na(Ticker$ROIC)]), 
  y=Ticker$ROIC[!is.na(Ticker$ROIC)],col = "#AAAAAA", 
  ylab = "ROIC Values", xlab = "Quarters since Feb 29th 2012 till Dec 31st 2016")

enter image description here

Now I want to find the Point-wise slope of this smoothed curve. Also fit a trend line to the smoothed graph. How can I do that?

ForeverLearner
  • 179
  • 1
  • 4
  • 12

2 Answers2

7

There are some interesting R packages that implement nonparametric derivative estimation. The short review of Newell and Einbeck can be helpful: http://maths.dur.ac.uk/~dma0je/Papers/newell_einbeck_iwsm07.pdf

Here we consider an example based on the pspline package (smoothing splines with penalties on order m derivatives):

The data generating process is a negative logistic models with an additive noise (hence y values are all negative like the ROIC variable of @ForeverLearner) :

set.seed(1234)
x <- sort(runif(200, min=-5, max=5))
y = -1/(1+exp(-x))-1+0.1*rnorm(200)

We start plotting the nonparametric estimation of the curve (the black line is the true curve and the red one the estimated curve):

library(pspline)
pspl <- smooth.Pspline(x, y, df=5, method=3)
f0 <- predict(pspl, x, nderiv=0)

enter image description here

Then, we estimate the first derivative of the curve:

f1 <- predict(pspl, x, nderiv=1)
curve(-exp(-x)/(1+exp(-x))^2,-5,5, lwd=2, ylim=c(-.3,0))
lines(x, f1, lwd=3, lty=2, col="red")

enter image description here

And here the second derivative:

f2 <- predict(pspl, x, nderiv=2)
curve((exp(-x))/(1+exp(-x))^2-2*exp(-2*x)/(1+exp(-x))^3, -5, 5, 
      lwd=2, ylim=c(-.15,.15), ylab=)
lines(x, f2, lwd=3, lty=2, col="red")

enter image description here

Marco Sandri
  • 23,289
  • 7
  • 54
  • 58
4
#DATA
set.seed(42)
x = rnorm(20)
y = rnorm(20)

#Plot the points
plot(x, y, type = "p")

#Obtain points for the smooth curve
temp = loess.smooth(x, y, evaluation = 50) #Use higher evaluation for more points

#Plot smooth curve
lines(temp$x, temp$y, lwd = 2)

#Obtain slope of the smooth curve
slopes = diff(temp$y)/diff(temp$x)

#Add a trend line
abline(lm(y~x))
d.b
  • 32,245
  • 6
  • 36
  • 77
  • @d.b Thank you for that solution but since my data has negative numbers, I am not able to use 'loess'. Log of negative number is undefined and it throws an error. – ForeverLearner Apr 25 '17 at 16:17
  • @ForeverLearner what is stopping you from offsetting those values/normalizing... – Krupip Apr 25 '17 at 16:35