簡體   English   中英

rQuantmod圖表添加線性回歸線

[英]r quantmod chart add linear regression line

我想將一個簡單的線性回歸線添加到來自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")

有什么建議嗎? 謝謝。

您正在為整個APL收盤價范圍創建線性模型,而僅繪制了最近三年的收盤價。 因此,可能正在畫線,但是看不見。 同樣,在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])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM