How can I plot the regression lines analysis in R

215 Views Asked by At

I want to plot regression lines in R for technical analysis.

First, I regress the price on the date and I get the main regression line. However, also, I need lines that correspond to (Main regression line +- 2*standard deviation).

Do you know how I can implement this? I already checked the TTR package, but I couldn't find a built-in indicator for this purpose.

Thank you.

2

There are 2 best solutions below

0
On

To obtain points on the regression line, you can use the function predict on the fitted model. For confidence intervals, use the options interval and level, e.g.:

lsq <- lm(y ~ x, data)
predict(lsq, data.frame(x=c(12,45), interval="confidence", level=0.95)
0
On

To expand on @cdalitz answer this is how you plot the regression line with the confidence interval:

# Generate data
set.seed(123)
n = 100
x = runif(n)
y = 2 * x + rnorm(n, sd = 0.5)

m = lm(y ~ x)
newx = seq(min(x), max(x), length.out = 100)
pred = predict(m, newdata = data.frame(x = newx), interval="confidence", level=0.95)

# Plot data
plot(x, y)
# Plot model
abline(m)
# Plot 95% confidence interval
lines(newx, pred[, 2], col = "red", lty = 2)     
lines(newx, pred[, 3], col = "red", lty = 2)

enter image description here

This question also shows many ways to do the same thing.