如何用 plotly 在 R 中的两个给定点之间画一条线?

How to draw a line between two given points in R with plotly?

我正在尝试使用加密货币 (CC) 价格的高点和低点绘制某种趋势线。我使用的第一个图书馆:

library(tidyverse)
library(reshape2)
library(lubridate)
library(TTR)
library(binancer)
library(plotly)

由于我在众多CC中进行选择,因此我将使用下一个方案来实现某种自动化。对于这个例子,我使用比特币 (BTC)。以下代码将检索 4 小时时间范围内的比特币数据。我将“horas”设置为 900 以获得 225 个观测值:

nombre <- "BTC"
tiempo <- "4h"
horas <- 900

data <- binance_klines(paste0(nombre,"USDT"), interval = paste0(tiempo), 
    start_time=Sys.time()-hours(paste0(as.numeric(horas))), end_time=Sys.time())%>%
    select(open_time, open, high, low, close, volume, trades)%>%
    rename(time=1)

接下来我得到低点和高点以使用此数据绘制我想要的线条。如您所见,我为高点和低点选择了两个点:

lows <- arrange(data, low)%>%
    slice(c(which.min(low), which.max(low)))%>%
    arrange(time)

highs <- arrange(data, high)%>%
    slice(c(which.max(high), which.min(high)))%>%
    arrange(time)

我还添加了一些简单的移动平均线 (SMA)。我的 sma 数据库是我的情节的来源:

data%>%
    mutate(SMA_5= SMA(close, 5), SMA_10= SMA(close,10), SMA_20= SMA(close,20)) -> sma

我正在尝试使用 add_segments 绘制我想要的低点线(如果可行,我将对高点使用相同的代码)但我遇到了一些错误:

sma %>% plot_ly(x = ~time, type="candlestick",
                       open = ~open, close = ~close,
                       high = ~high, low = ~low) %>%
    add_lines(x = ~time, y= ~SMA_5,  line = list(color = "gold", width = 2), inherit = F,
                name = "SMA 5", showlegend=T)%>%
    add_lines(x = ~time, y= ~SMA_10,  line = list(color = "deeppink", width = 2), inherit = F,
                name = "SMA 10", showlegend=T)%>%
    add_lines(x = ~time, y= ~SMA_20,  line = list(color = "purple", width = 2), inherit = F,
                name = "SMA 20", showlegend=T)%>%
    add_segments(
                x = ~lows[1,1], xend = ~lows[2,1], 
                y = ~lows[1,4], yend = ~lows[2,4], color="black")%>%
    plotly::layout(title = paste0(nombre, " Simple Moving Average, ", tiempo),
        xaxis= list(title="Time", rangeslider = list(visible = F)), yaxis = list(title = "Price"),
        sliders=list(visible=F)) -> sma_plot

sma_plot

Error in `*tmp*`[[jj]] : subscript out of bounds 

知道我做错了什么吗?任何反馈将不胜感激。

如果您尝试在两个坐标之间画一条线,只需使用与其他线相同的模式。

add_lines(inherit = F, data = lows, x = ~time, y = ~low, 
          name = "Lows, line = list(color = "black"))