Reputation: 386
I have the graph from the quantmod package in which I get data from SPY, I want to make an interactive graph, similar to how we would do it with ggploty
from the plotly
package. This is the basic form of my code.
library(quantmod)
library(plotly)
getSymbols("SPY", from="2016-01-01", to="2020-01-01")
chartSeries(SPY, subset = "2017-11-18::2017-12-16")
addSMA(n=50, on=1, col = "blue")
This is what I tried to do
p <- chartSeries(SPY, subset = "2017-11-18::2017-12-16")
ggplotly(p)
This code doesn't work, I think it has a different class object. Is there a way to make the graph from chartSeries
an interactive graph so I can select a specific range of data?
Upvotes: 2
Views: 491
Reputation: 1439
you can use the dygraphs package to create an interactive chart with an object of xts class
try the code below, it will create an interactive chart with candlestick of of the prices
library(quantmod)
library(dygraphs)
library(tidyverse)
library(lubridate)
library(htmlwidgets)
getSymbols("SPY", from="2016-01-01", to="2020-01-01")
SPY <- SPY[,c(1:4)] ## remove the volume and adjusted columns
SPY$SMA50 <- SMA(Cl(SPY), n = 50) #create SMA50 line
p <- dygraph(SPY, xlab = "Date", ylab = "Price", main = "SPY Price") %>%
dySeries("SPY.Open", label = "Open", color = "black") %>%
dySeries("SPY.Low", label = "Low", color = "red") %>%
dySeries("SPY.High", label = "High", color = "green") %>%
dySeries("SPY.Close", label = "Close", color = "orange") %>%
dySeries("SMA50", label = "SMA50", color = "blue") %>%
dyRangeSelector() %>%
dyCandlestick()%>%
dyCrosshair(direction = "vertical") %>%
dyHighlight(highlightCircleSize = 3, highlightSeriesBackgroundAlpha = 0.2, hideOnMouseOut = T) %>%
dyRoller(rollPeriod = 1)
p
Upvotes: 3