| Title: | Flexible Graphs for Analysis of Financial Data and Time Series |
|---|---|
| Description: | Flexible wrappers around R graphics modules 'dygraphs' <https://dygraphs.com/> and 'ggplot2' <https://ggplot2.tidyverse.org/> to visualize data commonly found in Financial Studies, with an emphasis on time series. Interactive time series plots include multiple options for incorporating external data such as forecasts and events. Other static plots useful for time series data include an intuitive and generic scatter plotter, a boxplot generator suitable for multiple time series, and event study plotters for time series analysis around sets of dates. |
| Authors: | Derek Holmes [aut, cre, cph] |
| Maintainer: | Derek Holmes <[email protected]> |
| License: | GPL (>= 3) |
| Version: | 0.8.5 |
| Built: | 2026-06-09 05:50:45 UTC |
| Source: | https://github.com/derekholmes0/financegraphs |
University of Michigan Consumer Sentiment Data, FRED code UMCSENT
consumer_sentconsumer_sent
consumer_sentA data frame with 120 rows and 3 columns
FRED identifier
Date of report
Observation
IBM Earnings download
earnings_ibmearnings_ibm
earnings_ibmA data.table with 120 observations and e columns
Earnings announcement date
Reported Earnings per Share
Company
Closing Equity Prices
eqtypxeqtypx
eqtypxA data table with 2529 obersavatin and 5 variables
Date Of Observation
EEM Closing Price
IBM Closing Price
QQQ Closing Price
TLT Closing Price
Closing Equity Prices (melted)
eqtypx_melteqtypx_melt
eqtypx_meltA tibble with 10116 observations and 3 columns
Date Of Observation
Ticker
Closing Price
Closing Equity returns and a rolling regression
eqtyrtneqtyrtn
eqtyrtnA tibble with 2529 observations and 6 columns
Date Of Observation
EEM Log daily return
IBM Log daily return
QQQ Log daily return
TLT Log daily return
ROlling 66 business day regression of TLT on QQQ p.value
IBM Stock price forecasts from ets baseline ets model
example_fcst_setexample_fcst_set
example_fcst_setA data table with forecasts for two equities
Date
Forecast price for QQQ
80th percentile in Forecast CI for QQQ
20th percentile in Forecast CI for QQQ
Forecast price for IBM
80th percentile in Forecast CI for IBM
20th percentile in Forecast CI for IBM
Wrapper around the function ecp::e.divisive() to create events for fgts_dygraph()
fg_addbreakouts(indta, annotationstyle = "singleasdate", ...)fg_addbreakouts(indta, annotationstyle = "singleasdate", ...)
indta |
Time series |
annotationstyle |
String in set ( |
... |
Parameters passed to |
Event Helpers : fg_addbreakouts
data.table suitable for passing into fgts_dygraph() via the event_ds parameter
if (requireNamespace("ecp", quietly = TRUE)) { dta <- tail(eqtypx[,.(date,QQQ,TLT)],2*260) fgts_dygraph(dta,event_ds=fg_addbreakouts(dta,min.size=66,R=40),title="With Breakouts") }if (requireNamespace("ecp", quietly = TRUE)) { dta <- tail(eqtypx[,.(date,QQQ,TLT)],2*260) fgts_dygraph(dta,event_ds=fg_addbreakouts(dta,min.size=66,R=40),title="With Breakouts") }
Event Helpers: fg_cut_to_events
fg_cut_to_events( indta, ncutsperside = 4, center = 0, extend = TRUE, invert = FALSE )fg_cut_to_events( indta, ncutsperside = 4, center = 0, extend = TRUE, invert = FALSE )
indta |
Time series |
ncutsperside |
: Integer with number of colors to use on each side of 'center' |
center |
: String or Double as follows:
|
extend |
Logical (Default: TRUE) to extend data to today ( |
invert |
Use opposite color schemes for data, i.e. "red" for good outcomes |
Always uses first date column and first numeric columns in data. If indta has multiple series, filter them before calling the function.
data.table suitable for passing into fgts_dygraph() via the event_ds parameter
smalldta <- narrowbydtstr(eqtypx[,.(date,IBM,QQQ)],"-2y::") events <- fg_cut_to_events(consumer_sent,center="zscore") fgts_dygraph(smalldta,title="With Sentiment ranges",event_ds=events)smalldta <- narrowbydtstr(eqtypx[,.(date,IBM,QQQ)],"-2y::") events <- fg_cut_to_events(consumer_sent,center="zscore") fgts_dygraph(smalldta,title="With Sentiment ranges",event_ds=events)
fg_get_dates_of_interest() gets a set of time events for use in fg time series graphs
fg_update_dates_of_interest() updates a set of time events for future use in time series graphs
fg_get_dates_of_interest( search_categories = "", use_default = TRUE, startdt = NULL, totoday = FALSE ) fg_update_dates_of_interest(indta, replace = FALSE)fg_get_dates_of_interest( search_categories = "", use_default = TRUE, startdt = NULL, totoday = FALSE ) fg_update_dates_of_interest(indta, replace = FALSE)
search_categories |
Grep string of categories to return. |
use_default |
(Default TRUE) use dedault dates if none else found. |
startdt |
Minimum date for events to be returned. |
totoday |
(Default: FALSE) Ends last date set returned (if applicable) with |
indta |
|
replace |
(Default: FALSE) If TRUE, replaces existing dates of interest with new set provided, otherwise replaces/inserts new rows only. |
Retrieves default dates of interest given a grepstring of categories. There are a default set of categories provided which may not be up to date.
New data passed into fg_update_dates_of_interest() or fg_update_aes() persists across future loads of the package. Any duplicates in the new file will be taken out.
New doi data.frames must have at least three columns:
| Column | Meaning |
category |
Grouping name (string) for a given set of dates of interest |
eventid |
Character string to be displayed at each event. |
DT_ENTRY |
Start Date of event |
END_DT_ENTRY |
Optional end of period to define regimes or ranges of events. |
data.table::data.table() of date or date ranges, or 'NULL“if new dates are added.
require(utils) require(data.table) tail(fg_get_dates_of_interest("fedmoves"),2) # To add (for example) a new FOMC cut of 50bps on 6/16/2026: newdoi <-data.table(category="fedmoves",eventid="F:-50", DT_ENTRY=as.Date("6/16/2026",format="%m/%d/%Y")) fg_update_dates_of_interest(newdoi) # Since this is in the future, we have to make the future now. fg_get_dates_of_interest("fedmoves",totoday=as.Date("2026-12-31")) fg_reset_to_default_state("doi") fg_reset_to_default_state("all")require(utils) require(data.table) tail(fg_get_dates_of_interest("fedmoves"),2) # To add (for example) a new FOMC cut of 50bps on 6/16/2026: newdoi <-data.table(category="fedmoves",eventid="F:-50", DT_ENTRY=as.Date("6/16/2026",format="%m/%d/%Y")) fg_update_dates_of_interest(newdoi) # Since this is in the future, we have to make the future now. fg_get_dates_of_interest("fedmoves",totoday=as.Date("2026-12-31")) fg_reset_to_default_state("doi") fg_reset_to_default_state("all")
Summarizes and plots moves in data from a given set of event dates. Plots are designed to maintain reasonable aesthetics with as either time series or event dates increase.
fg_eventStudy(indata,dtset,output="path",changeas="diff", nbd_back=10,nbd_fwd=20,n_color_switch=5, title="Events",maxdelta=+Inf,meltvar="variable",verbose=FALSE)fg_eventStudy(indata,dtset,output="path",changeas="diff", nbd_back=10,nbd_fwd=20,n_color_switch=5, title="Events",maxdelta=+Inf,meltvar="variable",verbose=FALSE)
indata |
A data.frame with at least one date column and multiple numeric columns. If melted,
must also contain the character column specified in parameter |
dtset |
A list of dates or a |
output |
(Default
|
changeas |
(Default |
nbd_back |
(Default 10) Positive integer for number of days prior to event are considered. |
nbd_fwd |
(Default 20) Positive integer for number of days after event are considered. |
n_color_switch |
(Default 5) A positive integer after which colors are displayed as gradients instead of separate colors. See Examples. |
title |
Character string for title of graph |
maxdelta |
(Default |
meltvar |
(Default |
verbose |
(Default |
Event Studies
a ggplot() object with the events analysis requested by output parameter, or a data.frame with statistics if output in c("data"","summary","stats")
dtset <- fg_get_dates_of_interest("fedmoves",startdt="2024-01-01")[,.(DT_ENTRY,text=eventid2)] fg_eventStudy(yc_CMSUST,dtset,title="Fed Cuts",output="stats") fg_eventStudy(yc_CMSUST,dtset,title="Fed Cuts",output="pathbyevent") fg_eventStudy(yc_CMSUST,dtset,title="Fed Cuts",output="medbyvar") fg_eventStudy(yc_CMSUST,dtset,title="Fed Cuts",output="lmbyvar",n_color_switch=0) fg_eventStudy(yc_CMSUST,dtset,nbd_back=3,nbd_fwd=10,title="Fed Cuts",output="boxbyvar") fg_eventStudy(yc_CMSUST,dtset,title="Fed Cuts",output="scatter")dtset <- fg_get_dates_of_interest("fedmoves",startdt="2024-01-01")[,.(DT_ENTRY,text=eventid2)] fg_eventStudy(yc_CMSUST,dtset,title="Fed Cuts",output="stats") fg_eventStudy(yc_CMSUST,dtset,title="Fed Cuts",output="pathbyevent") fg_eventStudy(yc_CMSUST,dtset,title="Fed Cuts",output="medbyvar") fg_eventStudy(yc_CMSUST,dtset,title="Fed Cuts",output="lmbyvar",n_color_switch=0) fg_eventStudy(yc_CMSUST,dtset,nbd_back=3,nbd_fwd=10,title="Fed Cuts",output="boxbyvar") fg_eventStudy(yc_CMSUST,dtset,title="Fed Cuts",output="scatter")
Event Helpers : fg_findTurningPoints
fg_findTurningPoints( indta, rtn = "dates", method = "pctchg", npts = 10, pts_of_interest = "change", pctabovemin = 0.05, maxwindow = -1, addlast = FALSE, cpmmethod = "GLR", ... )fg_findTurningPoints( indta, rtn = "dates", method = "pctchg", npts = 10, pts_of_interest = "change", pctabovemin = 0.05, maxwindow = -1, addlast = FALSE, cpmmethod = "GLR", ... )
indta |
Time series |
rtn |
string with what to return ('dates','data','all') |
method |
string describing method of finding Turning Points
|
npts |
Number of change points to find |
pts_of_interest |
string in 'change' (default) or 'value' |
pctabovemin |
Minimum percentage change to look for. |
maxwindow |
Integer (default -1) which limits (if positive) the minimum number of observations between change points. |
addlast |
Logical (default: FALSE) to add an event with final observation. |
cpmmethod |
String (default: "GLM") passed to |
... |
Additional parameters passed to cpm-package |
data.table suitable for passing into fgts_dygraph() via the event_ds parameter
dta <-eqtypx[,.(date,QQQ,TLT)] fgts_dygraph(dta,event_ds=fg_findTurningPoints(dta),title="With turningPoints")dta <-eqtypx[,.(date,QQQ,TLT)] fgts_dygraph(dta,event_ds=fg_findTurningPoints(dta),title="With turningPoints")
fg_get_aes() gets aethestic data.frame for use in graphs.
fg_get_aesstring() takes a column from the data.frame retrieved by fg_get_aes()
fg_print_aes_list() prints names of aesthetics used internally in FinanceGraph functions.
fg_display_colors() Shows a plot with current colors.
fg_get_aes(item = "", n_max = NA_integer_, asdataframe = FALSE) fg_get_aesstring( item = "", n_max = NA_integer_, toget = "value", rtnifnotfound = FALSE ) fg_display_colors(item = "") fg_print_aes_list(grepstr = "")fg_get_aes(item = "", n_max = NA_integer_, asdataframe = FALSE) fg_get_aesstring( item = "", n_max = NA_integer_, toget = "value", rtnifnotfound = FALSE ) fg_display_colors(item = "") fg_print_aes_list(grepstr = "")
item |
(Default: "") A grep string for categories desired. |
n_max |
Maximum number of rows or entries to return. Required for |
asdataframe |
(Default: FALSE) Return dataframe of parameters regardless of type. (See details) |
toget |
Column in the aes |
rtnifnotfound |
Return |
grepstr |
narrow list of internal aesthetics sets to functions from |
fg_get_aes() returns data.frame of aesthetics, including sorting columns, help strings, and values,
fg_get_aesstring() returns a list with just the character values of the requested aesthetic.
fg_print_aes_list() returns a markdown ready character vector of aesthetic names used in each function
fg_display_colors() returns a ggplot2::ggplot() object with colors and associated names for an aesthetic name
fgts_dygraph(), fg_update_aes()
# Data set, String head(fg_get_aes("lines"),3) fg_get_aesstring("lines") # Gradient colors are stored in a `data.frame` as in a set of "Blue Greens" fg_get_aes("espath_gp",asdataframe=TRUE) # To get the actual colors, we need to know how many: fg_get_aes("espath_gp",n_max=8) fg_display_colors("lines")# Data set, String head(fg_get_aes("lines"),3) fg_get_aesstring("lines") # Gradient colors are stored in a `data.frame` as in a set of "Blue Greens" fg_get_aes("espath_gp",asdataframe=TRUE) # To get the actual colors, we need to know how many: fg_get_aes("espath_gp",n_max=8) fg_display_colors("lines")
fg_prophet Augments a prophet::predict.prophet() output into fgts_dygraph() forecastdataset format.
fg_prophet(prophet_data, seriesname = "y")fg_prophet(prophet_data, seriesname = "y")
prophet_data |
Data resulting from a |
seriesname |
(Default: |
Note that prophet::predict.prophet() loses the name of the series, the
data.table suitable for passing into fgts_dygraph() via the forecastdataset parameter
if (requireNamespace("prophet", quietly = TRUE)) { p_model <- eqtypx[,.(ds=date,y=QQQ)] |> narrowbydtstr(dtstr="-1y::") |> prophet::prophet() p_fcst <- predict(p_model,prophet::make_future_dataframe(p_model,periods=60)) fgts_dygraph(eqtypx[,.(date,QQQ)],title="With Prophet Forecasts", roller=1,dtstartfrac=0.8, forecast_ds=fg_prophet(p_fcst,seriesname="QQQ")) }if (requireNamespace("prophet", quietly = TRUE)) { p_model <- eqtypx[,.(ds=date,y=QQQ)] |> narrowbydtstr(dtstr="-1y::") |> prophet::prophet() p_fcst <- predict(p_model,prophet::make_future_dataframe(p_model,periods=60)) fgts_dygraph(eqtypx[,.(date,QQQ)],title="With Prophet Forecasts", roller=1,dtstartfrac=0.8, forecast_ds=fg_prophet(p_fcst,seriesname="QQQ")) }
Calls tidyquant::tq_get() to get dividends for a given set of tickers. A previously created data.frame can also be input.
Created event_ds from alphavantagepf::av_get_pf quarterly earnings data.
fg_ratingsEvents(credit, ratings_db, agency = "S.P") fg_tq_divs(tickers, divs_ds = NULL, ticker_in_label = TRUE) fg_av_earnings(indt, field = "reportedEPS", ticker_in_label = FALSE)fg_ratingsEvents(credit, ratings_db, agency = "S.P") fg_tq_divs(tickers, divs_ds = NULL, ticker_in_label = TRUE) fg_av_earnings(indt, field = "reportedEPS", ticker_in_label = FALSE)
credit |
String with name of credit to look up in 'ratings_db' |
||||||||||||||||||
ratings_db |
A 'data.table' or 'data.frame' with the all of the following columns:
|
||||||||||||||||||
agency |
String (default 'S.P') with 'AGENCY to look up in 'ratings_db' |
||||||||||||||||||
tickers |
List of tickers to get dividends for. |
||||||||||||||||||
divs_ds |
Alternatively a |
||||||||||||||||||
ticker_in_label |
(Default: TRUE) Make label ticker and the earnings |
||||||||||||||||||
indt |
|
||||||||||||||||||
field |
(Default: |
Investment grade ratings are shaded in blue, High Yield are in red. Darker areas are closest to the cutoff between the two.
data.table suitable for passing into fgts_dygraph() via the event_ds parameter
data.table suitable for passing into fgts_dygraph() via the event_ds parameter
data.table suitable for passing into fgts_dygraph() via the event_ds parameter
data("nomfxdta") copdta <- nomfxdta |> dplyr::filter(variable=="COP") fgts_dygraph(copdta,title="COP with Ratings",dtstartfrac=0.3, event_ds=fg_ratingsEvents("COLOM",ratings_db,agency="S.P")) if (requireNamespace("tidyquant", quietly = TRUE)) { fgts_dygraph(eqtypx,title="With divs",dtstartfrac=0.8,event_ds=fg_tq_divs(c("IBM","QQQ"))) } if (requireNamespace("alphavantagepf", quietly = TRUE)) { earnings = alphavantagepf::av_get_pf("IBM","EARNINGS") |> alphavantagepf::av_extract_df("quarterlyEarnings") |> fg_av_earnings() toplot = dplyr::select(eqtypx,date,IBM) fgts_dygraph(toplot,title="With earnings",dtstartfrac=0.8,event_ds=earnings) }data("nomfxdta") copdta <- nomfxdta |> dplyr::filter(variable=="COP") fgts_dygraph(copdta,title="COP with Ratings",dtstartfrac=0.3, event_ds=fg_ratingsEvents("COLOM",ratings_db,agency="S.P")) if (requireNamespace("tidyquant", quietly = TRUE)) { fgts_dygraph(eqtypx,title="With divs",dtstartfrac=0.8,event_ds=fg_tq_divs(c("IBM","QQQ"))) } if (requireNamespace("alphavantagepf", quietly = TRUE)) { earnings = alphavantagepf::av_get_pf("IBM","EARNINGS") |> alphavantagepf::av_extract_df("quarterlyEarnings") |> fg_av_earnings() toplot = dplyr::select(eqtypx,date,IBM) fgts_dygraph(toplot,title="With earnings",dtstartfrac=0.8,event_ds=earnings) }
Wrapper around the function RegimeChange::detect_regimes() to create events for fgts_dygraph()
fg_RegimeChange(indta, usereturns = TRUE, series = NULL, ...)fg_RegimeChange(indta, usereturns = TRUE, series = NULL, ...)
indta |
Time series |
usereturns |
(default TRUE) LOgical to take log returns before changepoint calculations. |
series |
Which series in |
... |
Parameters passed to |
Event Helpers : fg_RegimeChange https://cran.r-project.org/web/packages/RegimeChange/vignettes/introduction.html
data.table suitable for passing into fgts_dygraph() via the event_ds parameter
if (requireNamespace("RegimeChange", quietly = TRUE)) { dta <- tail(eqtypx[,.(date,QQQ,TLT)],260) eventdt = fg_RegimeChange(dta) fgts_dygraph(dta,event_ds=eventdt,title="With Breakouts") }if (requireNamespace("RegimeChange", quietly = TRUE)) { dta <- tail(eqtypx[,.(date,QQQ,TLT)],260) eventdt = fg_RegimeChange(dta) fgts_dygraph(dta,event_ds=eventdt,title="With Breakouts") }
Plots bivariate plots with some time-series specific enhancements. Rather than programmatically describing graph aesthetics, a simple formula-based approach is used. This approach allows quick specification of many customizaton options.
fg_scatplot(indata,plotform,type="scatter",datecuts=c(7,66), noscales="",xdecoration="",ydecoration="",annotatecorners="", tsize=3,psize=1,n_color_switch=7,n_hex_switch=400,repel=TRUE,jitter=c(0,0), title="",subtitle="",caption="",axislabels="", boundbox=c(),boundboxtype="",gridstyle=NA_character_,legendinside=FALSE, tformula=formula("y~x"),returnregresults=FALSE, keepcols="", meltvar="variable",melted=NULL)fg_scatplot(indata,plotform,type="scatter",datecuts=c(7,66), noscales="",xdecoration="",ydecoration="",annotatecorners="", tsize=3,psize=1,n_color_switch=7,n_hex_switch=400,repel=TRUE,jitter=c(0,0), title="",subtitle="",caption="",axislabels="", boundbox=c(),boundboxtype="",gridstyle=NA_character_,legendinside=FALSE, tformula=formula("y~x"),returnregresults=FALSE, keepcols="", meltvar="variable",melted=NULL)
indata |
|
plotform |
A text formula describing how to set up the graph. The formula is of the general form
where Aesthetic options:
Date specific options:
Text options:
Other annotations:
|
type |
character string for the type of graph to plot:
if |
datecuts |
list of integers (Default |
noscales |
String to suppress guides with any of |
xdecoration, ydecoration
|
2 element string list to add to either side of an axis label. |
annotatecorners |
4 element string list to add notes to each of 4 quadrants of the graph. See examples. |
tsize |
default text size (with some scaled variations for graph parts such as titles) |
psize |
default point size. |
n_color_switch |
(Default 7): Number of distint color categories beyond which colors are taken from gradient scales,
unless a color set is specified in a |
n_hex_switch |
(Default 400): Number of data points beyond which points are replaced with binned hexagons (see |
repel |
(Default TRUE) Text and labels are plotted using |
jitter |
Jitter parameters used by |
title |
Title to add to graph |
subtitle |
Subtitle to add to graph |
caption |
Caption to add to graph |
axislabels |
Semicolon separated string with x and y labels, e.g |
boundboxtype, boundbox
|
string describing how to use bounding boxes. If
|
gridstyle |
String in |
legendinside |
(Default: TRUE) Put all guides inside the graph. |
tformula |
(Default |
returnregresults |
Return a two element list c(plot,regression |
keepcols |
list of |
meltvar |
(Default |
melted |
(Default:NULL) If |
indata 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 casts or
pivot_wider to get x and y columns. Note that aesthetic characteristics (if used) must be present for both
long and wide input formats.
Default aesehetic sets used for portions of the graph each have their own names, which can be seeing by running
fg_print_aes_list() and modified or added to using fg_update_aes(). The default theme can be modified using
fg_replace_theme(). Both aesthetic changes and theme changes are persistent across R sessions.
Use of doi: in plotform string supercedes color aesthetics otherwise specified. (Is this true?)
If tooltips are used, the result of fg_scatplot must be viewed using print(girafe(ggobj=fg_scatplot(...)))
See ggiraph::geom_point_interactive()
Winsorized hulls with quantile cutoff q are formed using the closest (by euclidean distance) 1-q points to the
geograpic center of the entire set.
Captions are added if data is truncated or omitted by the bounding box procedure.
A ggplot2::ggplot() object with desired graph, or a ggiraph::girafe() object if tooltips is in the plotform string.
# Simple text examples require(data.table) dt_mtcars=data.table(datasets::mtcars) dt_mtcars$id=lapply(rownames(datasets::mtcars),\(x) last(strsplit(x," ")[[1]])) fg_scatplot(dt_mtcars,"disp ~ hp + color:am + text:id","scatter",title="text basic") fg_scatplot(dt_mtcars,"disp ~ hp + color:carb + label:id","scatter", n_color_switch=0,title="scat color switch") # Plotting data with dates: set.seed(1); ndates <- 400; dlyvol <- 0.2/sqrt(260) rtns <- cbind(cumsum(rnorm(ndates,sd=dlyvol)),cumsum(rnorm(ndates,sd=dlyvol))) dttest <- data.table(date=seq(as.Date("2021-01-01"),as.Date("2021-01-01")+ndates-1), xtest=100*(1+rtns[,1]),ytest=100*(1+rtns[,2]), ccat=fifelse(runif(ndates)<=0.2,"Rare","mkt")) # Making categories out of recent data fg_scatplot(dttest,"ytest ~ xtest + doi:recent","scatter",datecuts=c(66,122),title="from recent") fg_scatplot(dttest ,"ytest ~ xtest + color:ccat + doi:recent + point:label","scat", datecuts=c(7,66),title="recent w label") # Makes categories out of event sets from [fg_get_dates_of_interest()] fg_scatplot(dttest,"ytest ~ xtest + doi:regm","scatter",title="from a regime") # Point graphing switches. fg_scatplot(dttest,"ytest ~ xtest + color:ccat","lm",n_hex_switch=100,title="Hex Switch") # Quick changes to aesthetic sets fg_scatplot(dttest,"ytest ~ xtest + color:ccat,altlines_6","loess",title="Alternate colors") # Extra summarizatons fg_scatplot(dttest,"ytest ~ xtest + color:ccat + hull:0.1 + ellipse","lm",title="Curves") # Annotations fg_scatplot(dttest,"ytest ~ xtest + color:ccat + point:labelall","scat",title="Last Values") fg_scatplot(dttest,"ytest ~ xtest + color:ccat + point:anno","scat",annotatecorners="NW;NE;SE;SW", legendinside = FALSE)# Simple text examples require(data.table) dt_mtcars=data.table(datasets::mtcars) dt_mtcars$id=lapply(rownames(datasets::mtcars),\(x) last(strsplit(x," ")[[1]])) fg_scatplot(dt_mtcars,"disp ~ hp + color:am + text:id","scatter",title="text basic") fg_scatplot(dt_mtcars,"disp ~ hp + color:carb + label:id","scatter", n_color_switch=0,title="scat color switch") # Plotting data with dates: set.seed(1); ndates <- 400; dlyvol <- 0.2/sqrt(260) rtns <- cbind(cumsum(rnorm(ndates,sd=dlyvol)),cumsum(rnorm(ndates,sd=dlyvol))) dttest <- data.table(date=seq(as.Date("2021-01-01"),as.Date("2021-01-01")+ndates-1), xtest=100*(1+rtns[,1]),ytest=100*(1+rtns[,2]), ccat=fifelse(runif(ndates)<=0.2,"Rare","mkt")) # Making categories out of recent data fg_scatplot(dttest,"ytest ~ xtest + doi:recent","scatter",datecuts=c(66,122),title="from recent") fg_scatplot(dttest ,"ytest ~ xtest + color:ccat + doi:recent + point:label","scat", datecuts=c(7,66),title="recent w label") # Makes categories out of event sets from [fg_get_dates_of_interest()] fg_scatplot(dttest,"ytest ~ xtest + doi:regm","scatter",title="from a regime") # Point graphing switches. fg_scatplot(dttest,"ytest ~ xtest + color:ccat","lm",n_hex_switch=100,title="Hex Switch") # Quick changes to aesthetic sets fg_scatplot(dttest,"ytest ~ xtest + color:ccat,altlines_6","loess",title="Alternate colors") # Extra summarizatons fg_scatplot(dttest,"ytest ~ xtest + color:ccat + hull:0.1 + ellipse","lm",title="Curves") # Annotations fg_scatplot(dttest,"ytest ~ xtest + color:ccat + point:labelall","scat",title="Last Values") fg_scatplot(dttest,"ytest ~ xtest + color:ccat + point:anno","scat",annotatecorners="NW;NE;SE;SW", legendinside = FALSE)
Event Helpers: fg_signal_to_events
fg_signal_to_events(signal_df, colormap)fg_signal_to_events(signal_df, colormap)
signal_df |
A two-column |
colormap |
A two column |
This helper applies run-length encoding to match the signal in signal_df to the color in colormap
data.table suitable for passing into fgts_dygraph() via the event_ds parameter
# A simple moving average strategy with threshold require(data.table) ma_signal<-eqtypx[,.(date,sig=cut(frollmean(EEM,5)-frollmean(EEM,20), c(-10,-0.5,0.5,10),labels=c("long","flat","short")),EEM)] colormap<-data.frame(sig=c("long","flat","short"),color=c("#f56462","white","#6161ff")) fgts_dygraph(eqtypx[,.(date,EEM)],event_ds=fg_signal_to_events(ma_signal,colormap), dtstartfrac=0.8,roller=1,title="5/20 MA positions")# A simple moving average strategy with threshold require(data.table) ma_signal<-eqtypx[,.(date,sig=cut(frollmean(EEM,5)-frollmean(EEM,20), c(-10,-0.5,0.5,10),labels=c("long","flat","short")),EEM)] colormap<-data.frame(sig=c("long","flat","short"),color=c("#f56462","white","#6161ff")) fgts_dygraph(eqtypx[,.(date,EEM)],event_ds=fg_signal_to_events(ma_signal,colormap), dtstartfrac=0.8,roller=1,title="5/20 MA positions")
fg_sweep Augments a sweep::sw_sweep() output into fgts_dygraph() forecastdataset format. See
Introduction to Sweep
fg_sweep(swept_data, confidence = 80)fg_sweep(swept_data, confidence = 80)
swept_data |
Data resulting from a |
confidence |
(Default: 80) Confidence interval (in percent) to display |
Forecast Helpers
data.table suitable for passing into fgts_dygraph() via the forecastdataset parameter
if ( requireNamespace("forecast", quietly = TRUE) & requireNamespace("timetk", quietly = TRUE) & requireNamespace("sweep", quietly = TRUE) ) { fcst_eqtypx <- timetk::tk_ts(eqtypx[,.(date,QQQ)]) |> forecast::ets() |> forecast::forecast(h=30) |> sweep::sw_sweep(timetk_idx=TRUE) fcst_in <- fg_sweep(fcst_eqtypx) toplot <- eqtypx[,.(date,IBM,QQQ)] fgts_dygraph(toplot,title="With Forecasts", roller=1,dtstartfrac=0.7,forecast_ds=fcst_in) }if ( requireNamespace("forecast", quietly = TRUE) & requireNamespace("timetk", quietly = TRUE) & requireNamespace("sweep", quietly = TRUE) ) { fcst_eqtypx <- timetk::tk_ts(eqtypx[,.(date,QQQ)]) |> forecast::ets() |> forecast::forecast(h=30) |> sweep::sw_sweep(timetk_idx=TRUE) fcst_in <- fg_sweep(fcst_eqtypx) toplot <- eqtypx[,.(date,IBM,QQQ)] fgts_dygraph(toplot,title="With Forecasts", roller=1,dtstartfrac=0.7,forecast_ds=fcst_in) }
Sets, gets, or resets a common name to be passed into fgts_dygraph() for synchronization.
fg_sync_group(gpname = "")fg_sync_group(gpname = "")
gpname |
A string or NULL
|
Use thie to set a common groupname for time scale synchronization (for Markdown or shiny apps), Only set it in the beginning, or when needed, and call with NULL to turn synchronization off.
current groupname
fg_sync_group() fg_sync_group("common") fg_sync_group() fg_sync_group(NULL)fg_sync_group() fg_sync_group("common") fg_sync_group() fg_sync_group(NULL)
Plots static summaries of time series in boxplot form.
fg_tsboxplot(indt,title="",xlab="",ylab="", breaks=c(7,30,90,360), doi="last", normalize="", orderby="", boxtype= "", dropset="",hilightcats="", addline="", #last/mean facetform="", ycoord=NULL,trimpctile=0, legend="insidetop",meltvar="variable",flip=FALSE,ptsize=3)fg_tsboxplot(indt,title="",xlab="",ylab="", breaks=c(7,30,90,360), doi="last", normalize="", orderby="", boxtype= "", dropset="",hilightcats="", addline="", #last/mean facetform="", ycoord=NULL,trimpctile=0, legend="insidetop",meltvar="variable",flip=FALSE,ptsize=3)
indt |
Input data.frame with at least one date variable and one or more vategorical variables, if melted. |
title, xlab, ylab
|
TItles and Labels |
breaks |
A list or text as follows
|
doi |
Points or segments to overlay with latest observations, or changes since a particular date.
|
normalize |
Normalize data in some way prior to plotting. Choices are
|
orderby |
(Default
|
boxtype |
Formatting of boxplots. If in |
dropset |
String or list with underlying categories to drop from graph |
hilightcats |
String or list of underlying categories to highlight with differnt color in label. |
addline |
in |
facetform |
(Default: "") Any faceting formula which includes text or factor columns in |
ycoord |
(Default NULL) a two element list with limits on y corrdinates |
trimpctile |
(Default 0) trims data before any plotting to fall within |
legend |
(Default |
meltvar |
(Default: |
flip |
(Default |
ptsize |
(Default: 3) Size of points for |
A ggplot2::ggplot() object
fg_tsboxplot(eqtypx,breaks=c(7,30,360),normalize="byvar",hilightcats="QQQ", title="Equity prices, within ranges") fg_tsboxplot(narrowbydtstr(eqtypx,"-2y::"),breaks="regm",normalize="byvar", hilightcats="QQQ",title="Equity prices, in regimes") fg_tsboxplot(reerdta,breaks=c(0,0.2,0.5,1),doi="last",orderby="value", boxtype="nowhisker",facetform=". ~ REGION",title="Real Eff. Exch Rates") fg_tsboxplot(reerdta,breaks=c(0,0.2,0.5,1),doi="last",orderby="value", addline="last",boxtype="violin",title="Real Eff. Exch Rates (Violin)")fg_tsboxplot(eqtypx,breaks=c(7,30,360),normalize="byvar",hilightcats="QQQ", title="Equity prices, within ranges") fg_tsboxplot(narrowbydtstr(eqtypx,"-2y::"),breaks="regm",normalize="byvar", hilightcats="QQQ",title="Equity prices, in regimes") fg_tsboxplot(reerdta,breaks=c(0,0.2,0.5,1),doi="last",orderby="value", boxtype="nowhisker",facetform=". ~ REGION",title="Real Eff. Exch Rates") fg_tsboxplot(reerdta,breaks=c(0,0.2,0.5,1),doi="last",orderby="value", addline="last",boxtype="violin",title="Real Eff. Exch Rates (Violin)")
fg_update_aes() updates or replaces default aesthestics (e.g. colors, linestyles, etc).
fg_update_line_colors() replaces line colors only
fg_reset_to_default_state() resets colors and/or dates of interest
fg_replace_theme() Replaces default theme used in static plots
fg_verbose() Toggles printing of aesthetics
fg_update_aes(indta, aestype = NA_character_, persist = TRUE, replace = FALSE) fg_update_line_colors(colorlist, replace = FALSE, persist = TRUE) fg_replace_theme(newTheme, persist = TRUE) fg_verbose(item = "") fg_reset_to_default_state(reset = "all")fg_update_aes(indta, aestype = NA_character_, persist = TRUE, replace = FALSE) fg_update_line_colors(colorlist, replace = FALSE, persist = TRUE) fg_replace_theme(newTheme, persist = TRUE) fg_verbose(item = "") fg_reset_to_default_state(reset = "all")
indta |
|
aestype |
(Default: |
persist |
(Default: TRUE) Keep changes across invocations of the package. |
replace |
(Default: FALSE) Replaces existing dates of interest with new set provided, otherwise replaces/inserts new rows only. |
colorlist |
List with up to 14 new colors just for line (series) coloring |
newTheme |
A new ggplot2 theme |
item |
(Default: "") A grep string for categories desired. |
reset |
(Default: "all"), options in ("all","colors","doi") to reset to defaults with the package. |
For colors,
New data passed into fg_update_aes() persists across future loads of the package unless persist=FALSE.
New color datasets must have at least three columns:
| Column | Meaning |
category |
Arbitrary aestehtic category, e.g. "lines" for line colors. |
variable |
Any string that can be sorted or grepped to map to data. |
type |
Aesthetic type, in c("color","colorrange","linetype","symbol","alpha") |
value |
String with value detired (e.g a color) |
variable is used to prioritize colors, so (e.g. D01 will be the color of the first series in an input dataset)
If aestype=="colorrange" then a sequential scale of size n_max will be returned using details saved from fg_update_aes(). See scales::brewer_pal
and colorbrewer
No return value, as these are called for the side effects of adding to or replacing aesthetic sets.
fgts_dygraph(), fg_scatplot(), fg_get_aes()
# Data set, String head(oldcolors <- fg_get_aes("lines"),3) # then change as needed. For example, to make the second line blue, and the 4th line red, oldcolors[c(2,3),"value"] <- c("blue","tomato") fg_update_aes( oldcolors ) head( fg_get_aes("lines"),3) # to create a new category, make a similar `data.frame`, as in newcolors <- data.frame(category=rep("mylines",3),variable=c("D01","D02","D03"), value=c("red","black","green")) fg_update_aes( newcolors, aestype="color") fg_get_aesstring("mylines") #Theme replacement require(ggplot2) fg_replace_theme(ggplot2::theme_dark(),persist=FALSE) fg_reset_to_default_state("all")# Data set, String head(oldcolors <- fg_get_aes("lines"),3) # then change as needed. For example, to make the second line blue, and the 4th line red, oldcolors[c(2,3),"value"] <- c("blue","tomato") fg_update_aes( oldcolors ) head( fg_get_aes("lines"),3) # to create a new category, make a similar `data.frame`, as in newcolors <- data.frame(category=rep("mylines",3),variable=c("D01","D02","D03"), value=c("red","black","green")) fg_update_aes( newcolors, aestype="color") fg_get_aesstring("mylines") #Theme replacement require(ggplot2) fg_replace_theme(ggplot2::theme_dark(),persist=FALSE) fg_reset_to_default_state("all")
Plots interactive time series graphs with many options for highlighting key events, regions and customizations.
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() )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() )
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 |
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
|
bg_opts |
Semicomma separated options to change interactivity and background of charts. These semicomma separated options change pointer option and grids options.
|
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 |
hilightcols |
String or list of data series to plot in different style than other series. |
hilightwidth |
(Default: 2) relative width of series specified in |
hilightstyle |
(Default: solid). Line style of series specified in |
events |
String with possible events to add to graph. Options can be added together
with
|
event_ds |
|
annotations |
string with annotations on individual series or along
|
annotation_ds |
|
forecast_ds |
|
ylimits |
Two number vector of lower and upper limits of data to be displayed. Alternatively,
a string of the form |
dtstartfrac |
Fraction in (0,1] of dates in |
dtwindow |
String to specify date ranges applied |
rebase |
String of the form |
exportevents |
(Default: FALSE) Return list of the form |
meltvar |
(Default: |
dylegend |
(Default: "auto") Passed to |
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 |
verbose |
(Default: FALSE) Print extra details about what will be graphed. |
extraoptions |
Additional options passed to |
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
"doi,<category>" gets events from fg_get_dates_of_interest() which can be added to or managed using fg_update_dates_of_interest().
Colors and label placement can be customized as necessary.
seasonal,<type> puts regularly occurring events on the graph. <type> can be
<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:
| column | description | type |
date |
(Required) Start date | Date |
date_end |
End date to specify range of a colored band | Date |
text |
(Required) Text to display | character |
color |
Color for line and text | character |
eventonly |
Only draw line for for start of event, no band | logical |
strokePattern |
One of ('solid','dashed' (Default) ,'dotted','dotdash') | character |
loc |
one of ('top','bottom' (Default)) | character |
series |
Name of series to apply event to, if needed | character |
category |
Optional 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:
| column | description | type |
date |
(Required) Start date | Date |
date_end |
End date to specify range of a colored band | Date |
text |
(Required) Text to display | character |
color |
Color for line and text | character |
eventonly |
Only draw line for for start of event, no band | logical
|
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.
Dygraph dygraphs plotting input data, with annotations and other customizations.
# 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) require(timetk) require(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") fgts_dygraph(smalldta,title="With Forecasts", dtstartfrac=0.7,rebase=",100",forecast_ds=fpred)# 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) require(timetk) require(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") fgts_dygraph(smalldta,title="With Forecasts", dtstartfrac=0.7,rebase=",100",forecast_ds=fpred)
COnverts a generic relative string defining one or two endpoints to exact dates or datestrings
gendtstr(x, today = Sys.Date(), rtn = "dtstr") narrowbydtstr( xin, dtstr = "", includetoday = TRUE, windowdays = 0, invert = FALSE, addindicator = FALSE ) extenddtstr( instr, begchg = 0, endchg = 0, mindt = NULL, maxdt = NULL, rtn = "", rtnstyle = "string" )gendtstr(x, today = Sys.Date(), rtn = "dtstr") narrowbydtstr( xin, dtstr = "", includetoday = TRUE, windowdays = 0, invert = FALSE, addindicator = FALSE ) extenddtstr( instr, begchg = 0, endchg = 0, mindt = NULL, maxdt = NULL, rtn = "", rtnstyle = "string" )
x |
String describing generalized date as of today |
today |
Default |
rtn |
string describing what to do: ( |
xin |
Input |
dtstr |
Generalized Date string of the form |
includetoday |
(Default: TRUE) pass either today |
windowdays |
(Default: 0)Number of additional days to add at beginning of series |
invert |
(Default: FALSE) Return dates not in |
addindicator |
(Default: FALSE) Returns original dataset with logical variable |
instr |
Input generalized date string, |
begchg |
(Default: 0) Number of calendar days to extend beginning |
endchg |
(Default: 0) Number of calendar days to extend end |
mindt |
Minimum date to return |
maxdt |
Maximum date to return |
rtnstyle |
REturn datestring or list |
an exact start date startdt and an exact end date enddt, in the following forms:
If rtn="list" returns c(startdt,enddt), if rtn="first" then startdt, if rtn="days then an integer number of days from startdt to today otherwise (by default) "startdt::enddt"
Same form as xin, i.e. a data.table or data.frame
character string or list with new dates
gendtstr("-3m::") gendtstr("-2y::-3m",today=as.Date("2025-03-15")) narrowbydtstr(eqtypx,"-2m::-1m") extenddtstr("-2m::-1m") extenddtstr("-2m::-1m",begchg=-10,endchg=5)gendtstr("-3m::") gendtstr("-2y::-3m",today=as.Date("2025-03-15")) narrowbydtstr(eqtypx,"-2m::-1m") extenddtstr("-2m::-1m") extenddtstr("-2m::-1m",begchg=-10,endchg=5)
IMF World Economic Outlook June 2025
imfdtaimfdta
imfdtaA long format data.table with both historical economic data and projections.
ISO Country code
IMF subject classification
Value of historical data or forecast
Short abbreviation for SUBJ
Full country name correponding to CC
Investment Region each country is in
Dominant currency used in Country
Date of historical data or of forecast
https://www.imf.org/en/publications/weo
Closing Nominal currency levels (local currency per dollar)
nomfxdtanomfxdta
nomfxdtaA tibble with 13134 observations and 3 columns
Date Of Observation
CUrrency
Currency/USD
Ratings changes for a few select sovereigns.
ratings_dbratings_db
ratings_dbA tibble with 110 observations and 5 columns
Short Credit name for a few countries
Ratings Agency
Rating code for each country specific to each agency
Character indicator if ratings is watch positive or negative
Date of ratings annoucement
Monthly recession indicator, FRED code RECPROUSM156N
recession_indicrecession_indic
recession_indic A data frame with 120 rows and 3 columns
FRED identifier
Date of report
Observation
Real Effective Exchange Rates
reerdtareerdta
reerdtaA tibble with 1920 observations and 3 columns
Date Of Observation
ISO Country code
investment region to which each country belongs
Index of Real Effective Exchange Rates
FRED calculated constant maturity interest rates
yc_CMSUSTyc_CMSUST
yc_CMSUSTA long format data.table with constant maturity UST with tenors 2 year, 10 year and 30 year
Term of UST
Date of observation
Annualized Percent interest rae