[英]How to draw a line between two given points in R with plotly?
I'm trying to draw some kind of trend line using highs and lows from cryptocurrencies (CC) prices.我正在尝试使用加密货币(CC)价格的高点和低点绘制某种趋势线。 First libraries I'm using:我正在使用的第一个库:
library(tidyverse)
library(reshape2)
library(lubridate)
library(TTR)
library(binancer)
library(plotly)
Since I choose among many CC, I'm using next scheme to achieve some kind of automation.由于我在许多 CC 中进行选择,我正在使用下一个方案来实现某种自动化。 For this example, I use Bitcoin (BTC).对于这个例子,我使用比特币 (BTC)。 The following code will retrieve data for Bitcoin for 4 hours timeframe.以下代码将检索 4 小时时间范围内的比特币数据。 I set "horas" to 900 in order to get 225 observations:我将“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)
Next I get lows and highs to use this data for drawing the lines I want.接下来,我得到低点和高点,以使用这些数据绘制我想要的线条。 As you can see, I choose exactly two points for either highs and lows:如您所见,我为高点和低点选择了两个点:
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)
And I also add some simple moving averages (SMA).我还添加了一些简单的移动平均线 (SMA)。 My sma database is the source for my plot:我的 sma 数据库是我的 plot 的来源:
data%>%
mutate(SMA_5= SMA(close, 5), SMA_10= SMA(close,10), SMA_20= SMA(close,20)) -> sma
I'm trying to use add_segments to draw the line I want for lows (if this works I'll use same code for highs) but I got some error:我正在尝试使用 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
Any idea on what I'm doing wrong?知道我做错了什么吗? Any feedback will be highly appreciated.任何反馈将不胜感激。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.