How to highlight time series in some date ranges in R - r

I need to highlight some dates ranges in my time series chart, but I can´t go ahead.
The dataset used is following:
library(dplyr)
library(xts)
library(zoo)
df <- read.csv("https://github.com/rhozon/datasets/raw/master/dataset_1a.csv", header = TRUE, sep =",") %>%
mutate(
dates = as.Date(dates)
) %>%
filter(
dates >= "2019-01-01"
) %>%
glimpse()
df_xts <- xts(df[,-1, drop = FALSE], order.by = df[,1]) %>% as.xts()
class(df_xts)
head(df_xts)
Then I tryed the following PerfomanceAnalytics commands:
library(PerformanceAnalytics)
# Create period to hold the 3 months of 2020
period <- c("2020-01/2020-03")
# Highlight the first three months of 2020
chart.TimeSeries(df$prices_usa, period.areas = period, period.color = "lightgrey")
with no success...
Error in try.xts(x, error = "'x' needs to be timeBased or xtsible") :
'x' needs to be timeBased or xtsible
By using the dygraphs package...
library(dygraphs)
dygraph( df$prices_usa ) %>%
dyShading(from = "2020-06-30", to = "2020-09-01") %>%
dyAnnotation("2020-08-01", text = "X", tooltip = "date range") %>%
dyAxis("x", drawGrid = TRUE) %>%
dyEvent("2020-06-30", "Jul 2020", labelLoc = "bottom") %>%
dyEvent("2020-09-01", "Sep 2020", labelLoc = "bottom") %>%
dyOptions(drawPoints = FALSE, pointSize = 2) #%>%
And again I found another issue:
Error in dygraph(df$prices_usa) : Unsupported type passed to argument 'data'.
I didn´t tryed with the ggplot2 package because I need to use it with interaticvity.
Could someone recommend me a solution to these issues or something that is simpler to do (even with ggplot2+plotly) that can be useful for me to demarcate or highlight some ranges of dates/periods in my time series graphs?

Using the reproducible xts object in the Note at the end use plot and xblocks. To specify a different color use something like adjustcolor("blue", 0.2) in place of grey(...). For many other approaches google R shading recessions
library(xts)
plot(as.zoo(aapl))
xblocks(aapl, ifelse(time(aapl) %in% time(aapl[period]), grey(.2, .2), NA))
Note
library(quantmod)
getSymbols("AAPL")
period <- "2020-01/2020-03"
aapl <- Cl(AAPL)

Related

How to plot multiple xts objects inside list to have n amount of dygraphs printed in an output folder?

I have sample file with csv that describe some stock exchange indexes. I have already managed to:
Create for loop statement to tidy the data in a way that I have those data as DFs in a list.
In each index I calculated using loop OLSSlope, Log values, Percent Change, STDSlope etc.
Create XTS objects that are stored inside list.
I want to write such for loop/ lapply code that will take each xts object inside list, create plot using (dygraph) library and then save this graph in an output file. So that the goal is to have graph for each index that is inside this list of xts objects. I don't have problem with creating one graph for one object but to make it universal inside loop. Code for graph that I want is:
wig20tr_d_xts <- xts(x = wig20tr_d$Zamkniecie,
order.by = wig20tr_d$Date)
wig20tr_d_ols <- xts(x = wig20tr_d$OLSSlope,
order.by = wig20tr_d$Date)
wig20tr_d_stdup <- xts(x = wig20tr_d$OneSTDup,
order.by = wig20tr_d$Date)
wig20tr_d_stduptwo <- xts(x = wig20tr_d$TwoSTDup,
order.by = wig20tr_d$Date)
wig20tr_d_stddown <- xts(x = wig20tr_d$OneSTDdown,
order.by = wig20tr_d$Date)
wig20tr_d_stddowntwo <- xts(x = wig20tr_d$TwoSTDdown,
order.by = wig20tr_d$Date)
wig20 <- cbind(wig20tr_d_xts, wig20tr_d_ols, wig20tr_d_stdup, wig20tr_d_stduptwo, wig20tr_d_stddown, wig20tr_d_stddowntwo)
wig20_graph <- dygraph(wig20, main = "WIG 20 TR", ylab = "Total return in zł") %>%
dySeries("wig20tr_d_xts", color = "black") %>%
dySeries("wig20tr_d_ols", strokeWidth = 2, strokePattern = "dashed", color = "blue") %>%
dySeries("wig20tr_d_stdup", color = "green") %>%
dySeries("wig20tr_d_stduptwo", color = "green") %>%
dySeries("wig20tr_d_stddown", color = "red") %>%
dySeries("wig20tr_d_stddowntwo", color = "red") %>%
dyRangeSelector() %>%
dyUnzoom() %>%
dyOptions(axisLineColor = "navy",
gridLineColor = "lightblue") %>%
dyCrosshair(direction = "vertical")
wig20_graph
htmltools::save_html(wig20_graph, file = "C:/DATA_output/wig20_graph.html")
As you can see I use this addition to the graph:
dyCrosshair <- function(dygraph,
direction = c("both", "horizontal", "vertical")) {
dyPlugin(
dygraph = dygraph,
name = "Crosshair",
path = system.file("plugins/crosshair.js",
package = "dygraphs"),
options = list(direction = match.arg(direction))
)
}
Loop to create list of xts objects is like this:
for(i in 1:length(xts_list)){
df <- xts_list[i]
df <- as.data.frame(df)
colnames(df) <- c("Date", "Zamkniecie", "Trend", "OLSSlope", "LogClose", "LogCloseOLS", "LogCloseOLSSlope", "PercentChange", "LogChange", "OneSTDup", "OneSTDdown", "TwoSTDup", "TwoSTDdown")
time_series <- xts(x = df$Zamkniecie,
order.by = df$Date)
ols <- xts(x = df$OLSSlope,
order.by = df$Date)
stdup <- xts(x = df$OneSTDup,
order.by = df$Date)
stduptwo <- xts(x = df$TwoSTDup,
order.by = df$Date)
stddown <- xts(x = df$OneSTDdown,
order.by = df$Date)
stddowntwo <- xts(x = df$TwoSTDdown,
order.by = df$Date)
time_series_full <- cbind(time_series, ols, stdup, stduptwo, stddown, stddowntwo)
xts_list[[i]] <- time_series_full
print(i)
}
I have problem with adding part with graph inside this last for loop. So that the HTML graph would be named after the index. In this example the index is wig20tr_d

Change the 'Frame' Label in Plotly Animation

TLDR: I want to label the frame slider with the three letter abbreviation instead of the number for each month.
I created a bar chart showing average snow depth each month over a 40 year period. I'm pulling my data from NOAA and then grouping by year and month using lubridate. Here is the code:
snow_depth <- govy_data$snwd %>%
replace_na(list(snwd = 0)) %>%
mutate(month_char = month(date, label = TRUE, abbr = TRUE)) %>%
group_by(year = year(date), month = month(date), month_char) %>%
summarise(avg_depth = mean(snwd))
The mutate function creates a column (month_char) in the data frame holding the three letter abbreviation for each month. The class for this column is an ordered factor.
The code below shows how I'm creating the chart/animation:
snow_plot <- snow_depth %>% plot_ly(
x = ~year,
y = ~avg_depth,
color = ~avg_temp,
frame = ~month,
text = ~paste('<i>Month</i>: ', month_char,
'<br><b>Avg. Depth</b>: ', avg_depth,
'<br><b>Avg. Temp</b>: ', avg_temp),
hoverinfo = 'text',
type = 'bar'
)
snow_plot
This code generates a plot that animates well and looks like this:
What I'd like to do is change the labels on the slider so instead of numbers, it shows the three letter month abbreviation. I've tried switching the frame to ~month_char which is the ordered factor of three letter month abbreviations. What I end up with, isn't right at all:
The data frame looks like:
I fear, with the current implementation of animation sliders in R's plotly API the desired behaviour can't be realized. This is due to the fact, that no custom animation steps are allowed (this includes the labels). Please see (and support) my GitHub FR for further information.
This is the best I was currently able to come up with:
library(plotly)
DF <- data.frame(
year = rep(seq(1980L, 2020L), each = 12),
month = rep(1:12, 41),
month_char = rep(factor(month.abb), 41),
avg_depth = runif(492)
)
fig <- DF %>%
plot_ly(
x = ~year,
y = ~avg_depth,
frame = ~paste0(sprintf("%02d", month), " - ", month_char),
type = 'bar'
) %>%
animation_slider(
currentvalue = list(prefix = "Month: ")
)
fig
(Edit from OP) Here's the resulting graph using the above code:

Cannot combine a Ribbon in highcharter (R) with normal line series

I am trying to produce a ribbon on my highcharter chart (roughly following is there an equivalent to geom_ribbon in highcharter?).
However, the following example to produce a highcharter graph in R produces an error:
library(quantmod)
library(dplyr)
library(highcharter)
getSymbols("VOD")
bb_data = BBands(Cl(VOD), n=20)
highchart(type = "stock") %>%
hc_add_series(bb_data, type = "arearange", hcaes(low = dn, high=up))
The error is:
Error: 'hcaes(low = dn, high = up)' argument is not named in hc_add_series
I have think this is because it is a time series object (xts).
It works if I cast it to a data.frame, but then I lose the date.
highchart(type = "stock") %>%
hc_add_series(as.data.frame(bb_data), type = "arearange", hcaes(low = dn, high=up))
I cannot combine it to with the moving average or price data as I would wish, as the ribbon is then missing from the subsequent plot:
highchart(type = "stock") %>%
hc_add_series(Cl(VOD), name = "VOD") %>%
hc_add_series(bb_data$mavg, name = "20d MA") %>%
hc_add_series(as.data.frame(bb_data), type = "arearange", hcaes(low = dn, high=up))
ok, so I had to first extract the date from the time series object and bind it with the time series object to form a data frame or data table and then plot using that.
bb_data2 = cbind(date = as.Date(index(bb_data)), data.table(bb_data))
highchart(type = "stock") %>%
hc_add_series(bb_data2, type = "arearange", hcaes(x=date, low = dn, high=up)) %>%
hc_add_series(Cl(VOD), name = "VOD") %>%
hc_add_series(bb_data$mavg, name = "20d MA")

Error in mutate_impl(.data, dots) : Evaluation error: Only year, quarter, month, week, and day periods are allowed for an index of class Date

I am using Anomalize package to detect the Anomalies, but I am getting the mentioned error even though I have defined the Date as index :
Sample Code :
x <- as.data.frame(data %>%
group_by(date,acc_id) %>%
summarise(count = as.numeric(n_distinct(d_id))) %>%
ungroup())
x$acc_id <- as.character(x$acc_id)
x <- x %>%
tibbletime::as_tbl_time(index = date)
x %>%
time_decompose(count, method = "twitter", trend = "2 months") %>%
anomalize(remainder, method = "gesd") %>%
time_recompose() %>%
plot_anomalies(time_recomposed = TRUE)
Error :
Error in mutate_impl(.data, dots) : Evaluation error: Only year,
quarter, month, week, and day periods are allowed for an index of
class Date.
dput(head(x))
structure(list(date = structure(c(17532, 17532, 17532, 17532, 17532, 17532), class = "Date"), acc_id = c("a44444", "gg555", "0195459b-5809-4b54-89b5-1a4376c9f126", "ggg6546", "hhjh77", "hhjh68777"), count = c(3, 1, 1, 1, 1, 1)), .Names = c("date", "acc_id", "count"), row.names = c(NA,
-6L), class = c("tbl_time", "tbl_df", "tbl", "data.frame"), index_quo = ~date, index_time_zone = "UTC")
I have the objective to group by date and some other factor not alone with the date.
I had the same issue. What helped me was to correctly define your date format:
library(tibbletime)
x <- as_tbl_time(x, index = date)
x %>%
as_period("daily")
From the help:
frequency Controls the seasonal adjustment (removal of seasonality).
Input can be either "auto", a time-based definition (e.g. "2 weeks"),
or a numeric number of observations per frequency (e.g. 10). Refer to
time_frequency().
trend Controls the trend component For stl, the
trend controls the sensitivity of the lowess smoother, which is used
to remove the remainder. For twitter, the trend controls the period
width of the median, which are used to remove the trend and center the
remainder.
I think you swapped them:
x %>%
time_decompose(count, method = "twitter", frequency* = "2 months") %>%
anomalize(remainder, method = "gesd") %>%
time_recompose() %>%
plot_anomalies(time_recomposed = TRUE)
But it's hard to tell if there are any other problems, as the data is not enough
There is missing a "group_by" at this pipeline. This error is also in the examples of the anomalize package. Error was gone after adding it. This worked:
x %>%
group_by(acc_id) %>%
time_decompose(count, method = "twitter", trend = "2 months") %>%
anomalize(remainder, method = "gesd") %>%
time_recompose() %>%
plot_anomalies(time_recomposed = TRUE)
I was getting this error as well, until I removed duplicate dates. I was trying to run the code on data that had multiple observations for each site. Once I aggrigated to single obs per day, all was well.

Change y-axis in Dygraph to NOT be scientific notation

I have created a dygraph and want change the y-axis from scientific notation to decimal form.
This is what the code looks like:
df_xts <- xts(df$Var1,order.by=df$Date)
dygraph(A_xts,
main="DF - Var1",group="group1") %>%
dySeries("V1",label="Var1") %>%
dyOptions(stackedGraph = FALSE,colors=c("blue")) %>%
dyRangeSelector()
I'm guessing it would be placed under dyOptions but I'm not sure.
Thanks!
With my sample data it looks like this:
df_xts <- xts(runif(10) * 1e10, order.by = as.POSIXct(x = 1:10, origin = "2015-01-01") )
dygraph(df_xts, main="DF - Var1") %>%
dySeries("V1",label="Var1") %>%
dyOptions(maxNumberWidth = 20, stackedGraph = FALSE,colors=c("blue")) %>%
dyRangeSelector

Resources