简体   繁体   English

rQuantmod图表添加线性回归线

[英]r quantmod chart add linear regression line

I would like to add a simple linear regression line into the plot from quantmod chartSeries function. 我想将一个简单的线性回归线添加到来自quantmod chartSeries函数的绘图中。

Input:
getSymbols('AAPL')

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

But when I try to add the line, none of them work 但是当我尝试添加行时,它们都不起作用

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

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

Any advice ? 有什么建议吗? Thanks. 谢谢。

You are creating a linear model for the entire range of AAPL closing prices, whereas you are plotting only the last 3 years of closing prices. 您正在为整个APL收盘价范围创建线性模型,而仅绘制了最近三年的收盘价。 So the line is probably being drawn, but out of view. 因此,可能正在画线,但是看不见。 Also, in lm, you may be better off fitting to the indices rather than the dates. 同样,在lm中,最好适合索引而不是日期。

This works for me: 这对我有用:

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