2017-07-16 18 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年間のみをプロットしています。ラインはおそらく描かれているが、見えない。また、作品では、日付ではなく指標にフィットするほうがよいかもしれません。

これが私の作品:

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