r quantmod图表添加线性回归线

时间:2017-07-16 12:37:09

标签: r plot charts linear-regression quantmod

我想在quantmod chartSeries函数中添加一个简单的线性回归线。

Input:
getSymbols('AAPL')

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

但是当我尝试添加该行时,它们都不起作用

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

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

有什么建议吗?感谢。

1 个答案:

答案 0 :(得分:0)

您正在为整个AAPL收盘价创建一个线性模型,而您只绘制收盘价的最后3年。所以这条线可能正在绘制,但不在视野范围内。此外,在lm中,您可能最适合索引而不是日期。

这对我有用:

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])