【问题标题】:How to draw a line on chartSeries plot using quantmod?如何使用 quantmod 在 chartSeries 绘图上画一条线?
【发布时间】:2011-08-28 04:02:43
【问题描述】:

我想使用 quantmod 生成像 https://stat.ethz.ch/pipermail/r-sig-finance/attachments/20110826/19da3834/attachment.png 这样的图。

我想,我对一个非常简单的任务感到有点沮丧。我希望能够使用 quantmod 在图表上画一条线。经过几天的尝试,我一无所获。我看不到如何使用 quantmod::addLines 函数执行此操作的示例(这是我发现的唯一类似问题,但无法找到答案http://r.789695.n4.nabble.com/quantmod-plot-trendline-td894632.html

我的问题是这样的:我想在指定的日期/时间/条 nad y 值处绘制一条水平线。这条线只允许从某个特定的条开始为 n(例如 5)条长(另外我还想在指定的 y 值的行上方添加文本)。

我已经尝试了几件事:

getSymbols("SPY")

lines.SPY <- (Hi(SPY) + Lo(SPY))/2
names(lines.SPY) <- c("lines")
lines.SPY$BuySell <- ifelse(lag(lines.SPY$lines) > lines.SPY$lines, 1, -1)

chartSeries(SPY, subset="2011-08::", theme=chartTheme('white',
up.col='blue', dn.col='red'))
addTA(lines.SPY$lines[lines.SPY$BuySell == -1,], type='p', col='darkred', pch="_", on=1, cex = 2.5)
addTA(lines.SPY$lines[lines.SPY$BuySell == 1,], type='p', col='green4', pch="_", on=1, cex = 2.5)

但这实际上不是线条...而且我不知道如何添加文字...

那我试过了

getSymbols("SPY")

subset = "2011-03::"

dev.new()
chartSeries(SPY, subset=subset, theme="white")
test <- xts(rep(coredata(last(Cl(SPY))), 20), order.by=index(last(SPY, n=20)))
addTA(test, on=1, col="red", legend=NULL, lwd=3)

同样,无法添加文本。这种方法的另一个问题是我无法摆脱顶部的传说。由于我想在一个图表图例上绘制数十或数百条线,因此不应显示...

提前感谢您的想法/代码示例/...

最好的问候, 萨摩。

【问题讨论】:

标签: r charts quantmod


【解决方案1】:

(我只是复制了 Stergios Marinopoulos 的 R-sig-finance 的答案) 使用新的 chart_Series() 函数以及文本和段。

require(quantmod) 
getSymbols("SPY") 
chart_Series(SPY, subset="2011-08::", type = "candlesticks" ) 
text(9, 112.00, "SOME TEXT", adj=0); 
segments(9, 111.5, 12, 111.5) ; 

我的一些补充评论。要添加消息:text(x,y,"message") 其中 x 是柱的编号(1 表示最左边的柱;您可以使用 0 或负数来绘制左侧),y 是图表中的值。对于 adj,0 表示左对齐,1 表示右对齐,0.5 表示居中。超出 0..1 范围会相应地移动它(但依赖它可能是不明智的)。

segments(x1,y1,x2,y2) 从 (x1,y1) 到 (x2,y2) 画一条线,其中 x 是条形索引,y 是价格。

下面绘制了一个等腰三角形,20% 不透明的红色: 多边形( c(20,30,40), c(5290,5320,5290), col="#ff000033")

即所有 R 图形功能均可用;但你必须使用 chart_Series()。

【讨论】:

  • 达伦,谢谢。当我将代码嵌入到函数 require(quantmod) getSymbols("SPY") drawSomething
  • @Samo 错误信息让人分心,因为问题出在前一行。当您使用在函数中创建绘图的函数时,您必须打印它。 IE。将您的第一行更改为print(chart_Series(SPY, subset="2011-08::", type = "candlesticks" ) )
  • 您对我发布的这个stackoverflow.com/questions/8639928/… 问题有解决方案吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-09
  • 2014-07-19
相关资源
最近更新 更多