Skip to contents

Plots interactive time series graphs with many options for highlighting key events, regions and customizations.

Usage

fgts_dygraph( indata,
 title = "",  xlab="", ylab = "",  roller = "default",  bg_opts = "hair,both;grid,both",
 splitcols = FALSE, stepcols = FALSE, hidecols = FALSE, hilightcols = FALSE,
 hilightwidth = 2, hilightstyle = "solid",
 events = "", event_ds = NULL,
 annotations = "", annotation_ds = NULL, forecast_ds = NULL,
 ylimits = NULL,  dtstartfrac = 0,  dtwindow = "",  rebase = "",  exportevents = FALSE,
 meltvar = "variable", dylegend = "always", fillGraph = FALSE, colorset="lines",
 groupnm = fg_sync_group(), verbose = FALSE,  extraoptions = list() )

Arguments

indata

Input data in long or wide format. THere must be at least one date column, one character column and one numeric column. Ideal format is date,variable,value

title

Title to put on top of graph

xlab, ylab

Labels for x and y axis

roller

Initial moving average value to smooth graphs. (See dygraphs::dyRoller()) Options are

  • default (Default) chose a smoothing parameter consistent with the length of the input series

  • finest No smoothing

  • integer >= 0 : User specified moving average length.

bg_opts

Semicomma separated options to change interactivity and background of charts. These semicomma separated options change pointer option and grids options.

  • hair,<style> passes <style> to dygraphs::dyCrosshair(). Default is "both" x and y crosshairs.

  • grid,<x,y,both> specifies which gri lines to show. Default is "both"

  • norange turns off date range selector.

splitcols, stepcols, hidecols

String or list of data series to show on a second y axis, to be shown as step plots, or to be hidden. Can also be TRUE in which case first series in the data is used Can also be a semicolon separated single string with mutiple series.

hilightcols

String or list of data series to plot in different style than other series.

hilightwidth

(Default: 2) relative width of series specified in hilightcols

hilightstyle

(Default: solid). Line style of series specified in hilightcols. Options are (solid,dashed,dotted,dotdash)

events

String with possible events to add to graph. Options can be added together with ; and include

  • doi,<eventsetname> : Events in internal event list eventsetname from list maintained by fg_update_dates_of_interest().

  • seasonal,<type> : Regularly spaced intervals of dates. See details below.

  • minmax : Locations of highest and lowest observations per series.

  • dt,text,d1,<d2> : Text events starting at d1 and possibly ending at <d2>,both of the form yyyy-mm-dd. See details for adjustments.

  • pt,d1,series,text : Text annotation for series at date d1 See details for adjustments.

  • break,labelform : Breakouts as determined by fg_addbreakouts() with labelform in ("singleasdate","singleavalue","breakno")

  • tp,n : Turning points on the first series as determined by fg_findTurningPoints()

event_ds

data.frame of events to be added to graph. See details and examples for specification.

annotations

string with annotations on individual series or along y axes. Options can be added together with ; and can include

  • last,[value|label] : Value or name of latest observation for each series, placed at the end of the series

  • last,[linevalue|linelabel] : Value or name of latest observation for each series, placed at the end of the seriesName of each series, placed at the end of the series.

  • hline,y : Horizontal line at y`

  • range,ybeg,yend : Band placed between ybeg and yend

annotation_ds

data.frame of annotations added to graph. See details for specification.

forecast_ds

data.frame of forecasts to be displayed after the end of those in indt. Those typically are in wide format, with at minimum a (first) date column and series names of the form series.f``, series.flo and/or `series.fhi, where series is one of the plotted series in indt

ylimits

Two number vector of lower and upper limits of data to be displayed. Alternatively, a string of the form <seriesnm>,<q> will limit displayed data to the (q,1-q) quantiles of seriesnm

dtstartfrac

Fraction in (0,1] of dates in indt to start the range selector. See dygraphs::dyRangeSelector()

dtwindow

String to specify date ranges applied dygraphs::dyRangeSelector() of the form begin::end where either end can take the form "yyyy-mm-dd" or a relative date to the other end of the series, e.g -3m or -2w. Example: "-3m::-1m" defines a 2 month period 1 month back from the end of the series.

rebase

String of the form yyyy-mm-dd,<value> with <value> assumed 100 if not specified. This normalizes all series to <value> as of the given date. See examples.

exportevents

(Default: FALSE) Return list of the form c(<graph>,<event dataframe>) instead of just the graph.

meltvar

(Default: variable) Column name in indt with series names, if melted.

dylegend

(Default: "auto") Passed to dygraphs::dyLegend(), can be one of ("auto", "always", "onmouseover", "follow", "never")

fillGraph

(Default: FALSE) Shade area underneath each series.

colorset

(Default: "lines") Set of default colors to use. See Customization vignette .

groupnm

(Default: NULL, unless set via fg_sync_group() ) Group name used in shiny or RMarkdown to synchronize graphs. See fg_sync_group() for details.

verbose

(Default: FALSE) Print extra details about what will be graphed.

extraoptions

Additional options passed to dygraphs::dyOptions()

Value

Dygraph dygraphs plotting input data, with annotations and other customizations.

Details

Input data can either be in wide ('date' ,'series1',...) format or normalized (long) format ('date','variable','value') format. This package infers date columns names from column types and seeks to be as agnostic as possible as to column names. Colors can be managed using fg_update_aes() and will persist across R sessions, See vignette for details. Series are grouped together into bands around a series series if their names end as in 'series.lo' or 'series.hi'. See examples and vignette for details.

Events are dates and date ranges to be highlighted in the graph. Multiple types of events can be strung together in semicolon delimited strings. Of the options outlined above, two additional details are

<type>description
"optex,mo | qtr"Monthly and/or quarterly equity option expiration dates.
"roll"IMM CDS roll dates
"daysfromroll"Dates with same number of days to the next roll as last date plotted
"doq","doy","bdoy"Dates with same day in quarter, in year, or business day of year to the last day plotted

Events can also be added using a data.frame passed via event_ds with the following columns:

columndescriptiontype
date(Required) Start dateDate
date_endEnd date to specify range of a colored bandDate
text(Required) Text to displaycharacter
colorColor for line and textcharacter
eventonlyOnly draw line for for start of event, no bandlogical
strokePatternOne of ('solid','dashed' (Default) ,'dotted','dotdash')character
locone of ('top','bottom' (Default))character
seriesName of series to apply event to, if neededcharacter
categoryOptional string used for exceptions. See notes below.character

Many times, events depend on outside data or statistical analysis on the original data. The event_ds to be passed in can come from event helpers in fg_cut_to_events(), fg_addbreakouts(), fg_findTurningPoints(), or fg_ratingsEvents(). Event columns are processed as is, unless category=="series_color" which will replace color with that of its series.

Annotiations include any notes or highlights added to the graph on the 'y' axis or on an individual series. In addition to those passed via the annotations parameter, annotations can be added using a data.frame with the following columns:

columndescriptiontype
date(Required) Start dateDate
date_endEnd date to specify range of a colored bandDate
text(Required) Text to displaycharacter
colorColor for line and textcharacter
eventonlyOnly draw line for for start of event, no bandlogical

Other notes:

  • Using stepcols most often happens with lower frequency data, so an nafill is automatically performed.

  • Dates in event types pt and dt are adjusted to next day in series if they do not already exist.

Examples

# See Vignette for more extensive examples.
# Basic Example
fgts_dygraph(eqtypx, title="Stock Prices", ylab="Adjusted Close")
# With series Highlights, finer resolution and focused date range fgts_dygraph(eqtypx, dtstartfrac=0.8,hilightcols="IBM",hilightwidth=4,roller=3)
# Rebasing to 1/1/2022 fgts_dygraph(eqtypx, title="Rebased Prices", ylab="Adjusted Close",rebase="2022-01-01")
# Using bands (.lo, .hi) toplot <- reerdta[REGION=="LATAM",.(cop=sum(value*(variable=="COL")), reer=mean(value),reer.lo=min(value),reer.hi=max(value)),by=.(date)] fgts_dygraph(toplot,title="COP REER vs Latam peers",roller=3,hilightcols="cop",hilightwidth=4)
# Events Examples. Notice how roller shortens with the series. # See Vignette for more extensive examples require(data.table) smalldta <- narrowbydtstr(eqtypx[,.(date,TLT,EEM)],"-3y::") fgts_dygraph(smalldta,events="doi,regm;doi,fedmoves")
fgts_dygraph(smalldta,events="date,FOMO,2025-01-01,2025-06-01;date,xmas,2025-12-25")
# Events passed in as data.frames myevents = data.frame(end_date=as.Date(c("2024-03-10","2024-06-10")), date=as.Date(c("2024-01-10","2024-04-10")), text=c("range","event"),color=c("green","red")) fgts_dygraph(smalldta,events="doi,fedmoves",event_ds=myevents)
# Annotations on y axis fgts_dygraph(eqtypx,annotations="last,linevalue")
fgts_dygraph(eqtypx,annotations="hline,100,at100,red;hline,200,at200;range,300,400")
# use with helpers smalldta <- narrowbydtstr(eqtypx[,.(date,IBM,QQQ)],"-2y::") fgts_dygraph(smalldta,title="W TurnPts",event_ds=fg_findTurningPoints(smalldta[,.(date,QQQ)]))
fgts_dygraph(smalldta,title="W Sentiment",event_ds=fg_cut_to_events(consumer_sent,center="zscore"))
fgts_dygraph(smalldta,title="W dividends",event_ds=fg_tq_divs(c("IBM","QQQ")))
# Other helpers for use with credit ratings, breakouts, and earnings data are available. # use with forecasts require(forecast) #> Loading required package: forecast require(timetk) #> Loading required package: timetk #> #> Attaching package: ‘timetk’ #> The following object is masked from ‘package:data.table’: #> #> := require(sweep) #> Loading required package: sweep smalldta <- narrowbydtstr(eqtypx[,.(date,IBM,QQQ)],"-2y::") fcst_one <- function(ticker) { fcst <-tk_ts(smalldta[,.SD,.SDcol=c("date",ticker)]) |> ets() |> forecast::forecast(h=30) fcst |> sweep::sw_sweep(timetk_idx=TRUE) |> fg_sweep() } fpred <- merge(fcst_one("QQQ"),fcst_one("IBM"),by="date") #> Warning: Non-numeric columns being dropped: date #> Warning: 'tzone' attributes are inconsistent #> Warning: Non-numeric columns being dropped: date #> Warning: 'tzone' attributes are inconsistent fgts_dygraph(smalldta,title="With Forecasts", dtstartfrac=0.7,rebase=",100",forecast_ds=fpred)