gpt4 book ai didi

r - 如何使用 Quantmod 在 ChartSeries 图上画一条线?

转载 作者:行者123 更新时间:2023-12-01 19:39:54 25 4
gpt4 key购买 nike

我想制作一个像这样的情节 https://stat.ethz.ch/pipermail/r-sig-finance/attachments/20110826/19da3834/attachment.png使用 Quantmod。

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

我的问题是这样的:我想在指定的日期/时间/栏和 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)

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

预先感谢您的想法/代码示例/...

最诚挚的问候,萨摩。

最佳答案

(我只是复制 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()。

关于r - 如何使用 Quantmod 在 ChartSeries 图上画一条线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7218978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com