| Title: | Comprehensive R Wrapper and Shiny Interface for 'Alphavantage Financial Data' API |
|---|---|
| Description: | Download, manage, and visualize 'Alphavantage financial data' <https://www.alphavantage.co/documentation/> to reduced 'data.table' objects. API interface Includes support functions to extract and simplify returned complex data. A Shiny application is also provided to download, manage, and graph asset prices and characteristics. |
| Authors: | Derek Holmes [aut, cre, cph] |
| Maintainer: | Derek Holmes <[email protected]> |
| License: | GPL (>= 3) |
| Version: | 0.7.5 |
| Built: | 2026-06-10 23:05:23 UTC |
| Source: | https://github.com/derekholmes0/alphavantagepf |
An R interface to the Alpha Vantage API which emphasizes normalized data nd data.table conventions
The alphavantagepf package provides a lightweight interface to the
Alpha Vantage API. Alpha Vantage is a free source for financial data
that in many cases is more accurate than Yahoo Finance and Google Finance.
Get a free API KEY at https://www.alphavantage.co. Then use the R interface
functions av_api_key("YOUR_KEY") to set the API key and the av_get_pf()
function to get financial data.
Adds price data to av_runShiny() internal data.
Adds asset lists to av_runShiny() internal data.
av_add_data(indta, assettypes = NULL, delay = 0) av_add_assetgroups(indta)av_add_data(indta, assettypes = NULL, delay = 0) av_add_assetgroups(indta)
indta |
A data.frame with two columns |
assettypes |
(default NULL) An optional data.frame with minimal columns |
delay |
(default 0) Seconds to delay calls to determine asset type for future AV downloads. This is
unused if |
Entire set of columns from av_get_pf() can be added. First date column renamed to timestamp
Lists are specified in normalized form. Duplicate list names with those currently in use are replaced.
Nothing
Nothing
## Not run: av_add_data(av_get_pf("IBM","TIME_SERIES_DAILY_ADJUSTED")) suppressMessages(require(quantmod)) ffdta <- as.data.table(quantmod::getSymbols("FEDFUNDS",src="FRED",auto.assign=FALSE)) ffdta <- ffdta[,.(DT_ENTRY=index,close=FEDFUNDS,adjusted_close=FEDFUNDS,symbol="FEDFUNDS")] av_add_data(ffdta) ## End(Not run) ## Not run: newtickers <- c("QQQ","QQQE","NDX") av_add_assetgroups(data.table(listnm=rep("nasdaq",length(newtickers)),ticker=newtickers)) # To remove an asset list, just use an empty string for the ticker av_add_assetgroups(data.table(listnm=c("new"),ticker=c(""))) ## End(Not run)## Not run: av_add_data(av_get_pf("IBM","TIME_SERIES_DAILY_ADJUSTED")) suppressMessages(require(quantmod)) ffdta <- as.data.table(quantmod::getSymbols("FEDFUNDS",src="FRED",auto.assign=FALSE)) ffdta <- ffdta[,.(DT_ENTRY=index,close=FEDFUNDS,adjusted_close=FEDFUNDS,symbol="FEDFUNDS")] av_add_data(ffdta) ## End(Not run) ## Not run: newtickers <- c("QQQ","QQQE","NDX") av_add_assetgroups(data.table(listnm=rep("nasdaq",length(newtickers)),ticker=newtickers)) # To remove an asset list, just use an empty string for the ticker av_add_assetgroups(data.table(listnm=c("new"),ticker=c(""))) ## End(Not run)
av_api_key() sets Alphavantage API key and entitlement code
av_api_key(api_key, entitlement = NULL)av_api_key(api_key, entitlement = NULL)
api_key |
A character string with your Alpha Vantage API Key. |
entitlement |
A character string with your Alpha Vantage entitlement status. If not "delayed" or "realtime" entitlement not added to API string. |
The Alpha Vantage API key must be set prior to using av_get_pf(). You can obtain
an API key at the Alpha Vantage Website.
Invisibly returns two item list with API key and entitlement string once set). Use print method to view.
## Not run: av_api_key("YOUR_API_KEY",entitlement="delayed") av_get_pf("IBM", "TIME_SERIES_INTRADAY") ## End(Not run)## Not run: av_api_key("YOUR_API_KEY",entitlement="delayed") av_get_pf("IBM", "TIME_SERIES_INTRADAY") ## End(Not run)
av_extract_df() pulls out nested data.frames from mixed data returned by av_get_pf()
av_extract_fx() returns a simplified FX quote in data.table formfrom av_get_pf() calls.
av_extract_analytics() returns melted data.table from calls to av_get_pf("ANALYTICS_FIXED_WINDOW") or av_get_pf("ANALYTICS_SLIDING_WINDOW")
av_extract_divs_or_splits() returns melted data.table from calls to av_get_pf("DIVIDENDS") or av_get_pf("SPLITS")
av_extract_df(indta, grepstring = "", melt = FALSE, empty_dt_onerror = FALSE) av_extract_fx(indta, outputform = "common", cols = "") av_extract_analytics(indta, separate_vars = FALSE) av_extract_divs_or_splits(indta)av_extract_df(indta, grepstring = "", melt = FALSE, empty_dt_onerror = FALSE) av_extract_fx(indta, outputform = "common", cols = "") av_extract_analytics(indta, separate_vars = FALSE) av_extract_divs_or_splits(indta)
indta |
A data.table as returned by av_get() |
grepstring |
select which variable (data item) to unnest in data.table returned from av_get_pf |
melt |
Return data in melted/normalized form |
empty_dt_onerror |
(default : FALSE): Return gracefully an empty data.table if requested item is not present. |
outputform |
(default : |
cols |
(default : all columns: |
separate_vars |
(default : FALSE) separate out multiple levels of variable names into new keys |
av_get_pf() frequently returns a nested data.table, or a structure with nested data.frames. These are utilities functions to extract, filter and summarize returned values.
Extracted data.tables for nested data returned from av_get_pf(), If grepstring is not specified, first nested table is returned. av_extract_fx() returns a shortened data.table with FX quotes.
## Not run: av_get_pf("","MARKET_STATUS") |> av_extract_df() av_get_pf("","TOP_GAINERS_LOSERS") |> av_extract_df("top_losers") av_get_pf("USD/BRL","CURRENCY_EXCHANGE_RATE") |> av_extract_fx() av_get_pf(c("ORCL","IBM"),"ANALYTICS_FIXED_WINDOW") |> av_extract_analytics(separate_vars=TRUE) ## End(Not run)## Not run: av_get_pf("","MARKET_STATUS") |> av_extract_df() av_get_pf("","TOP_GAINERS_LOSERS") |> av_extract_df("top_losers") av_get_pf("USD/BRL","CURRENCY_EXCHANGE_RATE") |> av_extract_fx() av_get_pf(c("ORCL","IBM"),"ANALYTICS_FIXED_WINDOW") |> av_extract_analytics(separate_vars=TRUE) ## End(Not run)
Extract data from Alpha Vantage retuned data
av_funhelp(av_fun_grep = "", verbose = TRUE)av_funhelp(av_fun_grep = "", verbose = TRUE)
av_fun_grep |
A Alpha Vantage function name or portions of one. For a list of parameters, visit the Alpha Vantage API documentation. |
verbose |
(Default: TRUE) Prints the help string |
Returns defaults and parameter lists for Alphavantage functions
Help Text and default parameters.
av_funhelp("GLOBAL_QUOTE")av_funhelp("GLOBAL_QUOTE")
Interface to alphavantage API.
av_get_pf( symbol, av_fun, symbolvarnm = "symbol", dfonerror = TRUE, melted = "default", delay = 0, verbose = FALSE, ... )av_get_pf( symbol, av_fun, symbolvarnm = "symbol", dfonerror = TRUE, melted = "default", delay = 0, verbose = FALSE, ... )
symbol |
A character string of an appropriate stock, fund, or currency See parameter "symbol" in Alpha Vantage API documentation. |
av_fun |
A character string matching an appropriate Alpha Vantage "function". See parameter "function" in Alpha Vantage API documentation. |
symbolvarnm |
(default: |
dfonerror |
(default: TRUE) Return an empty data.table when any error occurs |
melted |
(default: "default") String specifying when to melt, "default" is chosen by the package, "TRUE|always" always melt, "FALSE|never" never melts |
delay |
(default: 0) Delay in seconds after API call, used to embed within large single-symbol calls. |
verbose |
(default: FALSE) Print debug information helpful for errors. Also copies full url to clipboard. |
... |
Additional parameters or overrides passed to the Alpha Vantage API. For a list of parameters, visit the Alpha Vantage API documentation. |
The av_fun argument replaces the API parameter “function” because function is a reserved name in R. All other arguments match the Alpha Vantage API parameters.
There is no need to specify the apikey, datatype, outputsize or entitlement parameters as arguments to av_get_pf(). Before using, you must set the API key using av_api_key("YOUR_API_KEY"). outputsize defaults to "full" unless overridden with "compact in ...."
Required parameters other than symbol must be passed as named arguments via ....
Optional parameters have defaults which can be obtained by calling av_funhelp() and overridden via ....
There is no need to specify the datatype parameter as an argument to av_get_pf(). The function will return a data.table.
ForEx "FROM/TO" symbol details. FOREX symbols in the av_get_pf() function are
supplied in "FROM/TO" format, which are then parsed in the Alpha Vantage API
into from_currency and to_currency API parameters. Usage example:
av_get_pf("USD/BRL", "FX_DAILY")
Returns a data.table with results dependent on the function called. Mixed data is returned as a melted data.table, possibly with nested data.frames. Time series are returned as data.tables.
av_api_key(), av_extract_df(), av_extract_fx(), av_grep_opts(),av_funhelp()
## Not run: av_api_key("YOUR_API_KEY") av_api_key("YOUR_API_KEY","delayed") # if you have such access # example code # ---- 1.0 SINGLE NAME EQUITY SUMMARY INFORMATION AND SEARCH ---- av_get_pf("IBM","OVERVIEW") |> str() av_get_pf("EWZ","ETF_PROFILE") av_get_pf("EWZ","ETF_PROFILE") |> av_extract_df("holdings") av_get_pf("","SYMBOL_SEARCH",keywords="COMMERCE") # ---- 2.0 MARKET QUOTES ---- av_get_pf("IBM","GLOBAL_QUOTE") av_get_pf("USD/BRL","CURRENCY_EXCHANGE_RATE") |> av_extract_fx() av_get_pf(c("ORCL","IBM","EWZ","ARGT"),"REALTIME_BULK_QUOTES",melt=FALSE) # Note you need advanced permissioning for REALTIME_BULK_QUOTES # ---- 3.0 SINGLE NAME HISTORICAL DATA ---- av_get_pf("IBM","TIME_SERIES_DAILY") av_get_pf("IBM","TIME_SERIES_INTRADAY") # ---- 4.0 MARKET PRICING DATA ---- av_get_pf("","MARKET_STATUS") |> av_extract_df() av_get_pf("","TOP_GAINERS_LOSERS") |> av_extract_df("top_losers") av_get_pf("","TREASURY_YIELD",maturity='7year') # ---- 4.0 SINGLE NAME NON-PRICING DATA ---- av_get_pf("IBM","DIVIDENDS") av_get_pf("IBM","EARNINGS") |> av_extract_df("quarter",melt=TRUE) av_get_pf("IBM","NEWS_SENTIMENT") |> av_extract_df("feed") av_get_pf("IBM","EARNINGS_CALL_TRANSCRIPT",quarter="2024Q3") |> av_extract_df("transcript") # Note that quarter is a required parameter, not specifying will throw an error # ---- 5.0 SINGLE NAME OPTION PRICING DATA ---- av_get_pf("IBM","HISTORICAL_OPTIONS") |> av_grep_opts("F,M,put",mindays=2) # ---- 6.0 TECHNICAL INDICATORS ---- av_funhelp("SMA") # Shows parameters and defaults chosen by this package. av_get_pf("IBM","SMA",time_period=20) # ---- 7.0 WINDOW ANALYTICS ---- av_get_pf(c("ORCL","IBM","EWZ","ARGT"),"ANALYTICS_FIXED_WINDOW",verbose=TRUE) |> av_extract_analytics(separate_vars=TRUE) ## End(Not run)## Not run: av_api_key("YOUR_API_KEY") av_api_key("YOUR_API_KEY","delayed") # if you have such access # example code # ---- 1.0 SINGLE NAME EQUITY SUMMARY INFORMATION AND SEARCH ---- av_get_pf("IBM","OVERVIEW") |> str() av_get_pf("EWZ","ETF_PROFILE") av_get_pf("EWZ","ETF_PROFILE") |> av_extract_df("holdings") av_get_pf("","SYMBOL_SEARCH",keywords="COMMERCE") # ---- 2.0 MARKET QUOTES ---- av_get_pf("IBM","GLOBAL_QUOTE") av_get_pf("USD/BRL","CURRENCY_EXCHANGE_RATE") |> av_extract_fx() av_get_pf(c("ORCL","IBM","EWZ","ARGT"),"REALTIME_BULK_QUOTES",melt=FALSE) # Note you need advanced permissioning for REALTIME_BULK_QUOTES # ---- 3.0 SINGLE NAME HISTORICAL DATA ---- av_get_pf("IBM","TIME_SERIES_DAILY") av_get_pf("IBM","TIME_SERIES_INTRADAY") # ---- 4.0 MARKET PRICING DATA ---- av_get_pf("","MARKET_STATUS") |> av_extract_df() av_get_pf("","TOP_GAINERS_LOSERS") |> av_extract_df("top_losers") av_get_pf("","TREASURY_YIELD",maturity='7year') # ---- 4.0 SINGLE NAME NON-PRICING DATA ---- av_get_pf("IBM","DIVIDENDS") av_get_pf("IBM","EARNINGS") |> av_extract_df("quarter",melt=TRUE) av_get_pf("IBM","NEWS_SENTIMENT") |> av_extract_df("feed") av_get_pf("IBM","EARNINGS_CALL_TRANSCRIPT",quarter="2024Q3") |> av_extract_df("transcript") # Note that quarter is a required parameter, not specifying will throw an error # ---- 5.0 SINGLE NAME OPTION PRICING DATA ---- av_get_pf("IBM","HISTORICAL_OPTIONS") |> av_grep_opts("F,M,put",mindays=2) # ---- 6.0 TECHNICAL INDICATORS ---- av_funhelp("SMA") # Shows parameters and defaults chosen by this package. av_get_pf("IBM","SMA",time_period=20) # ---- 7.0 WINDOW ANALYTICS ---- av_get_pf(c("ORCL","IBM","EWZ","ARGT"),"ANALYTICS_FIXED_WINDOW",verbose=TRUE) |> av_extract_analytics(separate_vars=TRUE) ## End(Not run)
Extract data from Alpha Vantage returned data
av_grep_opts( indta, grepstring = "F,M,C,otm", spot = NULL, mindays = 3, startdt = Sys.Date(), mindelta = 0.05, dropsymbol = FALSE )av_grep_opts( indta, grepstring = "F,M,C,otm", spot = NULL, mindays = 3, startdt = Sys.Date(), mindelta = 0.05, dropsymbol = FALSE )
indta |
A data.table as returned by |
||||||||||||||||||
grepstring |
(default
|
||||||||||||||||||
spot |
(default |
||||||||||||||||||
mindays |
(default 3). Minimum number of days to expiration to be passed through from |
||||||||||||||||||
startdt |
(default |
||||||||||||||||||
mindelta |
(default |
||||||||||||||||||
dropsymbol |
(default |
av_get_pf() returns a large list of options. This function helps to narrow down the list by maturity and moneyness.
A reduced set of options obtained from av_get_pf() using Alphavantage HISTORICAL_OPTIONS function.
## Not run: av_get_pf("IBM","HISTORICAL_OPTIONS") |> av_grep_opts("F,M,put",mindays=2) ## End(Not run)## Not run: av_get_pf("IBM","HISTORICAL_OPTIONS") |> av_grep_opts("F,M,put",mindays=2) ## End(Not run)
Extract data from Alpha Vantage retuned data
av_make_funcmap()av_make_funcmap()
Creates a data.table with API signatures and default values for Alphavantage API calls
function map dat.table, also written to data directory
## Not run: av_make_funcmap() ## End(Not run)## Not run: av_make_funcmap() ## End(Not run)
Add additional data to returned option sets
av_opt_helper_cols(indta, scaling = NULL, spot = NULL)av_opt_helper_cols(indta, scaling = NULL, spot = NULL)
indta |
An option data.table as returned by |
scaling |
(default
|
spot |
(default |
Adds columns including
| Column | Definition |
daysExp |
Days to Expiration |
bo_pct |
Bid offer in percent of option mid |
bid_size_poi |
Bid size percent of open interest |
ncak |
Notional number of contracts |
An option data.table with extra columns helpful for further analysis
## Not run: av_get_pf("IBM","HISTORICAL_OPTIONS") |> av_grep_opts("F,M,put",mindays=2) |> av_opt_helper_cols() ## End(Not run)## Not run: av_get_pf("IBM","HISTORICAL_OPTIONS") |> av_grep_opts("F,M,put",mindays=2) |> av_opt_helper_cols() ## End(Not run)
Extract data from Alpha Vantage retuned data
av_reset_defaults(fileopts = TRUE)av_reset_defaults(fileopts = TRUE)
fileopts |
(default: TRUE) If TRUE, then remove all files and subdirectories |
Resets av_runShiny() defaults to original (newly installed) state
No return
## Not run: av_reset_defaults() ## End(Not run)## Not run: av_reset_defaults() ## End(Not run)
av_runShiny() runs an interactive RShiny app to download, manage, and visualize data from the Alpha Vantage data service.
The app treats equities, ETFs, indices, and FX equally, so users do not need to know specific API calls to integrate data. Downloaded data is cached to reduce
API calls, all data can be saved for external use, and external data can be added to the app. Sets of securities can be easily added and managed.
av_runShiny()av_runShiny()
Invocation starts Shiny application. See vignette for full details.
On first use, click on AVOPTS tab, fill in the following fields, and hit the "Set Opts" button.
++AV API Key++: API key obtained from Alpha Vantage
++Entitlement++ Entitlement status (either delayed or realtime)
Other options that can be set are given below.
To run analysis, Enter a semicolon delimited set of securities (e.g. SPY;QQQ;DIA), select a runtime option from
the adjacent dropdown, and press the 'RUN button. Options include:
| Option | Description |
Inventory |
Table of what asset lists and price data is available |
LivePx |
Live prices of all tickers |
NameSearch |
Search for tickers |
PriceTS |
Time Series of prices or Total Return indices |
ActiveTS |
Active returns of tickers in top row relative to first ticker in bottom row |
HistVolTS |
Historic vol and rolling correlations of tickers in top row. |
DES,News |
Descriptions and News for tickers in top row. |
DivEarn |
Dividends, earnings, and earnings estimates for tickers in top row. |
OptSearch |
Search for options for tickers in top row. (OPTS tab)
|
** Options that can be set**. click on AVOPTS tab, fill in the following fields, and hit the "Set Opts" button.
fgts colorset: A named list of colors which can be set using the FinanceGraphs::fg_update_aes() function.
Regr Significance: p-level to highlight significant regressions. (Used in the HistVolTS function above.)
Cache Directory: A directory where internal App data can be stored (and added to). If not filled in, a temporary directory is created and used.
The app allows all downloaded data to be saved. If used, data is saved in one file, and is stored as a named (by API call function)
list of data.tables. Options to control this behavior are
AV dump Directory: A directory where individual API requests can be cached. Data is saved in one file as a named
(by API call function) list of data.tables.
Capture AV Data: Save Price data, non-price data, all or none.
Update or Cumulative: If update is selected, data is keyed relevantly, so for example there will only be one set of dividend data stored.
If cumulative then all API data (including a timestamp) is saved sequentially. The latter will lead to much larger files.
Other options:
CleanOnStart : cleans out the cache file every time the app is started.
SaveEveryAVCall : Saves cache file after every call.
SaveNow : Save cache file when this is selected.
Nothing
## Not run: av_runShiny() ## End(Not run)## Not run: av_runShiny() ## End(Not run)
Prints internal data state of av_runShiny()
dump_the(typegrep="*")
dump_inv()
dump_assetgroups()
dump_captured()
dump_the(typegrep = "*") dump_inv() dump_assetgroups(returngt = TRUE) dump_captured(todo = "byfunction")dump_the(typegrep = "*") dump_inv() dump_assetgroups(returngt = TRUE) dump_captured(todo = "byfunction")
typegrep |
: Grep string for internal state parameters |
returngt |
: Return GT table |
todo |
: One of c("byfunction","pxhist",any av function name) |
data.table with desired data.
## Not run: `dump_the()` `dump_inv()` `dump_assetgroups(returngt=TRUE)` `dump_captured(todo="byfunction")` ## End(Not run)## Not run: `dump_the()` `dump_inv()` `dump_assetgroups(returngt=TRUE)` `dump_captured(todo="byfunction")` ## End(Not run)
Adds default elements to gt() table
gt.basetheme( x, gtopts = "all", sizepct = 100, style = 4, digits = 2, seps = FALSE, na_format = "-", size = "", interactive = FALSE )gt.basetheme( x, gtopts = "all", sizepct = 100, style = 4, digits = 2, seps = FALSE, na_format = "-", size = "", interactive = FALSE )
x |
Input data or |
gtopts |
Which elements to add |
sizepct |
(default: 70) How big to make tables |
style |
(default: 4) Style number (see |
digits |
(default: 2) Number formatting |
seps |
(default: FALSE) Number formatting thousands separators |
na_format |
(default: "-") WHat to show for NAs |
size |
(default: "") Size of text, either |
interactive |
(default: |
Prints message if condition met
message_if(reallydothis, ...)message_if(reallydothis, ...)
reallydothis |
Condition to be met |
... |
Additional items to be passed to |
Other utititlies internal to this package