2017-07-16 140 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])