【问题标题】:r quantmod chart add linear regression liner quantmod 图表添加线性回归线
【发布时间】:2017-07-16 12:37:08
【问题描述】:

我想在 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")

有什么建议吗?谢谢。

【问题讨论】:

    标签: r plot charts linear-regression quantmod


    【解决方案1】:

    您正在为整个 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])
    

    【讨论】:

      猜你喜欢
      • 2021-01-21
      • 2016-08-01
      • 2013-02-11
      • 2021-05-21
      • 2021-03-25
      • 2020-03-13
      • 1970-01-01
      • 2012-01-12
      • 1970-01-01
      相关资源
      最近更新 更多