简体   繁体   中英

r quantmod chart add linear regression line

I would like to add a simple linear regression line into the plot from quantmod chartSeries function.

Input:
getSymbols('AAPL')

chartSeries(AAPL, subset='last 3 years', TA = NULL, theme = "white", up.col = "green", dn.col = "red")

But when I try to add the line, none of them work

addLines(lm(Cl(AAPL)~index(AAPL)),col="blue", on=1)

abline(lm(Cl(AAPL)~index(AAPL)),col="blue")

Any advice ? Thanks.

You are creating a linear model for the entire range of AAPL closing prices, whereas you are plotting only the last 3 years of closing prices. So the line is probably being drawn, but out of view. Also, in lm, you may be better off fitting to the indices rather than the dates.

This works for me:

library(quantmod)
library(TimeWarp)

getSymbols('AAPL')

# Subset to your desired 3-year date range
end = as.character(last(index(AAPL)))
start = as.character(TimeWarp::dateWarp(last(index(AAPL)),"-3 years"))
subset = AAPL[paste(start,end,sep="/")]

# Work with subset from now on. Chart subset (note I removed
# subset argument from call to chartSeries)
chartSeries(subset, TA = NULL, theme = "white", up.col = "green", dn.col = "red")

# Linear model on same range as your chart
indices = 1:nrow(subset)
model=lm(AAPL.Close~indices,data=subset)

# Draw line
abline(model$coefficients[1],model$coefficients[2])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM