2017-07-16 138 views
1

我想从quantmod chartSeries函数向图中添加一个简单的线性回归线。r Quantmod Chart添加线性回归线

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

有什么建议?谢谢。

回答

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