gpt4 book ai didi

r - geom_boxplot (R) 的股票烛台绘制问题

转载 作者:行者123 更新时间:2023-12-04 16:44:33 27 4
gpt4 key购买 nike

我正在使用 geom_boxplot使用股市数据绘制烛台。问题是单个箱线图的上下边缘以及上须端点在 y 轴上显示的比其相应值高得多。不过,每个箱线图的相对高度(上下边缘之间的差异)和下须的端点都很好。这是我的代码:

candlestickPlot <- function(x){

library("ggplot2")

# x is a data.frame with columns 'date','open','high','low','close'
x$candleLower <- pmin(x$open, x$close)
x$candleUpper <- pmax(x$open, x$close)
x$candleMiddle <- NA
x$fill <- "red"
x$fill[x$open < x$close] = "green"

# Draw the candlesticks
g <- ggplot(x, aes(x=date, lower=candleLower, middle=candleMiddle, upper=candleUpper, ymin=low, ymax=high))
g <- g + geom_boxplot(stat='identity', aes(group=date, fill=fill))
g
}

这是 x :
    date     close volume  open  high   low
5 2013-12-30 25.82 3525026 27.30 27.76 25.7
4 2013-12-31 27.41 5487204 25.25 27.70 25.25
3 2014-01-02 30.70 7835374 29.25 31.24 29.21
2 2014-01-03 30.12 4577278 31.49 31.80 30.08
1 2014-01-06 30.65 4042724 30.89 31.88 30.37

我在这里做错了吗?

最佳答案

有更有效的方法可以使用 ggplot2 创建 OHLC 烛台比您使用 geom_boxplot 描述的方式.您的代码似乎与链接中的示例非常相似:
http://www.perdomocore.com/2012/using-ggplot-to-make-candlestick-charts-alpha/

似乎很多人都将 ggplot 烛台示例放在网上,这些示例基于该链接中的示例使用 geom_boxplot .但是用 geom_boxplot 绘图的问题是随着绘制的条形数量的增加,绘图本身在生成绘图时会变慢。

这是使用烛台/OHLC 条形图绘制金融数据的一种计算速度更快的解决方案:

library(ggplot2)
library(quantmod)
FOSL <- getSymbols("FOSL", from="2015-01-01", auto.assign=FALSE)
names(FOSL) <- gsub("^.+\\.","",names(FOSL)) # remove "FOSL." from column names

rng <- "2015-08"
FOSL <- FOSL[rng]
FOSL <- data.frame(Date=as.POSIXct(index(FOSL)), FOSL[,1:4])

FOSL$chg <- ifelse(Cl(FOSL) > Op(FOSL), "up", "dn")
FOSL$width <- as.numeric(periodicity(FOSL)[1])
FOSL$flat_bar <- FOSL[, "High"] == FOSL[, "Low"]

# Candle chart:
pl <- ggplot(FOSL, aes(x=Date))+
geom_linerange(aes(ymin=Low, ymax=High)) +
theme_bw() +
labs(title="FOSL") +
geom_rect(aes(xmin = Date - width/2 * 0.9, xmax = Date + width/2 * 0.9, ymin = pmin(Open, Close), ymax = pmax(Open, Close), fill = chg)) + guides(fill = FALSE, colour = FALSE) + scale_fill_manual(values = c("dn" = "darkred", "up" = "darkgreen"))

# Handle special case of drawing a flat bar where OHLC = Open:
if (any(FOSL$flat_bar)) pl <- pl + geom_segment(data = FOSL[FOSL$flat_bar,], aes(x = Date - width / 2 * 0.9, y = Close, yend = Close, xend = Date + width / 2 * 0.9))

print(pl)

enter image description here

关于r - geom_boxplot (R) 的股票烛台绘制问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21045866/

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