Title: | 'Dang' Associated New Goodies |
---|---|
Description: | A collection of utility functions. |
Authors: | Dirk Eddelbuettel [aut, cre] |
Maintainer: | Dirk Eddelbuettel <[email protected]> |
License: | GPL (>= 2) |
Version: | 0.0.16.3 |
Built: | 2024-08-21 23:16:05 UTC |
Source: | https://github.com/eddelbuettel/dang |
Fetch a real-time market data series from AlphaVantage
alphavantage(sym)
alphavantage(sym)
sym |
Character value for the ticker |
Several optional parameters could be set, but are not currently.
A data.table object
Dirk Eddelbuettel
Convert an xts object into a data.table
## S3 method for class 'xts' as.data.table(x) as.data.table(x) ## Default S3 method: as.data.table(x, ...)
## S3 method for class 'xts' as.data.table(x) as.data.table(x) ## Default S3 method: as.data.table(x, ...)
x |
An xts object |
... |
Catch-all arguments passed on to methods |
This is still experimental. Note that all four added
columns are keys to the data.table object, and that
setNumericRounding(0)
is executed too,
A data.table object with new columns date, time, micros,
pt providing, respectively the data as IDate
, time as
ITime
, microseconds (rounded) and numeric
POSIXct
.
Dirk Eddelbuettel
Debugging helper to assign formals from function
assignFormals(f, env = .GlobalEnv)
assignFormals(f, env = .GlobalEnv)
f |
A function |
env |
An environment to assign the values to, defaults to global environment, |
(Beta) Attempt get default values from a given function,
extracting its arguments and assigning which should help in
debugging via browser()
and other helper functions.
Nothing, but a side effect of assignment in global environment
Dirk Eddelbuettel
Report Maintainer Status at CRAN
checkCRANStatus(email, cache, cache.life = 24 * 3600)
checkCRANStatus(email, cache, cache.life = 24 * 3600)
email |
A character variable with the maintainer email |
cache |
A character variable with an optional cache file, default value is to use a file inside the per-session temporary directory |
cache.life |
A numeric timeout, defaults to one day |
This function retrieves the maintainer status (given an email) at CRAN. Values are optionally cached; the default cache location is inside the per-session temporary directory as R should not write elsewhere.
Nothing, the sideffect of the display is the main effect
Brodie Gaslam (with minor modifications by Dirk Eddelbuettel)
Check a package directory for non-ASCII characters in source files.
checkPackageAsciiCode(dir, respect_quotes = FALSE)
checkPackageAsciiCode(dir, respect_quotes = FALSE)
dir |
Character variable with path to directory to be checked |
respect_quotes |
Logical variable whether quotes need to be checked |
The function is a renamed and slightly edited copy of the base R function
.check_package_ASCII_code
. It uses an unexported C function, also
included, from base R, called as _check_nonASCII
.
A vector of things that are wrong per this function, also displayed on standard output
Dirk Eddelbuettel for this version, R Core for the underlying code
## Not run: checkPackageAsciiCode(".", FALSE) ## End(Not run)
## Not run: checkPackageAsciiCode(".", FALSE) ## End(Not run)
This function returns a three-column data frame with first name, family name and orcid for all maintainers with (optional) ORCID fields at CRAN.
cranORCIDs()
cranORCIDs()
A data frame with three columns given (ie first name), family (name) and oid.
Kurt Hornik (plus small tweaks by Dirk Eddelbuettel)
A new function tools::CRAN_authors_db()
in r-devel as of August 2024.
Display a demotivating quote to remind the users of the harsh reality econometric and statistical practice.
demotivate(x, width = NULL)
demotivate(x, width = NULL)
x |
A index value chosen to select a quote; if not given a quote is chosen randomly. |
width |
The desired display width. |
This function is a port of demotivate
command for 'Stata' from the
ado file at http://fmwww.bc.edu/repec/bocode/d/demotivate.ado.
The formatted is returned invisibly.
Dirk Eddelbuettel for this function, and Kevin Denny for the 'Stata' original.
https://ideas.repec.org/c/boc/bocode/s458576.html
demotivate()
demotivate()
git
repository?The getGitRoot()
function recursively ascends the
filesystem tree from the given directory until it either finds a
directory .git
, or the top-level directory to abort the
search. The root directory of the git
repository is
returned, with an exmpty string in the case of no repository. The
inGit()
function turns this into boolean predicate returning
either TRUE
or FALSE
.
getGitRoot(cwd = getwd()) inGit(cwd = getwd())
getGitRoot(cwd = getwd()) inGit(cwd = getwd())
cwd |
The start directory, default to the current working directory |
For getGitRoot()
, the path of the directory containing
the .git
directory, ie the project root directory, or an
empty string in case the search started outside a git
directory.
The inGit()
function returns a boolean as to whether a git
repository was found or not.
Dirk Eddelbuettel
inGit()
inGit()
Download historical time series from Google Finance
googleFinanceData(sym, current = TRUE, sy = 2005, sm = 1, sd = 1, ey, em, ed)
googleFinanceData(sym, current = TRUE, sy = 2005, sm = 1, sd = 1, ey, em, ed)
sym |
A character string for a (tradeable) symbol |
current |
A logical switch to indicate whether the current time is the endtime |
sy |
An integer value for the start year, default is 2005 |
sm |
An integer value for the start month, default is 1 |
sd |
An integer value for the start date, default is 1 |
ey |
An optional integer value for the end year, required if |
em |
An optional integer value for the end month, required if |
ed |
An optional integer value for the end day, required if |
The function uses an (unofficial) older CGI-style interface at Google to download historical data.
A data.table
object with a key on date
Dirk Eddelbuettel
The post at https://web.archive.org/web/20221007040328/https://chrisconlan.com/download-historical-stock-data-google-r-python/ provided the initial starting point
Intra-day Market Monitor for Security Prices
intradayMarketMonitor(symbol = "^GSPC", defaultTZ = "America/Chicago", sleep = 10)
intradayMarketMonitor(symbol = "^GSPC", defaultTZ = "America/Chicago", sleep = 10)
symbol |
A character variable with symbol understood by |
defaultTZ |
A character variable with the (local) timezone used for displaying the data, default value is “America/Chicagp”. |
sleep |
An optional numerical value for the delay between updates, default is 10. |
This function periodically queries a public data source for a current price of given symbol and updates an intra-daily chart for that security. A working example is symbol “^GSPC” for the S&P500 index which can be obtained in real-time during (New York) trading hours. Other symbols may work.
An alternate version offering 24-hour coverage, for example for futures on Globex, is being prepared.
The function could be further generalized in numerous way and should be considered
‘alpha’. Current default values are a 15 second sleep, and fixed cut-off times
for market open/close states corresponding to NYSE hours. The data history is reset to
the two most recent days at the close, amd the data is snapshot to file (with the
filename derived from the symbol, and the path given by tools::R_user_dir
).
These parameters might become configuration parameters in the future.
Nothing is returned, but a display of the current price and the recent history is updated, and the loops loops ‘forever’.
Dirk Eddelbuettel extending and refactoring the original code by Josh Ulrich
https://gist.github.com/joshuaulrich/ee11ef67b1461df399b84efd3c8f9f67#file-intraday-sp500-r
if (requireNamespace("quantmod", quietly)) { # only suggested packages used suppressMessages({library(xts);library(quantmod)}) # dampen noise, add dang as needed intradayMarketMonitor() }
if (requireNamespace("quantmod", quietly)) { # only suggested packages used suppressMessages({library(xts);library(quantmod)}) # dampen noise, add dang as needed intradayMarketMonitor() }
Function to (heuristically) test for a network connection by attempting to connect to a given website.
isConnected(site = "https://www.google.com")
isConnected(site = "https://www.google.com")
site |
Character variable with site to try to connect to,
defauls to |
The main page of Google is used as a proxy for overall network connectivity as Google is generally 'network-close' and the page is relatively small. If a network is unavailable this fails generally already on domain name service resolution. Special thanks to Barry and Brodie for a very helpful discussion re-discovering this function.
A boolean value indicating networking status
Dirk Eddelbuettel
Set threads for data.table respecting possible local settings
limitDataTableCores(ncores, verbose = FALSE)
limitDataTableCores(ncores, verbose = FALSE)
ncores |
A numeric or character variable with the desired count of threads to use |
verbose |
A logical value with a default of ‘FALSE’ to operate more verbosely |
This function set the number of threads data.table will use while reflecting two possible machine-specific settings from the environment variable ‘OMP_THREAD_LIMIT’ as well as the R option ‘Ncpus’ (uses e.g. for parallel builds).
The return value of the data.table function
setDTthreads
which is called as a side-effect.
Dirk Eddelbuettel
List object and memory used by these objects
ls.objects(pos = 1, pattern, order.by, decreasing = FALSE, head = FALSE, n = 5) lsos(..., n = 10) showMemoryUse(sort = "size", decreasing = FALSE, limit)
ls.objects(pos = 1, pattern, order.by, decreasing = FALSE, head = FALSE, n = 5) lsos(..., n = 10) showMemoryUse(sort = "size", decreasing = FALSE, limit)
pos |
Position in search path, defaults to 1 |
pattern |
Pattern argument pass on to |
order.by |
Optional sort order column |
decreasing |
Optional switch for decreasing or increasing sort order |
head |
Optional switch to show |
n |
Number of elements to show, default to 5 |
... |
Passed through from |
sort |
Sort columns, defauls to ‘size’ |
limit |
Optional cap on displayed number of items |
These helper functions have evolved over the years; some were also posted on StackOverflow in response to https://stackoverflow.com/questions/1358003/tricks-to-manage-the-available-memory-in-an-r-session
The displayed data.frame is returned to, the main purpose effect however is the displayed information
Dirk Eddelbuettel, based on and extending code in mailing list posts by Petr Pikal and David Hinds
Display a motivating quote for users.
motivate(x, width = NULL)
motivate(x, width = NULL)
x |
A index value chosen to select a quote; if not given a quote is chosen randomly. |
width |
The desired display width. |
This function is a port of motivate
command for 'Stata' from the
ado file at http://fmwww.bc.edu/repec/bocode/m/motivate.ado
The formatted is returned invisibly.
Dirk Eddelbuettel for this function, and Kabira Namit for the 'Stata' original.
https://ideas.repec.org/c/boc/bocode/s458565.html
motivate()
motivate()
Mutes Twitter accounts using for than 'ncrit' hashtags among 'N' tweets in search of along with of 'term'.
muteTweeters(term = "#rstats", N = 1000, ncrit = 10)
muteTweeters(term = "#rstats", N = 1000, ncrit = 10)
term |
A character variable to search for, defaults to ‘#rstats’ |
N |
An number of tweets to fetch, defaults to 1000 |
ncrit |
A number of hashtags after which use is deemed excessive, defaults to 10 |
This is a modified version of the code in a wonderful tweet by Colin
Gillespie (csgillespie) on 2020-August-26. It requires the rtweet
and data.table
packages.
NULL
, invisibly, but the function is invoked for the side effect
of calling post_mute
.
Dirk Eddelbuettel
## Not run: ## mute users with more than 10 hashtags among ## the 1000 most recent #rstats tweets muteTweeters("#rstats", 1000, 10) ## End(Not run)
## Not run: ## mute users with more than 10 hashtags among ## the 1000 most recent #rstats tweets muteTweeters("#rstats", 1000, 10) ## End(Not run)
Compute and display overbought and oversold regions
plotOBOS(symbol, n = 50, type = c("sma", "ema", "zlema", "hma"), years = 1, blue = TRUE, current = TRUE, title = symbol, ticks = TRUE, axes = TRUE)
plotOBOS(symbol, n = 50, type = c("sma", "ema", "zlema", "hma"), years = 1, blue = TRUE, current = TRUE, title = symbol, ticks = TRUE, axes = TRUE)
symbol |
A (required) character string for stock symbol, or
alternatively a |
n |
An optional integer for the moving average length, defaults to 50 |
type |
An optional character string for the type of moving average; currently supported are ‘SMA’, ‘EMA’, ‘ZLEMA’, and ‘HMA’. |
years |
An optional numeric or integer value for the number of years of data to display, defaults to one |
blue |
An optional boolean determining whether blue or gray tones are used, defaults to true implying blue tones |
current |
An optional boolean determining whether the current date is the end date |
title |
An optional character string for the plot title, defaults to the symbol |
ticks |
An optional boolean indicating whether ticks are plotted,
passed on to |
axes |
An optional boolean indicating whether axes are plotted,
passed on to |
This function computes a smoothed version of the price using a moving average (with one of several possible methods) as well as a standard deviation band, and displays one and two standard deviations around the smoothed price.
NULL
as the function is invoked for the side effect of
the plot
Dirk Eddelbuettel
Print helper function for xts objects.
## S3 method for class 'xts' print(x, ..., n = 10)
## S3 method for class 'xts' print(x, ..., n = 10)
x |
An xts objects |
... |
Ignored, but needed for consistency with |
n |
The default number of lines to display, default is 10. |
The return from print
Dirk Eddelbuettel
Read a file in a different encoding and return it as UTF-8 using iconv
readAndConvert(filename, encoding = "")
readAndConvert(filename, encoding = "")
filename |
Character variable with path a file with text in encoding |
encoding |
Optional character variable with the encoding, if unset via the default empty string value no conversion is attempted. |
The function is an adapted version of the one in the Rcpp Gallery post at https://gallery.rcpp.org/articles/iconv-via-r-header/ which is itself based on https://dewey.dunnington.ca/post/2021/using-rs-cross-platform-iconv-wrapper-from-cpp11/. It is however worth pointing out that ‘iconv’ results have been seen to vary across operating systems. While it is portable it does not guarantee identical outcomes across implementations: results on Windows have different from those on Unix OSs.
A character variable with converted file content.
Reorder microbenchmark results
reorderMicrobenchmarkResults(res, order = "median") rmr(res, order = "median")
reorderMicrobenchmarkResults(res, order = "median") rmr(res, order = "median")
res |
An object returned from 'microbenchmark::microbenchmark' |
order |
An option character variable selecting a column to order on, defaults to 'median' |
The lovely 'microbenchmark' package returns its result is a simple structure with 'factor' variable which it leaves unordered. The printed as well as plotted results become a little more expressive if an order is added, which this helper function does.
'rmr' can be used as a shorter alias
A modified version of 'res' with an ordering by 'order'
This implementation is minimal without error checking, or NA handling. It is taken from the ichimoku package which had several more complicated variants, and is reused here with just tidyCpp.
rollMinMax(x, window, min = TRUE)
rollMinMax(x, window, min = TRUE)
x |
A numeric vector. |
window |
An interger with the size of the rolling window. |
min |
A logical which, if true, selects minimum, else maximum |
The ichimoku variant is by Charlie Gao and credits Andrew Uhl for the initial implementation.
A vector of the same length as 'x' with elements 1 to (length(window) - 1) containing NAs.
Dirk Eddelbuettel for this version, extending earlier by Charlie Gao crediting Andrew Uhl.
Return a data.table object with ‘shadowed’ packages,
meaning package which are installed in more than directory on the
.libPaths
.
shadowedPackages()
shadowedPackages()
The function relies on the base R functions
installed.packages()
to find all packages, as well as the
base R abilility to compare version numbers (once properly
converted to package_version
type).
data.table object with packages that are shadowed
Dirk Eddelbuettel
Silently attach a library to the search path.
silent(...)
silent(...)
... |
Passed though |
This function wraps suppressMessages
around the call to
library
Nothing, but the desired library is attached
Dirk Eddelbuettel
Print a parse tree
## S3 method for class 'language' str(expr, name = "", indent = 0)
## S3 method for class 'language' str(expr, name = "", indent = 0)
expr |
An R language expression to be parse and displayed |
name |
An optional character value with default ” to annotate the display |
indent |
An optional numeric value with default 0 to provide additional indentation |
The expression, invisibly
Bill Dunlap (and posted to r-devel on 4 Feb 2022)
Return the day of the week as an integer
wday(date = Sys.Date())
wday(date = Sys.Date())
date |
A Date object, with the current date as the default |
This function simply wraps around the as.POSIXlt
function and returns its
wday
field.
A integer with the weekday component of the date
Format a Date(time) object as ymd
ymd(pt)
ymd(pt)
pt |
A |
A character object formatted as ‘YYYYMMDD’
Dirk Eddelbuettel
if (requireNamespace("anytime", quietly=TRUE)) { ymd(anytime::anytime("2016-09-01 10:11:12.123456")) ymd(anytime::anydate("2016-Sep-01")) }
if (requireNamespace("anytime", quietly=TRUE)) { ymd(anytime::anytime("2016-09-01 10:11:12.123456")) ymd(anytime::anydate("2016-Sep-01")) }