Title: | Quantitative Financial Modelling Framework |
---|---|
Description: | Specify, build, trade, and analyse quantitative financial trading strategies. |
Authors: | Jeffrey A. Ryan [aut, cph], Joshua M. Ulrich [cre, aut], Ethan B. Smith [ctb], Wouter Thielen [ctb], Paul Teetor [ctb], Steve Bronder [ctb] |
Maintainer: | Joshua M. Ulrich <[email protected]> |
License: | GPL-3 |
Version: | 0.4.26.1 |
Built: | 2024-11-05 17:20:52 UTC |
Source: | https://github.com/joshuaulrich/quantmod |
Quantitative Financial Modelling and Trading Framework for R
The quantmod package for R is designed to assist the quantitative trader in the development, testing, and deployment of statistically based trading models.
What quantmod IS
A rapid prototyping environment, with comprehensive tools for data management and visualization. where quant traders can quickly and cleanly explore and build trading models.
What quantmod is NOT
A replacement for anything statistical. It has no 'new' modelling routines or analysis tool to speak of. It does now offer charting not currently available elsewhere in R, but most everything else is more of a wrapper to what you already know and love about the langauge and packages you currently use.
quantmod makes modelling easier by removing the repetitive workflow issues surrounding data management, modelling interfaces, and performance analysis.
Jeffrey A. Ryan
Maintainer: Joshua M. Ulrich <[email protected]>
Add Directional Movement Index
addADX(n = 14, maType="EMA", wilder=TRUE)
addADX(n = 14, maType="EMA", wilder=TRUE)
n |
periods to use for DX calculation |
maType |
moving average type |
wilder |
should Welles Wilder EMA be used? |
See 'ADX' in TTR for specific details and references.
An ADX indicator will be draw in a new window on the current chart. A chobTA object will be returned silently.
Jeffrey A. Ryan
see ADX in TTR written by Josh Ulrich
## Not run: addADX() ## End(Not run)
## Not run: addADX() ## End(Not run)
Add Bollinger Bands to current chart.
addBBands(n = 20, sd = 2, maType = "SMA", draw = 'bands', on = -1)
addBBands(n = 20, sd = 2, maType = "SMA", draw = 'bands', on = -1)
n |
number of moving average periods |
maType |
type of moving average to be used |
sd |
number of standard deviations |
draw |
indicator to draw: bands, percent, or width |
on |
which figure area of chart to apply to |
The primary addition to this function call over the TTR
version is in the draw
argument. ‘bands’ will draw
standard Bollinger Bands, ‘percent’ will draw Bollinger %b
and ‘width’ will draw Bolinger Bands Width. The last two will
be drawn in new figure regions.
See bollingerBands in TTR for specific details as to implementation and references.
Bollinger Bands will be drawn, or scheduled to be drawn,
on the current chart. If draw
is either percent or width
a new figure will be added to the current TA figures charted.
A chobTA object will be returned silently.
Jeffrey A. Ryan
See bollingerBands in TTR written by Josh Ulrich
## Not run: addBBands() ## End(Not run)
## Not run: addBBands() ## End(Not run)
Add Commodity Channel Index
addCCI(n = 20, maType="SMA", c=0.015)
addCCI(n = 20, maType="SMA", c=0.015)
n |
periods to use for DX calculation |
maType |
moving average type |
c |
Constant to apply to the mean deviation. |
See 'CCI' in TTR for specific details and references.
An CCI indicator will be draw in a new window on the current chart. A chobTA object will be returned silently.
Jeffrey A. Ryan
see CCI in TTR written by Josh Ulrich
## Not run: addCCI() ## End(Not run)
## Not run: addCCI() ## End(Not run)
Apply options or futures expiration vertical bars to current chart.
addExpiry(type = "options", lty = "dotted")
addExpiry(type = "options", lty = "dotted")
type |
options or futures expiration |
lty |
type of lines to draw |
See options.expiry and futures.expiry in quantmod for details and limitations.
Expiration lines will be drawn at appropriate dates. A chibTA object will be returned silently.
Jeffrey A. Ryan
## Not run: addExpiry() ## End(Not run)
## Not run: addExpiry() ## End(Not run)
Add one or more moving averages to a chart.
addSMA(n = 10, on = 1, with.col = Cl, overlay = TRUE, col = "brown") addEMA(n = 10, wilder = FALSE, ratio=NULL, on = 1, with.col = Cl, overlay = TRUE, col = "blue") addWMA(n = 10, wts=1:n, on = 1, with.col = Cl, overlay = TRUE, col = "green") addDEMA(n = 10, on = 1, with.col = Cl, overlay = TRUE, col = "pink") addEVWMA(n = 10, on = 1, with.col = Cl, overlay = TRUE, col = "yellow") addZLEMA(n = 10, ratio=NULL, on = 1, with.col = Cl, overlay = TRUE, col = "red")
addSMA(n = 10, on = 1, with.col = Cl, overlay = TRUE, col = "brown") addEMA(n = 10, wilder = FALSE, ratio=NULL, on = 1, with.col = Cl, overlay = TRUE, col = "blue") addWMA(n = 10, wts=1:n, on = 1, with.col = Cl, overlay = TRUE, col = "green") addDEMA(n = 10, on = 1, with.col = Cl, overlay = TRUE, col = "pink") addEVWMA(n = 10, on = 1, with.col = Cl, overlay = TRUE, col = "yellow") addZLEMA(n = 10, ratio=NULL, on = 1, with.col = Cl, overlay = TRUE, col = "red")
n |
periods to average over |
wilder |
logical; use wilder? |
wts |
a vector of weights |
ratio |
a smoothing/decay ratio |
on |
apply to which figure (see below) |
with.col |
using which column of data (see below) |
overlay |
draw as overlay |
col |
color of MA |
see the appropriate base MA functions in TTR for more details and references.
A moving average indicator will be draw on the current chart. A chobTA object will be returned silently.
Jeffrey A. Ryan
see MovingAverages in TTR written by Josh Ulrich
## Not run: addSMA() addEMA() addWMA() addDEMA() addEVWMA() addZLEMA() ## End(Not run)
## Not run: addSMA() addEMA() addWMA() addDEMA() addEVWMA() addZLEMA() ## End(Not run)
Add Moving Average Convergence Divergence indicator to chart.
addMACD(fast = 12, slow = 26, signal = 9, type = "EMA", histogram = TRUE, col)
addMACD(fast = 12, slow = 26, signal = 9, type = "EMA", histogram = TRUE, col)
fast |
fast period |
slow |
slow period |
signal |
signal period |
type |
type of MA to use. Single values will be replicated |
histogram |
include histogram |
col |
colors to use for lines (optional) |
See and 'MACD' in TTR for specific details and implementation references.
A MACD indicator will be draw in a new window on the current chart. A chobTA object will be returned silently.
Jeffrey A. Ryan
see MACD in TTR written by Josh Ulrich
## Not run: addMACD() ## End(Not run)
## Not run: addMACD() ## End(Not run)
Add Rate Of Change indicator to chart.
addROC(n = 1, type = c("discrete", "continuous"), col = "red")
addROC(n = 1, type = c("discrete", "continuous"), col = "red")
n |
periods |
type |
compounding type |
col |
line color (optional) |
See 'ROC' in TTR for specific details and references.
A ROC indicator will be draw in a new window on the current chart. A chobTA object will be returned silently.
Jeffrey A. Ryan
see ROC in TTR written by Josh Ulrich
## Not run: addROC() ## End(Not run)
## Not run: addROC() ## End(Not run)
Add a Relative Strength Index indicator to chart.
addRSI(n = 14, maType = "EMA", wilder = TRUE)
addRSI(n = 14, maType = "EMA", wilder = TRUE)
n |
periods |
maType |
type of MA to use |
wilder |
use wilder (see EMA) |
see 'RSI' in TTR for specific details and references.
An RSI indicator will be draw in a new window on the current chart. A chobTA object will be returned silently.
Jeffrey A. Ryan
see RSI in TTR written by Josh Ulrich
## Not run: addRSI() ## End(Not run)
## Not run: addRSI() ## End(Not run)
Add Parabolic Stop and Reversal indicator overlay to chart.
addSAR(accel = c(0.02, 0.2), col = "blue")
addSAR(accel = c(0.02, 0.2), col = "blue")
accel |
Accelleration factors - see SAR |
col |
color of points (optional) |
see 'SAR' in TTR for specific details and references.
A SAR overlay will be drawn on the current chart. A chobTA object will be returned silently.
Jeffrey A. Ryan
see SAR in TTR written by Josh Ulrich
## Not run: addSAR() ## End(Not run)
## Not run: addSAR() ## End(Not run)
Add Stochastic Momentum Indicator to chart.
addSMI(n=13,slow=25,fast=2,signal=9,ma.type="EMA")
addSMI(n=13,slow=25,fast=2,signal=9,ma.type="EMA")
n |
periods |
slow |
slow |
fast |
fast |
signal |
signal |
ma.type |
MA tyep to use, recycled as necessary |
see 'SMI in TTR for specifics and references.
An SMI indicator will be draw in a new window on the current chart. A chobTA object will be returned silently.
Jeffrey A. Ryan
see SMI in TTR written by Josh Ulrich
## Not run: addSMI() ## End(Not run)
## Not run: addSMI() ## End(Not run)
Add Volume of a series, if available, to the current chart. This is the default TA argument for all charting functions.
addVo(log.scale=FALSE)
addVo(log.scale=FALSE)
log.scale |
use log-scale for volume |
Add volume bars to current chart if data object contains appropriate volume column.
log.scale will transform the series via standard R graphics mechanisms.
Volume will be draw in a new window on the current chart. A chobTA object will be returned silently.
Jeffrey A. Ryan
## Not run: addVo() ## End(Not run)
## Not run: addVo() ## End(Not run)
Add William's percent R indiator to the current chart.
addWPR(n = 14)
addWPR(n = 14)
n |
periods |
see 'WPR' in TTR for details and references.
A William's percent R indicator will be draw in a new window on the current chart. A chobTA object will be returned silently.
Jeffrey A. Ryan
see 'WPR' in TTR written by Josh Ulrich
## Not run: addWPR() ## End(Not run)
## Not run: addWPR() ## End(Not run)
Adjust all columns of an OHLC object for split and dividend.
adjustOHLC(x, adjust = c("split","dividend"), use.Adjusted = FALSE, ratio = NULL, symbol.name=deparse(substitute(x)))
adjustOHLC(x, adjust = c("split","dividend"), use.Adjusted = FALSE, ratio = NULL, symbol.name=deparse(substitute(x)))
x |
An OHLC object |
adjust |
adjust by split, dividend, or both (default) |
use.Adjusted |
use the ‘Adjusted’ column in Yahoo! data to adjust |
ratio |
ratio to adjust with, bypassing internal calculations |
symbol.name |
used if x is not named the same as the symbol adjusting |
This function calculates the adjusted Open, High, Low, and Close prices according to split and dividend information.
There are three methods available to calculate the new OHLC object prices.
By default, getSplits
and getDividends
are
called to retrieve the respective information. These
may dispatch to custom methods following the “.”
methodology used by quantmod dispatch. See getSymbols
for information related to extending quantmod.
This information is passed to
adjRatios
from the TTR package, and
the resulting ratio calculations are used to adjust
to observed historical prices.
This is the most precise way to adjust a series.
The second method works only on standard Yahoo! data containing an explicit Adjusted column.
A final method allows for one to pass
a ratio
into the function directly.
All methods proceed as follows:
New columns are derived by taking the ratio of adjusted value to original Close, and multiplying by the difference of the respective column and the original Close. This is then added to the modified Close column to arrive at the remaining ‘adjusted’ Open, High, Low column values.
If no adjustment is needed, the function returns the original data unaltered.
An object of the original class, with prices adjusted for splits and dividends.
Using use.Adjusted = TRUE
will be less precise
than the method that employs actual split
and dividend information. This is due to
loss of precision from Yahoo! using
Adjusted columns of only two decimal places.
The advantage is that this can be run offline,
and for short series or those with few adjustments
the loss of precision will be small.
The resulting precision loss will be from row observation to row observation, as the calculation will be exact for intraday values.
Jeffrey A. Ryan
Yahoo Finance https://finance.yahoo.com
getSymbols.yahoo
getSplits
getDividends
## Not run: getSymbols("AAPL", from="1990-01-01", src="yahoo") head(AAPL) head(AAPL.a <- adjustOHLC(AAPL)) head(AAPL.uA <- adjustOHLC(AAPL, use.Adjusted=TRUE)) # intraday adjustments are precise across all methods # an example with Open to Close (OpCl) head(cbind(OpCl(AAPL),OpCl(AAPL.a),OpCl(AAPL.uA))) # Close to Close changes may lose precision head(cbind(ClCl(AAPL),ClCl(AAPL.a),ClCl(AAPL.uA))) ## End(Not run)
## Not run: getSymbols("AAPL", from="1990-01-01", src="yahoo") head(AAPL) head(AAPL.a <- adjustOHLC(AAPL)) head(AAPL.uA <- adjustOHLC(AAPL, use.Adjusted=TRUE)) # intraday adjustments are precise across all methods # an example with Open to Close (OpCl) head(cbind(OpCl(AAPL),OpCl(AAPL.a),OpCl(AAPL.uA))) # Close to Close changes may lose precision head(cbind(ClCl(AAPL),ClCl(AAPL.a),ClCl(AAPL.uA))) ## End(Not run)
Attach a demand database (lazy load) as a new environment.
attachSymbols(DB = DDB_Yahoo(), pos = 2, prefix = NULL, postfix = NULL, mem.cache = TRUE, file.cache = !mem.cache, cache.dir = tempdir()) flushSymbols(DB = DDB_Yahoo())
attachSymbols(DB = DDB_Yahoo(), pos = 2, prefix = NULL, postfix = NULL, mem.cache = TRUE, file.cache = !mem.cache, cache.dir = tempdir()) flushSymbols(DB = DDB_Yahoo())
DB |
A |
pos |
position in search path to attach DB |
prefix |
character to prefix all symbols with |
postfix |
character to postfix all symbols with |
mem.cache |
should objects be cached in memory |
file.cache |
should objects be cached in on disk |
cache.dir |
directory to use for |
An experimental function to allow access to remote objects without requiring explicit calls to a loading function.
attachSymbols
requires a DDB
object
to define where the data is to come from, as well as what symbols are
loaded on-demand.
attachSymbols calls the method referred to
by the DDB
object. In the default case this is
DDB_Yahoo
. See this function for specific details
about the Yahoo implementation.
The individual methods make use of getSymbols
to
load the data. This requires a corresponding
getSymbols method.
Internally, attachSymbols makes use of quantmod's unexported create.bindings to dynamically create active bindings to each symbol listed in the DDB object.
In turn, create.bindings uses one of two R methods to create the binding to the names required. This depends on the cache method requested.
Immediately after a call to attachSymbols, a new environment is attached that contains the names of objects yet to be loaded. This is similar to the lazy-load mechanism in R, though extended to be both more general and easier to use.
It is important to note that no data is loaded at this stage.
What occurs instead is that these symbols now have active bindings
using either delayedAssign
(mem.cache) or
makeActiveBinding
(file.cache).
During all future requests for the object(s) in question,
the binding will be used to determine how this data is
loaded into R. mem.cache
will simply load the
data from its corresponding source (as defined by the DDB object)
and leave it in the environment specified in the original call.
The effect of this is to allow lazy-loading of data from
a variety of external sources (Yahoo in the default case).
Once loaded, these are cached in R's memory. Nothing further
differentiates these from standard variables. This also means
that the environment will grow as more symbols are loaded.
If the file.cache
option is set, the data is loaded from
its source the first time the symbol is referenced. The difference
is that the data is then written to a temporary file and maintained
there. Data is loaded and subsequently removed upon each
request for the object. See makeActiveBinding
for details
of how this occurs at the R level.
A primary advantage of using the file.cache option is the ability to maintain hundreds or thousands of objects in your current session without using memory, or explicitly loading and removing. The main downside of this approach is the that data must be loaded from disk each time, with the corresponding (if generally negligible) overhead of file access.
This function is new, and all aspects may change in the near future.
Jeffrey A. Ryan
Luke's stuff and Mark Brevington and Roger Peng
delayedAssign
, makeActiveBinding
## Not run: attachSymbols() SBUX QQQ ls() ## End(Not run)
## Not run: attachSymbols() SBUX QQQ ls() ## End(Not run)
Create one data object from multiple sources, applying transformations via standard R formula mechanism.
buildData(formula, na.rm = TRUE, return.class = "zoo")
buildData(formula, na.rm = TRUE, return.class = "zoo")
formula |
an object of class |
na.rm |
drop rows with missing values? |
return.class |
one of "zoo","data.frame","ts","timeSeries" |
Makes available for use outside the quantmod workflow a dataset
of appropriately transformed variables, using the same mechanism
underlying specifyModel
. Offers the ability to apply transformations
to raw data using a common formula mechanism, without having to explicitly
merge different data objects.
Interally calls specifyModel
followed by modelData
, with the
returned object being coerced to the desired 'return.class' if possible,
otherwise returns a zoo
object.
See getSymbols
and specifyModel
for more information
regarding proper usage.
An object of class return.class
.
Jeffrey A. Ryan
getSymbols
, specifyModel
,
modelData
## Not run: buildData(Next(OpCl(DIA)) ~ Lag(TBILL) + I(Lag(OpHi(DIA))^2)) buildData(Next(OpCl(DIA)) ~ Lag(TBILL), na.rm=FALSE) buildData(Next(OpCl(DIA)) ~ Lag(TBILL), na.rm=FALSE, return.class="ts") ## End(Not run)
## Not run: buildData(Next(OpCl(DIA)) ~ Lag(TBILL) + I(Lag(OpHi(DIA))^2)) buildData(Next(OpCl(DIA)) ~ Lag(TBILL), na.rm=FALSE) buildData(Next(OpCl(DIA)) ~ Lag(TBILL), na.rm=FALSE, return.class="ts") ## End(Not run)
Construct and attach a fitted model of type method
to quantmod
object.
buildModel(x, method, training.per, ...)
buildModel(x, method, training.per, ...)
x |
An object of class |
training.per |
character vector representing dates in ISO 8601 format “CCYY-MM-DD” or “CCYY-MM-DD HH:MM:SS” of length 2 |
method |
A character string naming the fitting method. See details section for available methods, and how to create new methods. |
... |
Additional arguments to method call |
Currently available methods include:
lm, glm, loess, step, ppr, rpart[rpart], tree[tree], randomForest[randomForest], mars[mda], polymars[polspline], lars[lars], rq[quantreg], lqs[MASS], rlm[MASS], svm[e1071], and nnet[nnet].
The training.per
should match the undelying date
format of the time-series data used in modelling. Any other style
may not return what you expect.
Additional methods wrappers can be created to allow for modelling
using custom functions. The only requirements are for a wrapper
function to be constructed taking parameters quantmod
,
training.data
, and .... The function must return the
fitted model object and have a predict method available.
It is possible to add predict methods if non exist by
adding an S3 method for predictModel. The
buildModel.skeleton
function can be used for new methods.
An object of class quantmod
with fitted model attached
See buildModel.skeleton
for information on adding additional methods
Jeffrey Ryan
## Not run: getSymbols('QQQ',src='yahoo') q.model = specifyModel(Next(OpCl(QQQ)) ~ Lag(OpHi(QQQ),0:3)) buildModel(q.model,method='lm',training.per=c('2006-08-01','2006-09-30')) ## End(Not run)
## Not run: getSymbols('QQQ',src='yahoo') q.model = specifyModel(Next(OpCl(QQQ)) ~ Lag(OpHi(QQQ),0:3)) buildModel(q.model,method='lm',training.per=c('2006-08-01','2006-09-30')) ## End(Not run)
These are experimental functions for a new version of chartSeries in quantmod. Interface, behavior, and functionality will change.
chart_Series(x, name = NULL, type = "candlesticks", subset = "", TA = "", pars = chart_pars(), theme = chart_theme(), clev = 0, ...)
chart_Series(x, name = NULL, type = "candlesticks", subset = "", TA = "", pars = chart_pars(), theme = chart_theme(), clev = 0, ...)
x |
time series object |
name |
name for chart |
type |
one of: |
subset |
an ISO8601 style character string indicating date range |
TA |
a character string of semi-colon seperated TA calls. |
pars |
chart parameters |
theme |
chart theme |
clev |
color level (experimental). Indicates the degree of brightness 0 is darkest color. |
... |
additional parameters |
These functions, when complete, will revert back to the original chartSeries naming convention.
Called for graphical side effects.
Highly experimental (read: alpha) use with caution.
Jeffrey A. Ryan
Charting tool to create standard financial charts given a time series like object. Serves as the base function for future technical analysis additions. Possible chart styles include candles, matches (1 pixel candles), bars, and lines. Chart may have white or black background.
reChart
allows for dynamic changes to the chart without
having to respecify the full chart parameters.
chartSeries(x, type = c("auto", "candlesticks", "matchsticks", "bars","line"), subset = NULL, show.grid = TRUE, name = NULL, time.scale = NULL, log.scale = FALSE, TA = 'addVo()', TAsep=';', line.type = "l", bar.type = "ohlc", theme = chartTheme("black"), layout = NA, major.ticks='auto', minor.ticks=TRUE, yrange=NULL, plot=TRUE, up.col,dn.col,color.vol = TRUE, multi.col = FALSE, ...) reChart(type = c("auto", "candlesticks", "matchsticks", "bars","line"), subset = NULL, show.grid = TRUE, name = NULL, time.scale = NULL, line.type = "l", bar.type = "ohlc", theme = chartTheme("black"), major.ticks='auto', minor.ticks=TRUE, yrange=NULL, up.col,dn.col,color.vol = TRUE, multi.col = FALSE, ...)
chartSeries(x, type = c("auto", "candlesticks", "matchsticks", "bars","line"), subset = NULL, show.grid = TRUE, name = NULL, time.scale = NULL, log.scale = FALSE, TA = 'addVo()', TAsep=';', line.type = "l", bar.type = "ohlc", theme = chartTheme("black"), layout = NA, major.ticks='auto', minor.ticks=TRUE, yrange=NULL, plot=TRUE, up.col,dn.col,color.vol = TRUE, multi.col = FALSE, ...) reChart(type = c("auto", "candlesticks", "matchsticks", "bars","line"), subset = NULL, show.grid = TRUE, name = NULL, time.scale = NULL, line.type = "l", bar.type = "ohlc", theme = chartTheme("black"), major.ticks='auto', minor.ticks=TRUE, yrange=NULL, up.col,dn.col,color.vol = TRUE, multi.col = FALSE, ...)
x |
an OHLC object - see details |
type |
style of chart to draw |
subset |
xts style date subsetting argument |
show.grid |
display price grid lines? |
name |
name of chart |
time.scale |
what is the timescale? automatically deduced (broken) |
log.scale |
should the y-axis be log-scaled? |
TA |
a vector of technical indicators and params, or character strings |
TAsep |
TA delimiter for TA strings |
line.type |
type of line in line chart |
bar.type |
type of barchart - ohlc or hlc |
theme |
a chart.theme object |
layout |
if |
major.ticks |
where should major ticks be drawn |
minor.ticks |
should minor ticks be draw? |
yrange |
override y-scale |
plot |
should plot be drawn |
up.col |
up bar/candle color |
dn.col |
down bar/candle color |
color.vol |
color code volume? |
multi.col |
4 color candle pattern |
... |
additional parameters |
Currently displays standard style OHLC charts familiar in financial applications, or line charts when not passes OHLC data. Works with objects having explicit time-series properties.
Line charts are created with close data, or from single column time series.
The subset
argument can be used to specify a
particular area of the series to view. The underlying
series is left intact to allow for TA functions to
use the full data set. Additionally, it is possible
to use syntax borrowed from the first
and last
functions, e.g. ‘last 4 months’.
TA
allows for the inclusion of a variety of
chart overlays and tecnical indicators. A full list is
available from addTA
. The default TA argument is
addVo()
- which adds volume, if available, to the
chart being drawn.
theme
requires an object of class chart.theme
, created
by a call to chartTheme
. This function can be used to modify the
look of the resulting chart. See chart.theme
for details.
line.type
and bar.type
allow further fine tuning of
chart styles to user tastes.
multi.col
implements a color coding scheme used in some
charting applications, and follows the following rules:
grey => Op[t] < Cl[t] and Op[t] < Cl[t-1]
white => Op[t] < Cl[t] and Op[t] > Cl[t-1]
red => Op[t] > Cl[t] and Op[t] < Cl[t-1]
black => Op[t] > Cl[t] and Op[t] > Cl[t-1]
reChart
takes any number of arguments from the original
chart call — and redraws the chart with the updated parameters.
One item of note: if multiple color bars/candles are desired,
it is necessary to respecify the theme
argument. Additionally
it is not possible to change TA parameters at present. This must be
done with addTA/dropTA/swapTA/moveTA commands.
Returns a standard chart plus volume, if available, suitably scaled.
If plot=FALSE
a chob object will be returned.
Most details can be fine-tuned within the function, though the code does a reasonable job of scaling and labelling axes for the user.
The current implementation maintains a record of actions carried
out for any particular chart. This is used to recreate the original when
adding new indicator. A list of applied TA actions is available with a call
to listTA
. This list can be assigned to a variable and used in new
chart calls to recreate a set of technical indicators. It is also possible
to force all future charts to use the same indicators by calling setTA
.
Additional motivation to add outlined candles to allow for scaling and advanced color coding is owed to Josh Ulrich, as are the base functions (from TTR) for the yet to be released technical analysis charting code.
Many improvements in the current version were the result of conversations with Gabor Grothendieck. Many thanks to him.
Jeffrey A. Ryan
Josh Ulrich - TTR package and multi.col coding
getSymbols
, addTA
, setTA
,
chartTheme
## Not run: getSymbols("YHOO") chartSeries(YHOO) chartSeries(YHOO, subset='last 4 months') chartSeries(YHOO, subset='2007::2008-01') chartSeries(YHOO,theme=chartTheme('white')) chartSeries(YHOO,TA=NULL) #no volume chartSeries(YHOO,TA=c(addVo(),addBBands())) #add volume and Bollinger Bands from TTR addMACD() # add MACD indicator to current chart setTA() chartSeries(YHOO) #draws chart again, this time will all indicators present ## End(Not run)
## Not run: getSymbols("YHOO") chartSeries(YHOO) chartSeries(YHOO, subset='last 4 months') chartSeries(YHOO, subset='2007::2008-01') chartSeries(YHOO,theme=chartTheme('white')) chartSeries(YHOO,TA=NULL) #no volume chartSeries(YHOO,TA=c(addVo(),addBBands())) #add volume and Bollinger Bands from TTR addMACD() # add MACD indicator to current chart setTA() chartSeries(YHOO) #draws chart again, this time will all indicators present ## End(Not run)
Create a chart.theme object for use within chartSeries to manage desired chart colors.
chartTheme(theme = "black", ...)
chartTheme(theme = "black", ...)
theme |
name of base theme |
... |
name=value pairs to modify |
Used as an argument to the chartSeries family of functions,
chartTheme
allows for on-the-fly modification
of pre-specified chart ‘themes’. Users can modify
a pre-built theme in-place, or copy the theme to a new
variable for use in subsequent charting calls.
Internally a chart.theme object is nothing more than a list of values organized by chart components. The primary purpose of this is to facilitate minor modification on the fly, as well as provide a template for larger changes.
Setting style arguments for TA calls via chartTheme requires the user to pass the styles as name=value pairs with a name containing the TA call in question. See examples for assistance.
Current components that may be modified with appropriate values:
fg.col
: foreground color
bg.col
: background color
grid.col
: grid color
border
: border color
minor.tick
: minor tickmark color
major.tick
: major tickmark color
up.col
: up bar/candle color
dn.col
: down bar/candle color
up.up.col
: up after up bar/candle color
up.dn.col
: up after down bar/candle color
dn.dn.col
: down after down bar/candle color
dn.up.col
: down after up bar/candle color
up.border
: up bar/candle border color
dn.border
: down bar/candle border color
up.up.border
: up after up bar/candle border color
up.dn.border
: up after down bar/candle border color
dn.dn.border
: down after down bar/candle border color
dn.up.border
: down after up bar/candle border color
A chart.theme object
Jeffrey A. Ryan
chartTheme() chartTheme('white') chartTheme('white',up.col='blue',dn.col='red') # A TA example chartTheme(addRSI.col='red') str(chartTheme())
chartTheme() chartTheme('white') chartTheme('white',up.col='blue',dn.col='red') # A TA example chartTheme(addRSI.col='red') str(chartTheme())
Internal Objects for Tracking and Plotting Chart Changes
Objects are created internally through the charting
functions chartSeries
, barChart
, lineChart
, and
candleChart
.
device
:Object of class "ANY"
~~
call
:Object of class "call"
~~
xdata
:Object of class "ANY"
~~
xsubset
:Object of class "ANY"
~~
name
:Object of class "character"
~~
type
:Object of class "character"
~~
passed.args
:Object of class "ANY"
~~
windows
:Object of class "numeric"
~~
xrange
:Object of class "numeric"
~~
yrange
:Object of class "numeric"
~~
log.scale
:Object of class "logical"
~~
length
:Object of class "numeric"
~~
color.vol
:Object of class "logical"
~~
multi.col
:Object of class "logical"
~~
show.vol
:Object of class "logical"
~~
show.grid
:Object of class "logical"
~~
line.type
:Object of class "character"
~~
bar.type
:Object of class "character"
~~
xlab
:Object of class "character"
~~
ylab
:Object of class "character"
~~
spacing
:Object of class "numeric"
~~
width
:Object of class "numeric"
~~
bp
:Object of class "numeric"
~~
x.labels
:Object of class "character"
~~
colors
:Object of class "ANY"
~~
layout
:Object of class "ANY"
~~
time.scale
:Object of class "ANY"
~~
major.ticks
:Object of class "ANY"
~~
minor.ticks
:Object of class "logical"
~~
No methods defined with class "chob" in the signature.
Jeffrey A. Ryan
chartSeries
,
or chobTA
for links to other classes
showClass("chob")
showClass("chob")
Internal storage class for handling arbitrary TA objects
Objects of class chobTA
are created and returned invisibly
through calls to addTA-style functions.
call
:Object of class "call"
~~
on
:Object of class "ANY"
~~
new
:Object of class "logical"
~~
TA.values
:Object of class "ANY"
~~
name
:Object of class "character"
~~
params
:Object of class "ANY"
~~
signature(object = "chobTA")
: ...
It is of no external vaule to handle chobTA objects directly
Jeffrey A. Ryan
addTA
, ~~~
or chob
for links to other classes
showClass("chobTA")
showClass("chobTA")
Internal function used in attachSymbols
to create active bindings for symbols defined in a DDB
object.
create.binding(s, lsym, rsym, gsrc, mem.cache = TRUE, file.cache = !mem.cache, cache.dir = tempdir(), envir,...)
create.binding(s, lsym, rsym, gsrc, mem.cache = TRUE, file.cache = !mem.cache, cache.dir = tempdir(), envir,...)
s |
symbol name |
lsym |
function to convert to local name (legal R name) |
rsym |
function to convert to remote name (source name) |
gsrc |
corresponds to 'src' arg in getSymbols call |
mem.cache |
cache to memory |
file.cache |
cache to disk |
cache.dir |
directory to cache to/from |
envir |
environment name (character) |
... |
arguments to pass to getSymbols call |
Low level function to create bindings during initial demand-database construction.
Called for its side effect of creating active bindings to symbols.
This is code used internally by attachSymbols. User's may modify this to accomodate different systems. The upstream functions needn't maintain consistency with this interface.
Use as a guide or template.
Jeffrey A. Ryan
Mark, Roger, ?
Use globally specified defaults, if set, in place of formally specified default argument values. Allows user to specify function defaults different than formally supplied values, e.g. to change poorly performing defaults, or satisfy a different preference.
setDefaults(name, ...) unsetDefaults(name, confirm = TRUE) getDefaults(name = NULL, arg = NULL) importDefaults(calling.fun)
setDefaults(name, ...) unsetDefaults(name, confirm = TRUE) getDefaults(name = NULL, arg = NULL) importDefaults(calling.fun)
name |
name of function, quoted or unquoted (see Details) |
... |
name=value default pairs |
confirm |
prompt before unsetting defaults |
arg |
values to retrieve |
calling.fun |
name of function to act upon |
Provides a wrapper to R options
that allows the user to
specify any name=value pair for a function's formal arguments.
Only formal name=value pairs specified will be updated.
Values do not have to be respecified in subsequent calls to
setDefaults
, so it is possible to add new defaults for each
function one at a time, without having to retype all previous values.
Assigning NULL
to any argument will remove the argument from
the defaults list.
name
can be an unquoted, bare symbol only at the top-level. It
must be a quoted character string if you call setDefaults
inside
a function.
Removes name=value pairs from the defaults list.
Provides access to the stored user defaults. Single arguments need not be quoted, multiple arguments must be in a character vector.
A call to importDefaults
should be placed on the first line
in the body of the function. It checks the user's environment for
globally specified default values for the called function. These
defaults can be specified by the user with a call to
setDefaults
, and will override any default formal
parameters, in effect replacing the original defaults with user
supplied values instead. Any user-specified values in the parent
function (that is, the function containing importDefaults
)
will override the values set in the global default environment.
setDefaults |
None. Used for it's side effect of setting a list of default arguments by function. |
unsetDefaults |
None. Used for it's side effect of unsetting default arguments by function. |
getDefaults |
A named list of defaults and associated values, similar to
This does not imply that the returned function names are able
to accept defaults (via |
importDefaults |
None. Used for its side-effect of loading all non- |
At present it is not possible to specify NULL
as a replacement
for a non-NULL
default, as the process interprets NULL
values as being not set, and will simply use the value specified
formally in the function. If NULL
is what is desired, it is
necessary to include this in the function call itself.
Any arguments included in the actual function call will take
precedence over setDefaults
values, as well as the standard
formal function values. This conforms to the current user
experience in R.
Like options
, default settings are not kept across
sessions. Currently, it is not possible to pass values for
... arguments, only formally specified arguments in the original
function definition.
unsetDefaults
removes the all entries from the
options
lists for the specified function. To remove single
function default values simply set the name of the argument to
NULL
in setDefaults
.
When a function implements importDefaults
, non-named
arguments may be ignored if a global default has been set
(i.e. not NULL
). If this is the case, simply name the
arguments in the calling function.
This should also work for functions retrieving formal
parameter values from options
, as it assigns a value to the
parameter in a way that looks like it was passed in the function
call. So any check on options
would presumably disregard
importDefaults
values if an argument was passed to the
function.
Jeffrey A. Ryan
my.fun <- function(x=3) { importDefaults('my.fun') x^2 } my.fun() # returns 9 setDefaults(my.fun, x=10) my.fun() # returns 100 my.fun(x=4) # returns 16 getDefaults(my.fun) formals(my.fun) unsetDefaults(my.fun, confirm=FALSE) getDefaults(my.fun) my.fun() # returns 9
my.fun <- function(x=3) { importDefaults('my.fun') x^2 } my.fun() # returns 9 setDefaults(my.fun, x=10) my.fun() # returns 100 my.fun(x=4) # returns 16 getDefaults(my.fun) formals(my.fun) unsetDefaults(my.fun, confirm=FALSE) getDefaults(my.fun) my.fun() # returns 9
Calculate the k-period percent difference within one series, or between two series. Primarily used to calculate the percent change from one period to another of a given series, or to calculate the percent difference between two series over the full series.
Delt(x1, x2 = NULL, k = 0, type = c("arithmetic", "log"))
Delt(x1, x2 = NULL, k = 0, type = c("arithmetic", "log"))
x1 |
m x 1 vector |
x2 |
m x 1 vector |
k |
change over |
type |
type of difference. log or arithmetic (default). |
When called with only x1
, the one period percent change of the
series is returned by default. Internally this happens by copying
x1 to x2. A two period difference would be specified with k=2
.
If called with both x1
and x2
, the difference between
the two is returned. That is, k=0. A one period difference would be
specified by k=1
. k
may also be a vector to calculate
more than one period at a time. The results will then be an m x length(k)
Arithmetic differences are used by default: Lag = (x2(t) - x1(t-k))/x1(t-k)
Log differences are calculated: Lag = log(x2(t)/x1(t-k))
An matrix of length(x1)
rows and length(k)
columns.
Jeffrey A. Ryan
Stock.Open <- c(102.25,102.87,102.25,100.87,103.44,103.87,103.00) Stock.Close <- c(102.12,102.62,100.12,103.00,103.87,103.12,105.12) Delt(Stock.Open) #one period pct. price change Delt(Stock.Open,k=1) #same Delt(Stock.Open,type='arithmetic') #using arithmetic differences (default) Delt(Stock.Open,type='log') #using log differences Delt(Stock.Open,Stock.Close) #Open to Close pct. change Delt(Stock.Open,Stock.Close,k=0:2) #...for 0,1, and 2 periods
Stock.Open <- c(102.25,102.87,102.25,100.87,103.44,103.87,103.00) Stock.Close <- c(102.12,102.62,100.12,103.00,103.87,103.12,105.12) Delt(Stock.Open) #one period pct. price change Delt(Stock.Open,k=1) #same Delt(Stock.Open,type='arithmetic') #using arithmetic differences (default) Delt(Stock.Open,type='log') #using log differences Delt(Stock.Open,Stock.Close) #Open to Close pct. change Delt(Stock.Open,Stock.Close,k=0:2) #...for 0,1, and 2 periods
Functions to find the peaks (tops) and valleys (bottoms) of a given series.
findPeaks(x, thresh=0) findValleys(x, thresh=0)
findPeaks(x, thresh=0) findValleys(x, thresh=0)
x |
a time series or vector |
thresh |
minimum peak/valley threshold |
A vector of integers corresponding to peaks/valleys.
As a peak[valley] is defined as the highest[lowest] value in a series, the function can only define it after a change in direction has occurred. This means that the function will always return the first period after the peak/valley of the data, so as not to accidentally induce a look-ahead bias.
Jeffrey A. Ryan
findPeaks(sin(1:10)) p <- findPeaks(sin(seq(1,10,.1))) sin(seq(1,10,.1))[p] plot(sin(seq(1,10,.1))[p]) plot(sin(seq(1,10,.1)),type='l') points(p,sin(seq(1,10,.1))[p])
findPeaks(sin(1:10)) p <- findPeaks(sin(seq(1,10,.1))) sin(seq(1,10,.1))[p] plot(sin(seq(1,10,.1))[p]) plot(sin(seq(1,10,.1)),type='l') points(p,sin(seq(1,10,.1))[p])
Extract and replace fitted models from
quantmod
objects built with
buildModel
. All objects fitted
through methods specified in buildModel
calls can be extracted for further analysis.
fittedModel(object) ## S3 method for class 'quantmod' formula(x, ...) ## S3 method for class 'quantmod' plot(x, ...) ## S3 method for class 'quantmod' coefficients(object, ...) ## S3 method for class 'quantmod' coef(object, ...) ## S3 method for class 'quantmod' residuals(object, ...) ## S3 method for class 'quantmod' resid(object, ...) ## S3 method for class 'quantmod' fitted.values(object, ...) ## S3 method for class 'quantmod' fitted(object, ...) ## S3 method for class 'quantmod' anova(object, ...) ## S3 method for class 'quantmod' logLik(object, ...) ## S3 method for class 'quantmod' vcov(object, ...)
fittedModel(object) ## S3 method for class 'quantmod' formula(x, ...) ## S3 method for class 'quantmod' plot(x, ...) ## S3 method for class 'quantmod' coefficients(object, ...) ## S3 method for class 'quantmod' coef(object, ...) ## S3 method for class 'quantmod' residuals(object, ...) ## S3 method for class 'quantmod' resid(object, ...) ## S3 method for class 'quantmod' fitted.values(object, ...) ## S3 method for class 'quantmod' fitted(object, ...) ## S3 method for class 'quantmod' anova(object, ...) ## S3 method for class 'quantmod' logLik(object, ...) ## S3 method for class 'quantmod' vcov(object, ...)
object |
a |
x |
a suitable object |
... |
additional arguments |
Most often used to extract the final fitted object of the modelling process, usually for further analysis with tools outside the quantmod package.
Most common methods to apply to fitted objects
are available to the parent quantmod
object. At present, one can call directly the
following S3 methods on a built model as if
calling directly on the fitted object.
See *Usage* section.
It is also possible to add a fitted model to an object. This may be of value when applying heuristic rule sets for trading approaches, or when fine tuning already fit models by hand.
Returns an object matching that returned
by a call to the method specified in
buildModel
.
The replacement function fittedModel<-
is highly experimental, and may or may not
continue into further releases.
The fitted model added must use the
same names as appear in the quantmod
object's dataset.
Jeffrey A. Ryan
## Not run: x <- specifyModel(Next(OpCl(DIA)) ~ OpCl(VIX)) x.lm <- buildModel(x,method='lm',training.per=c('2001-01-01','2001-04-01')) fittedModel(x.lm) coef(fittedModel(x.lm)) coef(x.lm) # same vcov(fittedModel(x.lm)) vcov(x.lm) # same ## End(Not run)
## Not run: x <- specifyModel(Next(OpCl(DIA)) ~ OpCl(VIX)) x.lm <- buildModel(x,method='lm',training.per=c('2001-01-01','2001-04-01')) fittedModel(x.lm) coef(fittedModel(x.lm)) coef(x.lm) # same vcov(fittedModel(x.lm)) vcov(x.lm) # same ## End(Not run)
Download, or download and append stock dividend data from Yahoo! Finance.
getDividends(Symbol, from = "1970-01-01", to = Sys.Date(), env = parent.frame(), src = "yahoo", auto.assign = FALSE, auto.update = FALSE, verbose = FALSE, split.adjust = TRUE, ..., curl.options = list())
getDividends(Symbol, from = "1970-01-01", to = Sys.Date(), env = parent.frame(), src = "yahoo", auto.assign = FALSE, auto.update = FALSE, verbose = FALSE, split.adjust = TRUE, ..., curl.options = list())
Symbol |
The Yahoo! stock symbol |
from |
date from in CCYY-MM-DD format |
to |
date to in CCYY-MM-DD format |
env |
where to create object |
src |
data source (only yahoo is valid at present) |
auto.assign |
should results be loaded to env |
auto.update |
automatically add dividend to data object |
verbose |
display status of retrieval |
split.adjust |
adjust dividends for splits ( |
... |
currently unused |
curl.options |
options passed to |
Eventually destined to be a wrapper function along the lines
of getSymbols
to different sources - this currently
only support Yahoo data.
If auto.assign is TRUE, the symbol will be written
to the environment specified in env
with a
.div appended to the name.
If auto.update is TRUE and the object is of class
xts
, the dividends will be included as an
attribute of the original object and be reassigned
to the environment specified by env
.
All other cases will return the dividend data
as an xts
object.
This function is very preliminary - and will most likely change significantly in the future.
Jeffrey A. Ryan
Yahoo! Finance: https://finance.yahoo.com
## Not run: getSymbols("MSFT") getDividends("MSFT") getDividends(MSFT) ## End(Not run)
## Not run: getSymbols("MSFT") getDividends("MSFT") getDividends(MSFT) ## End(Not run)
Download Income Statement, Balance Sheet, and Cash Flow Statements.
getFinancials(Symbol, env = parent.frame(), src = "google", auto.assign = TRUE, ...) viewFinancials(x, type=c('BS','IS','CF'), period=c('A','Q'), subset = NULL)
getFinancials(Symbol, env = parent.frame(), src = "google", auto.assign = TRUE, ...) viewFinancials(x, type=c('BS','IS','CF'), period=c('A','Q'), subset = NULL)
Symbol |
one or more valid google symbol, as a character vector or semi-colon delimited string |
env |
where to create the object |
src |
currently no sources are implemented |
auto.assign |
should results be loaded to the environment |
... |
currently unused |
x |
an object of class financials |
type |
type of statement to view |
period |
period of statement to view |
subset |
‘xts’ style subset string |
A utility to download financial statements for publicly traded companies.
Individual statements can be accessed using
standard R list extraction tools, or by
using viewFinancials
.
viewFinancials
allows for the use of
date subsetting as available in the xts
package, as well as the specification of
the type of statement to view. BS for balance
sheet, IS for income statement, and CF for cash flow
statement. The period argument is used to identify
which statements to view - (A) for annual and (Q)
for quarterly.
Six individual matrices organized in a list of class ‘financials’:
IS |
a list containing (Q)uarterly and (A)nnual Income Statements |
BS |
a list containing (Q)uarterly and (A)nnual Balance Sheets |
CF |
a list containing (Q)uarterly and (A)nnual Cash Flow Statements |
As with all free data, you may be getting exactly what you pay for. Sometimes that may be absolutely nothing.
Jeffrey A. Ryan
## Not run: getFinancials('JAVA') # returns JAVA.f to "env" getFin('AAPL') # returns AAPL.f to "env" viewFin(JAVA.f, "IS", "Q") # Quarterly Income Statement viewFin(AAPL.f, "CF", "A") # Annual Cash Flows str(AAPL.f) ## End(Not run)
## Not run: getFinancials('JAVA') # returns JAVA.f to "env" getFin('AAPL') # returns AAPL.f to "env" viewFin(JAVA.f, "IS", "Q") # Quarterly Income Statement viewFin(AAPL.f, "CF", "A") # Annual Cash Flows str(AAPL.f) ## End(Not run)
Download exchange rates or metals prices from oanda.
getFX(Currencies, from = Sys.Date() - 179, to = Sys.Date(), env = parent.frame(), verbose = FALSE, warning = TRUE, auto.assign = TRUE, ...)
getFX(Currencies, from = Sys.Date() - 179, to = Sys.Date(), env = parent.frame(), verbose = FALSE, warning = TRUE, auto.assign = TRUE, ...)
Currencies |
Currency pairs expressed as ‘CUR/CUR’ |
from |
start date expressed in ISO CCYY-MM-DD format |
to |
end date expressed in ISO CCYY-MM-DD format |
env |
which environment should they be loaded into |
verbose |
be verbose |
warning |
show warnings |
auto.assign |
use auto.assign |
... |
additional parameters to be passed to getSymbols.oanda method |
A convenience wrapper to getSymbols(x,src='oanda')
. See
getSymbols
and getSymbls.oanda
for more detail.
Data will be assigned
automatically to the environment specified (the parent environment by default).
If auto.assign = FALSE
, the data from a single metal
request will simply be returned from the function call.
If auto.assign = TRUE
is used (the default)
a vector of downloaded symbol names will be returned.
See getSymbols
and getSymbols.oanda
for more detail.
Jeffrey A. Ryan
Oanda.com https://www.oanda.com
## Not run: getFX("USD/JPY") getFX("EUR/USD",from="2005-01-01") ## End(Not run)
## Not run: getFX("USD/JPY") getFX("EUR/USD",from="2005-01-01") ## End(Not run)
Download daily metals prices from oanda.
getMetals(Metals, from = Sys.Date() - 179, to = Sys.Date(), base.currency="USD", env = parent.frame(), verbose = FALSE, warning = TRUE, auto.assign = TRUE, ...)
getMetals(Metals, from = Sys.Date() - 179, to = Sys.Date(), base.currency="USD", env = parent.frame(), verbose = FALSE, warning = TRUE, auto.assign = TRUE, ...)
Metals |
metals expressed in common name or symbol form |
from |
start date expressed in ISO CCYY-MM-DD format |
to |
end date expressed in ISO CCYY-MM-DD format |
base.currency |
which currency should the price be in |
env |
which environment should they be loaded into |
verbose |
be verbose |
warning |
show warnings |
auto.assign |
use auto.assign |
... |
additional parameters to be passed to getSymbols.oanda method |
A convenience wrapper to getSymbols(x,src='oanda')
.
The most useful aspect of getMetals is the ability to specify the Metals in terms of underlying 3 character symbol or by name (e.g. XAU (gold) , XAG (silver), XPD (palladium), or XPT (platinum)).
There are unique aspects of any continuously traded commodity, and it is recommended that the user visit https://www.oanda.com for details on specific pricing issues.
See getSymbols
and getSymbls.oanda
for more detail.
Data will be assigned
automatically to the environment specified (the parent environment by default).
If auto.assign = FALSE
, the data from a single metal
request will simply be returned from the function call.
If auto.assign = TRUE
is used (the default)
a vector of downloaded symbol names will be returned.
See getSymbols
and getSymbols.oanda
for more detail.
Jeffrey A. Ryan
Oanda.com https://www.oanda.com
## Not run: getMetals(c("gold","XPD")) getMetals("plat",from="2005-01-01") ## End(Not run)
## Not run: getMetals(c("gold","XPD")) getMetals("plat",from="2005-01-01") ## End(Not run)
Update currently specified or built model with most recent data.
getModelData(x, na.rm = TRUE)
getModelData(x, na.rm = TRUE)
x |
An object of class |
na.rm |
Boolean. Remove NA values. Defaults to TRUE |
Primarily used within specify model calls,
getModelData
is used to retrieve the appropriate underlying variables,
and apply model specified transformations automatically.
It can be used to also update a current model in memory with the most recent data.
Returns object of class quantmod.OHLC
Jeffrey Ryan
getSymbols
load data
specifyModel
create model structure
buildModel
construct model
modelData
extract model dataset
## Not run: my.model <- specifyModel(Next(OpCl(QQQ)) ~ Lag(Cl(NDX),0:5)) getModelData(my.model) ## End(Not run)
## Not run: my.model <- specifyModel(Next(OpCl(QQQ)) ~ Lag(Cl(NDX),0:5)) getModelData(my.model) ## End(Not run)
Function to download option chain data from data providers.
getOptionChain(Symbols, Exp = NULL, src="yahoo", ...)
getOptionChain(Symbols, Exp = NULL, src="yahoo", ...)
Symbols |
The name of the underlying symbol. Source ‘yahoo’ only allows for a single ticker while source ‘orats’ can return multiple tickers. |
Exp |
One or more expiration dates, NULL, or an ISO-8601 style string.
If |
src |
Source of data. One of ‘yahoo’ or ‘orats’ with a default of ‘yahoo’. |
... |
Additional parameters. |
This function is a wrapper to data-provider specific APIs. By default the data is sourced from yahoo.
A named list containing two data.frames, one
for calls and one for puts. If more than one
expiration was requested, this two-element list
will be contained within list of length length(Exp)
.
Each element of this list will be named with the expiration
month, day, and year (for Yahoo sourced data).
If Exp
is set to NULL
, all expirations
will be returned. Not explicitly setting will only
return the front month.
Jeffrey A. Ryan, Joshua M. Ulrich, Steve Bronder
https://finance.yahoo.com, https://docs.orats.io/datav2-api-guide/data.html#strikes
## Not run: # Only the front-month expiry AAPL.OPT <- getOptionChain("AAPL") # All expiries AAPL.OPTS <- getOptionChain("AAPL", NULL) # All 2015 and 2016 expiries AAPL.2015 <- getOptionChain("AAPL", "2015/2016") # Using orats backend NFLX.AAPL.2021 <- getOptionChain(c("NFLX", "AAPL"), "2021", src = "orats", api.key = Sys.getenv("ORATS_API_KEY")) ## End(Not run)
## Not run: # Only the front-month expiry AAPL.OPT <- getOptionChain("AAPL") # All expiries AAPL.OPTS <- getOptionChain("AAPL", NULL) # All 2015 and 2016 expiries AAPL.2015 <- getOptionChain("AAPL", "2015/2016") # Using orats backend NFLX.AAPL.2021 <- getOptionChain(c("NFLX", "AAPL"), "2021", src = "orats", api.key = Sys.getenv("ORATS_API_KEY")) ## End(Not run)
Function to download option chain data from orats.
getOptionChain.orats(Symbols, Exp, api.key, dte, delta)
getOptionChain.orats(Symbols, Exp, api.key, dte, delta)
Symbols |
The name of the underlying symbol. Source ‘yahoo’ only allows for a single ticker while source ‘orats’ can return multiple tickers. |
Exp |
One or more expiration dates, NULL, or an ISO-8601 style string.
If |
api.key |
A character vector for the key given with an account for
accessing the orats API. If missing, the function will look for an
environment variable |
dte |
A vector of two integers giving a range of expiry dates to subset the results by. |
delta |
A vector of two integers giving a range deltas to subset the results by. |
This function is a wrapper to data-provider specific APIs. By default the data is sourced from yahoo.
For orats, returns A named list containing five data.frames, one
each for calls and puts that follows a similar form to the return
from yahoo, but does not have a Last price and instead has a
Ticker column for multiple ticker requests. The *_extra data.frames
contain additional information from the ‘orats’ API end point
whose definitions are available at the URL in the references.
If more than one expiration was requested, The results will be returned as
a list within list of length length(Exp)
.
Each element of this list will be named with the expiration
month, day, and year (%b.%d.%Y).
If Exp
is set to NULL
, all expirations
will be returned. Not explicitly setting will only
return the front month.
Steve Bronder
https://docs.orats.io/datav2-api-guide/data.html#strikes
## Not run: # Only the front-month expiry AAPL.OPT <- getOptionChain("AAPL", api.key = Sys.getenv("ORATS_API_KEY")) # All expiries AAPL.OPTS <- getOptionChain("AAPL", NULL, api.key = Sys.getenv("ORATS_API_KEY")) # All 2015 and 2016 expiries AAPL.2015 <- getOptionChain("AAPL", "2015/2016", api.key = Sys.getenv("ORATS_API_KEY")) ## End(Not run)
## Not run: # Only the front-month expiry AAPL.OPT <- getOptionChain("AAPL", api.key = Sys.getenv("ORATS_API_KEY")) # All expiries AAPL.OPTS <- getOptionChain("AAPL", NULL, api.key = Sys.getenv("ORATS_API_KEY")) # All 2015 and 2016 expiries AAPL.2015 <- getOptionChain("AAPL", "2015/2016", api.key = Sys.getenv("ORATS_API_KEY")) ## End(Not run)
Fetch current stock quote(s) from specified source. At present this only handles sourcing quotes from Yahoo Finance and Alpha Vantage, but it can be extended to additional sources.
getQuote(Symbols, src = "yahoo", what, ...) standardQuote(src="yahoo") yahooQF(names) yahooQuote.EOD
getQuote(Symbols, src = "yahoo", what, ...) standardQuote(src="yahoo") yahooQF(names) yahooQuote.EOD
Symbols |
character string of symbols, separated by semi-colons |
src |
source of data ("yahoo" and "av" are currently implemented) |
what |
what should be retrieved |
names |
which data should be retrieved |
... |
currently unused |
The number of symbols per request is limited to 200 for Yahoo! and 100 for
Alpha Vantage. getQuote
will make multiple requests if more than the
maximum number of symbols are requested. It will then combine the results of
all the requests and return one data frame. The data frame will contain a
column for each requested data field, and the requested symbols will be stored
in the row names.
In order to import quotes from Alpha Vantage, you must obtain an
API key by completing a free, one-time registration at their website:
https://www.alphavantage.co/. Then you can call getQuote
with
src = "av"
and api.key = "[your key]"
.
The what
argument allows for specific data to be requested. For
getQuote.yahoo
, the value of what
should be a quoteFormat
object like that returned by standardQuote
. The yahooQF
function
will create an interactive selection tool if the what
argument is
missing. The what
argument is currently ignored for Alpha Vantage data
because only a few fields are available.
standardQuote
currently only applies to the Yahoo! data source. It
returns a quoteFormat
object to use with the getQuote
function.
yahooQuote.EOD
is a constant quoteFormat
object for OHLCV data.
Jeffrey A. Ryan (Yahoo) Ethan B. Smith (Alpha Vantage)
Yahoo! Finance https://finance.yahoo.com Alpha Vantage https://www.alphavantage.co
yahooQuote.EOD ## Not run: getQuote("AAPL") getQuote("QQQ;SPY;^VXN",what=yahooQF(c("Bid","Ask"))) standardQuote() yahooQF() ## End(Not run)
yahooQuote.EOD ## Not run: getQuote("AAPL") getQuote("QQQ;SPY;^VXN",what=yahooQF(c("Bid","Ask"))) standardQuote() yahooQF() ## End(Not run)
Download, or download and append stock split data from Yahoo! Finance.
getSplits(Symbol, from = "1970-01-01", to = Sys.Date(), env = parent.frame(), src = "yahoo", auto.assign = FALSE, auto.update = FALSE, verbose = FALSE, ..., curl.options = list())
getSplits(Symbol, from = "1970-01-01", to = Sys.Date(), env = parent.frame(), src = "yahoo", auto.assign = FALSE, auto.update = FALSE, verbose = FALSE, ..., curl.options = list())
Symbol |
The Yahoo! stock symbol |
from |
date from in CCYY-MM-DD format |
to |
date to in CCYY-MM-DD format |
env |
where to create object |
src |
data source (only yahoo is valid at present) |
auto.assign |
should results be loaded to env |
auto.update |
automatically add split to data object |
verbose |
display status of retrieval |
... |
currently unused |
curl.options |
options passed to |
Eventually destined to be a wrapper function along the lines
of getSymbols
to different sources - this currently
only support Yahoo data.
If auto.assign is TRUE, the symbol will be written
to the environment specified in env
with a
.div appended to the name.
If auto.update is TRUE and the object is of class
xts
, the dividends will be included as an
attribute of the original object and be reassigned
to the environment specified by env
.
All other cases will return the split data
as an xts
object. NA
is returned if there
is no split data.
This function is very preliminary - and will most likely change significantly in the future.
Josh Ulrich
Yahoo! Finance: https://finance.yahoo.com
## Not run: getSymbols("MSFT") getSplits("MSFT") getSplits(MSFT) ## End(Not run)
## Not run: getSymbols("MSFT") getSplits("MSFT") getSplits(MSFT) ## End(Not run)
Functions to load and manage Symbols
in
specified environment. Used by specifyModel
to retrieve symbols specified in first step of modelling
procedure. Not a true S3 method, but methods for different
data sources follow an S3-like naming convention. Additional
methods can be added by simply adhering to the convention.
Current src
methods available are: yahoo, google,
MySQL, FRED, csv, RData, oanda, and av.
Data is loaded silently without user assignment by default.
getSymbols(Symbols = NULL, env = parent.frame(), reload.Symbols = FALSE, verbose = FALSE, warnings = TRUE, src = "yahoo", symbol.lookup = TRUE, auto.assign = getOption('getSymbols.auto.assign',TRUE), ...) loadSymbols(Symbols = NULL, env = parent.frame(), reload.Symbols = FALSE, verbose = FALSE, warnings = TRUE, src = "yahoo", symbol.lookup = TRUE, auto.assign = getOption('loadSymbols.auto.assign',TRUE), ...) showSymbols(env=parent.frame()) removeSymbols(Symbols=NULL,env=parent.frame()) saveSymbols(Symbols = NULL, file.path=stop("must specify 'file.path'"), env = parent.frame())
getSymbols(Symbols = NULL, env = parent.frame(), reload.Symbols = FALSE, verbose = FALSE, warnings = TRUE, src = "yahoo", symbol.lookup = TRUE, auto.assign = getOption('getSymbols.auto.assign',TRUE), ...) loadSymbols(Symbols = NULL, env = parent.frame(), reload.Symbols = FALSE, verbose = FALSE, warnings = TRUE, src = "yahoo", symbol.lookup = TRUE, auto.assign = getOption('loadSymbols.auto.assign',TRUE), ...) showSymbols(env=parent.frame()) removeSymbols(Symbols=NULL,env=parent.frame()) saveSymbols(Symbols = NULL, file.path=stop("must specify 'file.path'"), env = parent.frame())
Symbols |
a character vector specifying the names of each symbol to be loaded |
env |
where to create objects. Setting env=NULL is equal to auto.assign=FALSE |
reload.Symbols |
boolean to reload current symbols in specified environment. (FALSE) |
verbose |
boolean to turn on status of retrieval. (FALSE) |
warnings |
boolean to turn on warnings. (TRUE) |
src |
character string specifying sourcing method. (yahoo) |
symbol.lookup |
retrieve symbol's sourcing method from external lookup (TRUE) |
auto.assign |
should results be loaded to |
file.path |
character string of file location |
... |
additional parameters |
getSymbols
is a wrapper to load data from
various sources, local or remote. Data is
fetched via one of the available getSymbols
methods
and either saved in the env
specified - the parent.frame()
by default – or returned to the caller. The functionality derives from base::load
behavior and semantics, i.e. is assigned automatically
to a variable in the specified environment without the
user explicitly assigning the returned data to a variable. The assigned variable
name is that of the respective Symbols value.
The previous sentence's point warrants repeating - getSymbols is called for its side effects, and by defaultdoes not return the data object loaded. The data is ‘loaded’ silently by the function into the environment specified.
If automatic assignment is not desired, env
may be set to NULL, or
auto.assign
set to FALSE.
The early versions of getSymbols assigned each object into the user's .GlobalEnv by name (pre 2009 up to versions less than 0.4-0). This behavior is now supported by manually setting env=.GlobalEnv. As of version 0.4-0, the environment is set to parent.frame(), which preserved the user workspace when called within another scope.
This behavior is expect to change for getSymbols as of 0.5-0, and all
results will instead be explicitly returned to the caller
unless a auto.assign
is set to TRUE
.
Many thanks to Kurt Hornik and Achim Zeileis for suggesting this change, and
further thanks to Dirk Eddelbuettel for encouraging the move to a more functional
default by 0.5-0.
Using auto.assign=TRUE, the variable chosen is an R-legal name derived
from the symbol being loaded. It is possible, using
setSymbolLookup
to specify an alternate
name if the default is not desired. See that function for
details.
If auto.assign=FALSE or env=NULL (as of 0.4-0) the data will be returned from the call, and will require the user to assign the results himself. Note that only one symbol at a time may be requested when auto assignment is disabled.
Most, if not all, documentation and functionality related
to model construction and testing in quantmod
assumes that auto.assign remains set to TRUE and env
is
a valid environment object for the calls related to those functions.
Upon completion a list of
loaded symbols is stored in the specified environment
under the name .getSymbols
.
Objects loaded by getSymbols
with auto.assign=TRUE
can be viewed with
showSymbols
and
removed by a call to removeSymbols
. Additional
data loading “methods” can be
created simply by following the S3-like naming
convention where getSymbols.NAME
is used for your function NAME. See getSymbols
source code.
setDefaults(getSymbols)
can be used to
specify defaults for getSymbols
arguments.
setDefaults(getSymbols.MySQL)
may be used for arguments
specific to getSymbols.MySQL
, etc.
The “sourcing” of data is managed internally
through a complex lookup procedure. If symbol.lookup
is TRUE (the default), a check is made if any symbol
has had its source specified by setSymbolLookup
.
If not set, the process continues by checking to see if
src
has been specified by the user in the
function call. If not, any src
defined with
setDefaults(getSymbols,src=)
is used.
Finally, if none of the other source rules apply
the default getSymbols
src
method is
used (‘yahoo’).
Called for its side-effect with env
set to a
valid environment and auto.assign=TRUE,
getSymbols
will load into the specified
env
one object for each
Symbol
specified, with class defined
by return.class
. Presently this may be ts
,
zoo
, xts
, or timeSeries
.
If env=NULL or auto.assign=FALSE an object of type
return.class
will be returned.
As of version 0.4-0, the default env
value is now
parent.frame()
. In interactive use this should provide
the same functionality as the previous version.
While it is possible to load symbols as classes other
than zoo
, quantmod requires most, if not
all, data to be of class zoo
or inherited
from zoo
- e.g. xts
. The additional
methods are meant mainly to be of use for those
using the functionality outside of the quantmod workflow.
Jeffrey A. Ryan
getModelData
,specifyModel
,
setSymbolLookup
,
getSymbols.csv
,
getSymbols.RData
,
getSymbols.oanda
,
getSymbols.yahoo
,
getSymbols.google
,
getSymbols.FRED
,
getFX
,
getMetals
,
## Not run: setSymbolLookup(QQQ='yahoo',SPY='google') # loads QQQ from yahoo (set with setSymbolLookup) # loads SPY from MySQL (set with setSymbolLookup) getSymbols(c('QQQ','SPY')) # loads Ford market data from yahoo (the formal default) getSymbols('F') # loads symbol from MySQL database (set with setDefaults) getSymbols('DIA', verbose=TRUE, src='MySQL') # loads Ford as time series class ts getSymbols('F',src='yahoo',return.class='ts') # load into a new environment data.env <- new.env() getSymbols("YHOO", env=data.env) ls.str(data.env) # constrain to local scope try(local( { getSymbols("AAPL") # or getSymbols("AAPL", env=environment()) str(AAPL) })) exists("AAPL") # FALSE # assign into an attached environment attach(NULL, name="DATA.ENV") getSymbols("AAPL", env=as.environment("DATA.ENV")) ls("DATA.ENV") detach("DATA.ENV") # directly return to caller str( getSymbols("AAPL", env=NULL) ) str( getSymbols("AAPL", auto.assign=FALSE) ) # same ## End(Not run)
## Not run: setSymbolLookup(QQQ='yahoo',SPY='google') # loads QQQ from yahoo (set with setSymbolLookup) # loads SPY from MySQL (set with setSymbolLookup) getSymbols(c('QQQ','SPY')) # loads Ford market data from yahoo (the formal default) getSymbols('F') # loads symbol from MySQL database (set with setDefaults) getSymbols('DIA', verbose=TRUE, src='MySQL') # loads Ford as time series class ts getSymbols('F',src='yahoo',return.class='ts') # load into a new environment data.env <- new.env() getSymbols("YHOO", env=data.env) ls.str(data.env) # constrain to local scope try(local( { getSymbols("AAPL") # or getSymbols("AAPL", env=environment()) str(AAPL) })) exists("AAPL") # FALSE # assign into an attached environment attach(NULL, name="DATA.ENV") getSymbols("AAPL", env=as.environment("DATA.ENV")) ls("DATA.ENV") detach("DATA.ENV") # directly return to caller str( getSymbols("AAPL", env=NULL) ) str( getSymbols("AAPL", auto.assign=FALSE) ) # same ## End(Not run)
Downloads historical or realtime equity price data from https://www.alphavantage.co/. Free registration is required.
getSymbols.av(Symbols, env, api.key, return.class = "xts", periodicity = "daily", adjusted = FALSE, interval = "1min", output.size = "compact", data.type = "json", ...)
getSymbols.av(Symbols, env, api.key, return.class = "xts", periodicity = "daily", adjusted = FALSE, interval = "1min", output.size = "compact", data.type = "json", ...)
Symbols |
a character vector specifying the names of the symbols to be loaded |
env |
where to create objects (environment) |
api.key |
the API key issued by Alpha Vantage when you registered (character) |
return.class |
class of returned object, see Value (character) |
periodicity |
one of |
adjusted |
if TRUE, include a column of closing prices adjusted for dividends and splits |
interval |
one of |
output.size |
either |
data.type |
either |
... |
additional parameters as per |
Meant to be called internally by getSymbols
only.
This method is not meant to be called directly, instead
a call to getSymbols("x", src="av")
will
in turn call this method. It is documented for the
sole purpose of highlighting the arguments accepted.
You must register with Alpha Vantage in order to download their data,
but the one-time registration is fast and free.
Register at their web site, https://www.alphavantage.co/,
and you will receive an API key:
a short string of alphanumeric characters (e.g., "FU4U").
Provide the API key every time you call getSymbols
;
or set it globally using setDefaults(getSymbols.av, api.key="yourKey")
.
The Alpha Vantage site provides daily, weekly, monthly, and intraday data.
Use periodicity
to select one.
Note that intraday data will includes today's data (delayed) if downloaded
while the market is open, which is pretty cool.
Set adjusted=TRUE
to include a column of closing prices adjusted for
dividends and stock splits (available only for daily, weekly, and monthly data).
The intraday data is provided as a sequence of OHLC bars.
Use the interval
argument to determine the "width" of the bars:
1 minute bars, 5 minutes bars, 15 minutes bars, etc.
By default Alpha Vantage returns the 100 most-recent data points (output.size="compact"
).
Set output.size="full"
to obtain the entire available history.
For daily, weekly, and monthly data, Alpha Vantage says the available data is up to 20 years;
for intraday data, the available history is the most recent 10 or 15 days.
Be forewarned that downloading full
data requires more time than compact
data, of course.
Alpha Vantage provides access to data via two APIs. You can choose the API via
the data.type
argument. data.type="json"
, the default, will
import data using the JSON API. This API includes additional metadata (e.g.
last updated time, timezone, etc) that is not provided via the CSV API.
A call to getSymbols(Symbols, src="av")
will create objects
in the specified environment,
one object for each Symbol
specified.
The object class of the object(s) is determined by return.class
.
Presently this may be "ts"
, "zoo"
, "xts"
, or "timeSeries"
.
Paul Teetor
Alpha Vantage documentation available at https://www.alphavantage.co/
getSymbols
,
getSymbols.yahoo
,
getSymbols.google
## Not run: # You'll need the API key given when you registered getSymbols("IBM", src="av", api.key="yourKey") # The default output.size="compact" returns only the most recent 100 rows. # Set output.size="full" for all available data. getSymbols("IBM", src="av", api.key="yourKey", output.size="full") # Intraday data is available for the most recent 10 or 15 days # and includes quasi-realtime data (i.e., 20-minute delayed) getSymbols("IBM", src="av", api.key="yourKey", output.size="full", periodicity="intraday") # Repeating your API key every time is tedious. # Fortunately, you can set a global default. setDefaults(getSymbols.av, api.key="yourKey") getSymbols("IBM", src="av") ## End(Not run)
## Not run: # You'll need the API key given when you registered getSymbols("IBM", src="av", api.key="yourKey") # The default output.size="compact" returns only the most recent 100 rows. # Set output.size="full" for all available data. getSymbols("IBM", src="av", api.key="yourKey", output.size="full") # Intraday data is available for the most recent 10 or 15 days # and includes quasi-realtime data (i.e., 20-minute delayed) getSymbols("IBM", src="av", api.key="yourKey", output.size="full", periodicity="intraday") # Repeating your API key every time is tedious. # Fortunately, you can set a global default. setDefaults(getSymbols.av, api.key="yourKey") getSymbols("IBM", src="av") ## End(Not run)
Downloads Symbols
to specified env
from local comma seperated file. This method is
not to be called directly, instead a call to
getSymbols(Symbols,src='csv')
will in
turn call this method. It is documented for the
sole purpose of highlighting the arguments
accepted, and to serve as a guide to creating
additional getSymbols ‘methods’.
getSymbols.csv(Symbols, env, dir="", return.class = "xts", extension="csv", col.names=c("Open","High","Low","Close","Volume","Adjusted"), ...)
getSymbols.csv(Symbols, env, dir="", return.class = "xts", extension="csv", col.names=c("Open","High","Low","Close","Volume","Adjusted"), ...)
Symbols |
a character vector specifying the names of each symbol to be loaded |
env |
where to create objects. (.GlobalEnv) |
dir |
directory of csv file |
return.class |
class of returned object |
extension |
extension of csv file |
col.names |
data column names |
... |
additional parameters |
Meant to be called internally by getSymbols
(see also).
One of a few currently defined methods for loading
data for use with quantmod. Essentially a
simple wrapper to the underlying R read.csv
.
A call to getSymbols.csv will load into the specified
environment one object for each
Symbol
specified, with class defined
by return.class
. Presently this may be ts
,
zoo
, xts
, or timeSeries
.
This has yet to be tested on a windows platform. It should work though file seperators may be an issue.
Jeffrey A. Ryan
getSymbols
,
read.csv
,
setSymbolLookup
## Not run: # All 3 getSymbols calls return the same # MSFT to the global environment # The last example is what NOT to do! ## Method #1 getSymbols('MSFT',src='csv') ## Method #2 setDefaults(getSymbols,src='csv') # OR setSymbolLookup(MSFT='csv') getSymbols('MSFT') ######################################### ## NOT RECOMMENDED!!! ######################################### ## Method #3 getSymbols.csv('MSFT',verbose=TRUE,env=globalenv()) ## End(Not run)
## Not run: # All 3 getSymbols calls return the same # MSFT to the global environment # The last example is what NOT to do! ## Method #1 getSymbols('MSFT',src='csv') ## Method #2 setDefaults(getSymbols,src='csv') # OR setSymbolLookup(MSFT='csv') getSymbols('MSFT') ######################################### ## NOT RECOMMENDED!!! ######################################### ## Method #3 getSymbols.csv('MSFT',verbose=TRUE,env=globalenv()) ## End(Not run)
R access to over 11,000 data series accessible via the St. Louis Federal Reserve Bank's FRED system.
Downloads Symbols
to specified env
from ‘research.stlouisfed.org’. This method is
not to be called directly, instead a call to
getSymbols(Symbols,src='FRED')
will in
turn call this method. It is documented for the
sole purpose of highlighting the arguments
accepted, and to serve as a guide to creating
additional getSymbols ‘methods’.
getSymbols.FRED(Symbols, env, return.class = "xts", ...)
getSymbols.FRED(Symbols, env, return.class = "xts", ...)
Symbols |
a character vector specifying the names of each symbol to be loaded |
env |
where to create objects. (.GlobalEnv) |
return.class |
class of returned object |
... |
additional parameters |
Meant to be called internally by getSymbols
(see also).
One of many methods for loading data for use with quantmod. Essentially a simple wrapper to the underlying FRED data download site.
Naming conventions must follow those as seen on the Federal Reserve Bank of St Louis's website for FRED. A lookup facility will hopefully be incorporated into quantmod in the near future.
A call to getSymbols.FRED will load into the specified
environment one object for each
Symbol
specified, with class defined
by return.class
. Presently this may be ts
,
zoo
, xts
, or timeSeries
.
FRED changed its URL scheme for the downloads from http:// to
https://. If getSymbols.FRED
fails for this reason, try
one of the following solutions:
Explicitly pass method
via the getSymbols
call (or via setDefaults
).
Install downloader, which may be able to automagically determine a suitable method.
Set the download.file.method
global option.
Jeffrey A. Ryan
St. Louis Fed: Economic Data - FRED https://fred.stlouisfed.org/
## Not run: # All 3 getSymbols calls return the same # CPI data to the global environment # The last example is what NOT to do! ## Method #1 getSymbols('CPIAUCNS',src='FRED') ## Method #2 setDefaults(getSymbols,src='FRED') # OR setSymbolLookup(CPIAUCNS='FRED') getSymbols('CPIAUCNS') ######################################### ## NOT RECOMMENDED!!! ######################################### ## Method #3 getSymbols.FRED('CPIAUCNS',env=globalenv()) ## End(Not run)
## Not run: # All 3 getSymbols calls return the same # CPI data to the global environment # The last example is what NOT to do! ## Method #1 getSymbols('CPIAUCNS',src='FRED') ## Method #2 setDefaults(getSymbols,src='FRED') # OR setSymbolLookup(CPIAUCNS='FRED') getSymbols('CPIAUCNS') ######################################### ## NOT RECOMMENDED!!! ######################################### ## Method #3 getSymbols.FRED('CPIAUCNS',env=globalenv()) ## End(Not run)
Fetch data from MySQL database. As with other
methods extending the getSymbols
function,
this should NOT be called directly. Its
documentation is meant to highlight the formal
arguments, as well as provide a reference for
further user contributed data tools.
getSymbols.MySQL(Symbols, env, return.class = 'xts', db.fields = c("date", "o", "h", "l", "c", "v", "a"), field.names = NULL, user = NULL, password = NULL, dbname = NULL, host = "localhost", port = 3306, ...)
getSymbols.MySQL(Symbols, env, return.class = 'xts', db.fields = c("date", "o", "h", "l", "c", "v", "a"), field.names = NULL, user = NULL, password = NULL, dbname = NULL, host = "localhost", port = 3306, ...)
Symbols |
a character vector specifying the names of each symbol to be loaded |
env |
where to create objects. (.GlobalEnv) |
return.class |
desired class of returned object. Can be xts, zoo, data.frame, or ts. (zoo) |
db.fields |
character vector indicating names of fields to retrieve |
field.names |
names to assign to returned columns |
user |
username to access database |
password |
password to access database |
dbname |
database name |
host |
database host |
port |
database port |
... |
currently not used |
Meant to be called internally by getSymbols
(see also)
One of a few currently defined methods for loading data for
use with quantmod. Its use requires the packages
DBI and MySQL, along with a running
MySQL database with tables corresponding to the
Symbol
name.
The purpose of this abstraction is to make transparent the ‘source’ of the data, allowing instead the user to concentrate on the data itself.
A call to getSymbols.MySQL will load into the specified
environment one object for each Symbol
specified,
with class defined by return.class
.
The default configuration needs a table named
for the Symbol specified (e.g. MSFT), with
column names date,o,h,l,c,v,a. For table
layout changes it is best to use
setDefaults(getSymbols.MySQL,...)
with
the new db.fields values specified.
Jeffrey A. Ryan
MySQL AB https://www.mysql.com
Jeroen Ooms and David James and Saikat DebRoy and Hadley Wickham and Jeffrey Horner (2019). RMySQL: Database Interface and 'MySQL' Driver for R. https://CRAN.R-project.org/package=RMySQL
R-SIG-DB. DBI: R Database Interface
## Not run: # All 3 getSymbols calls return the same # MSFT to the global environment # The last example is what NOT to do! setDefaults(getSymbols.MySQL,user='jdoe',password='secret', dbname='tradedata') ## Method #1 getSymbols('MSFT',src='MySQL') ## Method #2 setDefaults(getSymbols,src='MySQL') # OR setSymbolLookup(MSFT='MySQL') getSymbols('MSFT') ######################################### ## NOT RECOMMENDED!!! ######################################### ## Method #3 getSymbols.MySQL('MSFT',env=globalenv()) ## End(Not run)
## Not run: # All 3 getSymbols calls return the same # MSFT to the global environment # The last example is what NOT to do! setDefaults(getSymbols.MySQL,user='jdoe',password='secret', dbname='tradedata') ## Method #1 getSymbols('MSFT',src='MySQL') ## Method #2 setDefaults(getSymbols,src='MySQL') # OR setSymbolLookup(MSFT='MySQL') getSymbols('MSFT') ######################################### ## NOT RECOMMENDED!!! ######################################### ## Method #3 getSymbols.MySQL('MSFT',env=globalenv()) ## End(Not run)
Access to 191 currency and metal prices, downloadable as more that 36000 currency pairs from Oanda.com.
Downloads Symbols
to specified env
from
https://www.oanda.com historical currency database.
This method is not meant to be called directly, instead
a call to getSymbols("x",src="oanda")
will
in turn call this method. It is documented for the
sole purpose of highlighting the arguments accepted,
and to serve as a guide to creating additional
getSymbols 'methods'.
getSymbols.oanda(Symbols, env, return.class = "xts", from = Sys.Date() - 179, to = Sys.Date(), ...)
getSymbols.oanda(Symbols, env, return.class = "xts", from = Sys.Date() - 179, to = Sys.Date(), ...)
Symbols |
a character vector specifying the names
of each symbol to be loaded - expressed as a currency pair.
(e.g. U.S. Dollar to Euro rate would be expressed as
a string “USD/EUR”. The naming convention follows from
Oanda.com, and a table of possible values is
available by calling |
env |
where to create objects. |
return.class |
class of returned object |
from |
Start of series expressed as "CCYY-MM-DD" |
to |
Start of series expressed as "CCYY-MM-DD" |
... |
additional parameters |
Meant to be called internally by getSymbols only.
Oanda data is 7 day daily average price data, that is Monday through Sunday.
Oanda only provides historical data for the past 180 days. getSymbols will
return as much data as possible, and warn when the from
date is more
than 180 days ago.
A call to getSymbols(Symbols,src="oanda") will load into the specified environment one object for each 'Symbol' specified, with class defined by 'return.class'. Presently this may be 'ts', 'zoo', 'xts', or 'timeSeries'.
Oanda rates are quoted as one unit of base currency to the equivelant amount of foreign currency.
Jeffrey A. Ryan
Oanda.com https://www.oanda.com
Currencies: getSymbols.FRED
,
getSymbols
## Not run: getSymbols("USD/EUR",src="oanda") getSymbols("USD/EUR",src="oanda",from="2005-01-01") ## End(Not run)
## Not run: getSymbols("USD/EUR",src="oanda") getSymbols("USD/EUR",src="oanda",from="2005-01-01") ## End(Not run)
Downloads Symbols
to specified env
from local R data file. This method is
not to be called directly, instead a call to
getSymbols(Symbols,src='rda')
will in
turn call this method. It is documented for the
sole purpose of highlighting the arguments
accepted, and to serve as a guide to creating
additional getSymbols ‘methods’.
getSymbols.rda(Symbols, env, dir="", return.class = "xts", extension="rda", col.names=c("Open","High","Low","Close","Volume","Adjusted"), ...)
getSymbols.rda(Symbols, env, dir="", return.class = "xts", extension="rda", col.names=c("Open","High","Low","Close","Volume","Adjusted"), ...)
Symbols |
a character vector specifying the names of each symbol to be loaded |
env |
where to create objects. (.GlobalEnv) |
dir |
directory of rda/RData file |
return.class |
class of returned object |
extension |
extension of R data file |
col.names |
data column names |
... |
additional parameters |
Meant to be called internally by getSymbols
(see also).
One of a few currently defined methods for loading
data for use with quantmod. Essentially a
simple wrapper to the underlying R load
.
A call to getSymbols.csv will load into the specified
environment one object for each
Symbol
specified, with class defined
by return.class
. Presently this may be ts
,
zoo
, xts
, data.frame
,
or timeSeries
.
Jeffrey A. Ryan
getSymbols
,
load
,
setSymbolLookup
## Not run: # All 3 getSymbols calls return the same # MSFT to the global environment # The last example is what NOT to do! ## Method #1 getSymbols('MSFT',src='rda') getSymbols('MSFT',src='RData') ## Method #2 setDefaults(getSymbols,src='rda') # OR setSymbolLookup(MSFT='rda') # OR setSymbolLookup(MSFT=list(src='rda')) getSymbols('MSFT') ######################################### ## NOT RECOMMENDED!!! ######################################### ## Method #3 getSymbols.rda('MSFT',verbose=TRUE,env=globalenv()) ## End(Not run)
## Not run: # All 3 getSymbols calls return the same # MSFT to the global environment # The last example is what NOT to do! ## Method #1 getSymbols('MSFT',src='rda') getSymbols('MSFT',src='RData') ## Method #2 setDefaults(getSymbols,src='rda') # OR setSymbolLookup(MSFT='rda') # OR setSymbolLookup(MSFT=list(src='rda')) getSymbols('MSFT') ######################################### ## NOT RECOMMENDED!!! ######################################### ## Method #3 getSymbols.rda('MSFT',verbose=TRUE,env=globalenv()) ## End(Not run)
Fetch data from SQLite database. As with other methods
extending getSymbols
this function should NOT be called directly.
getSymbols.SQLite(Symbols, env, return.class = 'xts', db.fields = c("row_names", "Open", "High", "Low", "Close", "Volume", "Adjusted"), field.names = NULL, dbname = NULL, POSIX = TRUE, ...)
getSymbols.SQLite(Symbols, env, return.class = 'xts', db.fields = c("row_names", "Open", "High", "Low", "Close", "Volume", "Adjusted"), field.names = NULL, dbname = NULL, POSIX = TRUE, ...)
Symbols |
a character vector specifying the names of each symbol to be loaded |
env |
where to create the objects |
return.class |
desired class of returned object |
db.fields |
character vector naming fields to retrieve |
field.names |
names to assign to returned columns |
dbname |
database name |
POSIX |
are rownames numeric |
... |
additional arguments |
Meant to be called internally by getSymbols
(see also)
One of a few currently defined methods for loading data for use with 'quantmod'. Its use requires the packages 'DBI' and 'RSQLite', along with a SQLite database.
The purpose of this abstraction is to make transparent the 'source' of the data, allowing instead the user to concentrate on the data itself.
A call to getSymbols.SQLite will load into the specified environment one object for each 'Symbol' specified, with class defined by 'return.class'.
This function is experimental at best, and has not been thoroughly tested. Use with caution, and please report any bugs to the maintainer of quantmod.
Jeffrey A. Ryan
SQLite https://www.sqlite.org/index.html
David A. James RSQLite: SQLite interface for R
R-SIG-DB. DBI: R Database Interface
## Not run: getSymbols("QQQ",src="SQLite") ## End(Not run)
## Not run: getSymbols("QQQ",src="SQLite") ## End(Not run)
Downloads historical or realtime equity price data from https://www.tiingo.com/. Registration is required.
getSymbols.tiingo(Symbols, env, api.key, return.class="xts", periodicity="daily", adjust=FALSE, from='2007-01-01', to=Sys.Date(), ...)
getSymbols.tiingo(Symbols, env, api.key, return.class="xts", periodicity="daily", adjust=FALSE, from='2007-01-01', to=Sys.Date(), ...)
Symbols |
a character vector specifying the names of the symbols to be loaded |
env |
where to create objects (environment) |
api.key |
the API key issued by Tiingo when you registered (character) |
return.class |
class of returned object, see Value (character) |
periodicity |
one of |
adjust |
adjust for dividends and splits? (FALSE) |
from |
Retrieve data no earlier than this date. (2007-01-01) |
to |
Retrieve data through this date (Sys.Date()) |
... |
additional parameters as per |
Meant to be called internally by getSymbols
only.
This method is not meant to be called directly, instead
a call to getSymbols("x", src="tiingo")
will
in turn call this method. It is documented for the
sole purpose of highlighting the arguments accepted.
You must register with Tiingo in order to download their data.
Register at their web site, https://www.tiingo.com,
and you will receive an API key:
a short string of alphanumeric characters (e.g., "FU4U").
Provide the API key every time you call getSymbols
;
or set it globally using setDefaults(getSymbols.tiingo, api.key="yourKey")
.
Tiingo provides daily, weekly, monthly, and annual data.
Use periodicity
to select one.
This API accessor will return adjusted or unadjusted OHLC as well as split and dividend information.
For daily, weekly, and monthly data, Tiingo says the available data is up to 30 years;
A call to getSymbols(Symbols, src="tiingo")
will create objects
in the specified environment,
one object for each Symbol
specified.
The object class of the object(s) is determined by return.class
.
Presently this may be "ts"
, "zoo"
, "xts"
, or "timeSeries"
.
Steve Bronder
Tiingo documentation available at https://www.tiingo.com
getSymbols
,
getSymbols.yahoo
,
getSymbols.av
## Not run: # You'll need the API key given when you registered getSymbols("IBM", src="tiingo", api.key="yourKey") # Repeating your API key every time is tedious. # Fortunately, you can set a global default. setDefaults(getSymbols.tiingo, api.key="yourKey") getSymbols("IBM", src="tiingo") ## End(Not run)
## Not run: # You'll need the API key given when you registered getSymbols("IBM", src="tiingo", api.key="yourKey") # Repeating your API key every time is tedious. # Fortunately, you can set a global default. setDefaults(getSymbols.tiingo, api.key="yourKey") getSymbols("IBM", src="tiingo") ## End(Not run)
Downloads Symbols
to specified env
from ‘finance.yahoo.com’. This method is
not to be called directly, instead a call to
getSymbols(Symbols,src='yahoo')
will in
turn call this method. It is documented for the
sole purpose of highlighting the arguments
accepted, and to serve as a guide to creating
additional getSymbols ‘methods’.
getSymbols.yahoo(Symbols, env, return.class = 'xts', index.class = 'Date', from = "2007-01-01", to = Sys.Date(), ..., periodicity = "daily", curl.options = list())
getSymbols.yahoo(Symbols, env, return.class = 'xts', index.class = 'Date', from = "2007-01-01", to = Sys.Date(), ..., periodicity = "daily", curl.options = list())
Symbols |
a character vector specifying the names of each symbol to be loaded |
env |
where to create objects. (.GlobalEnv) |
return.class |
class of returned object |
index.class |
class of returned object index (xts only) |
from |
Retrieve data no earlier than this date. (2007-01-01) |
to |
Retrieve data through this date (Sys.Date()) |
... |
additional parameters |
periodicity |
periodicity of data to query and return. Must be one of "daily", "weekly", "monthly". ("daily") |
curl.options |
options passed to |
Meant to be called internally by getSymbols
(see also).
One of a few currently defined methods for loading data for use with quantmod. Essentially a simple wrapper to the underlying Yahoo! finance site's historical data download.
A call to getSymbols.yahoo will load into the specified
environment one object for each
Symbol
specified, with class defined
by return.class
. Presently this may be ts
,
zoo
, xts
, or timeSeries
.
In the case of xts objects, the indexing will be by Date. This
can be altered with the index.class
argument. See
indexClass
for more information on changing index classes.
As of quantmod 0.4-9, getSymbols.yahoo
has been patched to
work with changes to Yahoo Finance, which also included the following
changes to the raw data:
The adjusted close column appears to no longer include dividend adjustments
The close column appears to be adjusted for splits twice
The open, high, and low columns are adjusted for splits, and
The raw data may contain missing values.
Jeffrey A. Ryan
Yahoo Finance: https://finance.yahoo.com
## Not run: # All 3 getSymbols calls return the same # MSFT to the global environment # The last example is what NOT to do! ## Method #1 getSymbols('MSFT',src='yahoo') ## Method #2 setDefaults(getSymbols,src='yahoo') # OR setSymbolLookup(MSFT='yahoo') getSymbols('MSFT') ######################################### ## NOT RECOMMENDED!!! ######################################### ## Method #3 getSymbols.yahoo('MSFT',env=globalenv()) ## End(Not run)
## Not run: # All 3 getSymbols calls return the same # MSFT to the global environment # The last example is what NOT to do! ## Method #1 getSymbols('MSFT',src='yahoo') ## Method #2 setDefaults(getSymbols,src='yahoo') # OR setSymbolLookup(MSFT='yahoo') getSymbols('MSFT') ######################################### ## NOT RECOMMENDED!!! ######################################### ## Method #3 getSymbols.yahoo('MSFT',env=globalenv()) ## End(Not run)
Downloads Symbols
to specified env
from ‘finance.yahoo.co.jp’. This method is
not to be called directly, instead a call to
getSymbols(Symbols,src='yahooj')
will in
turn call this method. It is documented for the
sole purpose of highlighting the arguments
accepted, and to serve as a guide to creating
additional getSymbols ‘methods’.
getSymbols.yahooj(Symbols, env, return.class = 'xts', index.class = 'Date', from = "2007-01-01", to = Sys.Date(), ...)
getSymbols.yahooj(Symbols, env, return.class = 'xts', index.class = 'Date', from = "2007-01-01", to = Sys.Date(), ...)
Symbols |
a character vector specifying the names of each symbol to be loaded |
env |
where to create objects. (.GlobalEnv) |
return.class |
class of returned object |
index.class |
class of returned object index (xts only) |
from |
Retrieve data no earlier than this date. (2007-01-01) |
to |
Retrieve data through this date (Sys.Date()) |
... |
additional parameters |
Meant to be called internally by getSymbols
(see also).
One of the few currently defined methods for loading data for use with quantmod. Essentially a simple wrapper to the underlying Yahoo! Japan finance site's historical data download.
The string ‘YJ’ will be prepended to the Symbols
because
Japanese ticker symbols usually start with a number and it is cumbersome
to use variable names that start with a number in the R environment.
It is recommended to prepend the ticker symbols with ‘YJ’ yourself
if you use setSymbolLookup
. That will make it possible for the main
getSymbols
function to find the symbols in the lookup table.
A call to getSymbols.yahooj will load into the specified
environment one object for each
Symbol
specified, with class defined
by return.class
. Presently this may be ts
,
zoo
, xts
, or timeSeries
.
In the case of xts objects, the indexing will be by Date. This
can be altered with the index.class
argument. See
indexClass
for more information on changing index classes.
Wouter Thielen
Yahoo! Japan Finance: https://finance.yahoo.co.jp
## Not run: # All 4 getSymbols calls return the same # Sony (6758.T) OHLC to the global environment # The last example is what NOT to do! ## Method #1 getSymbols('6758.T',src='yahooj') ## Method #2 getSymbols('YJ6758.T',src='yahooj') ## Method #3 setDefaults(getSymbols,src='yahooj') # OR setSymbolLookup(YJ6758.T='yahooj') getSymbols('YJ6758.T') ######################################### ## NOT RECOMMENDED!!! ######################################### ## Method #4 getSymbols.yahooj('6758.T',env=globalenv()) ## End(Not run)
## Not run: # All 4 getSymbols calls return the same # Sony (6758.T) OHLC to the global environment # The last example is what NOT to do! ## Method #1 getSymbols('6758.T',src='yahooj') ## Method #2 getSymbols('YJ6758.T',src='yahooj') ## Method #3 setDefaults(getSymbols,src='yahooj') # OR setSymbolLookup(YJ6758.T='yahooj') getSymbols('YJ6758.T') ######################################### ## NOT RECOMMENDED!!! ######################################### ## Method #4 getSymbols.yahooj('6758.T',env=globalenv()) ## End(Not run)
A set of functions to check for appropriate OHLC and HLC column names within a data object, as well as the availability and position of those columns.
is.OHLC(x) has.OHLC(x, which = FALSE) is.OHLCV(x) has.OHLCV(x, which = FALSE) is.HLC(x) has.HLC(x, which = FALSE) is.HL(x) has.HL(x, which = FALSE) has.Op(x, which = FALSE) has.Hi(x, which = FALSE) has.Lo(x, which = FALSE) has.Cl(x, which = FALSE) has.Vo(x, which = FALSE) has.Ad(x, which = FALSE) is.BBO(x) is.TBBO(x) has.Ask(x, which = FALSE) has.Bid(x, which = FALSE) has.Price(x, which = FALSE) has.Qty(x, which = FALSE) has.Trade(x, which = FALSE)
is.OHLC(x) has.OHLC(x, which = FALSE) is.OHLCV(x) has.OHLCV(x, which = FALSE) is.HLC(x) has.HLC(x, which = FALSE) is.HL(x) has.HL(x, which = FALSE) has.Op(x, which = FALSE) has.Hi(x, which = FALSE) has.Lo(x, which = FALSE) has.Cl(x, which = FALSE) has.Vo(x, which = FALSE) has.Ad(x, which = FALSE) is.BBO(x) is.TBBO(x) has.Ask(x, which = FALSE) has.Bid(x, which = FALSE) has.Price(x, which = FALSE) has.Qty(x, which = FALSE) has.Trade(x, which = FALSE)
x |
data object |
which |
display position of match |
Mostly used internally by quantmod, they can be useful
for checking whether an object
can be used in OHLC requiring functions like Op
,
OpCl
, etc.
Columns names must contain the full description of data,
that is, Open, High, Low, Close, Volume or Adjusted. Abbreviations
will return FALSE
(or NA
when which = TRUE
). See
quantmod.OHLC
for details of quantmod
naming conventions.
The "is" functions only return TRUE
when the objects has the relevant
column names:
is.HL
: High, Low
is.HLC
: High, Low, Close
is.OHLC
: Open, High, Low, Close
The search for relevant column names is not case sensitive. Any additional columns in the object does not affect the return value.
A logical value indicating success or failure by default.
If which = TRUE
, a numeric value representing the column position
will be returned.
is.OHLC
, is.HL
, and is.HLC
return a single logical value,
either TRUE
or FALSE
.
Jeffrey A. Ryan
quantmod.OHLC
,OHLC.Transformations
## Not run: getSymbols("YHOO") is.OHLC(YHOO) has.OHLC(YHOO) has.Ad(YHOO) ## End(Not run)
## Not run: getSymbols("YHOO") is.OHLC(YHOO) has.OHLC(YHOO) has.Ad(YHOO) ## End(Not run)
Test if object is of type quantmod
or
quantmodResults
.
is.quantmod(x) is.quantmodResults(x)
is.quantmod(x) is.quantmodResults(x)
x |
object to test |
Boolean TRUE or FALSE
Jeffrey A. Ryan
Create a lagged series from data, with NA
used to fill.
Lag(x, k = 1) ## S3 method for class 'quantmod.OHLC' Lag(x, k = 1) ## S3 method for class 'zoo' Lag(x, k = 1) ## S3 method for class 'data.frame' Lag(x, k = 1) ## S3 method for class 'numeric' Lag(x, k = 1)
Lag(x, k = 1) ## S3 method for class 'quantmod.OHLC' Lag(x, k = 1) ## S3 method for class 'zoo' Lag(x, k = 1) ## S3 method for class 'data.frame' Lag(x, k = 1) ## S3 method for class 'numeric' Lag(x, k = 1)
x |
vector or series to be lagged |
k |
periods to lag. |
Shift series k-periods down, prepending NA
s to front
of series.
Specifically designed to handle quantmod.OHLC
and
zoo
series within the quantmod
workflow.
If no S3 method is found, a call to lag
in base
is made.
The original x
prepended with k
NA
s
and missing the trailing k
values.
The returned series maintains the number of obs. of the original.
This function differs from lag
by returning
the original series modified, as opposed to simply changing
the time series properties. It differs from the like
named Lag
in the Hmisc as it deals primarily
with time-series like objects.
It is important to realize that if there is no applicable
method for Lag
, the value returned will be from
lag
in base. That is, coerced to 'ts'
if necessary, and subsequently shifted.
Jeffrey A. Ryan
Stock.Close <- c(102.12,102.62,100.12,103.00,103.87,103.12,105.12) Close.Dates <- as.Date(c(10660,10661,10662,10665,10666,10667,10668),origin="1970-01-01") Stock.Close <- zoo(Stock.Close,Close.Dates) Lag(Stock.Close) #lag by 1 period Lag(Stock.Close,k=1) #same Lag(Stock.Close,k=1:3) #lag 1,2 and 3 periods
Stock.Close <- c(102.12,102.62,100.12,103.00,103.87,103.12,105.12) Close.Dates <- as.Date(c(10660,10661,10662,10665,10666,10667,10668),origin="1970-01-01") Stock.Close <- zoo(Stock.Close,Close.Dates) Lag(Stock.Close) #lag by 1 period Lag(Stock.Close,k=1) #same Lag(Stock.Close,k=1:3) #lag 1,2 and 3 periods
Extract from a quantmod
object the
dataset created for use in modelling.
specifyModel creates a zoo
object for
use in subsequent workflow stages (
buildModel
,tradeModel
) that
combines all model inputs, from a variety
of sources, into one model frame.
modelData
returns this object.
modelData(x, data.window = NULL, exclude.training = FALSE)
modelData(x, data.window = NULL, exclude.training = FALSE)
x |
a |
data.window |
a character vector of subset start and end dates to return |
exclude.training |
remove training period |
When a model is created by specifyModel
, it
is attached to the returned object. One of the
slots of this S4 class is model.data
.
an object of class zoo
containing all
transformations to data specified in
specifyModel
.
Jeffrey A. Ryan
## Not run: m <- specifyModel(Next(OpCl(SPY)) ~ Cl(SPY) + OpHi(SPY) + Lag(Cl(SPY))) modelData(m) ## End(Not run)
## Not run: m <- specifyModel(Next(OpCl(SPY)) ~ Cl(SPY) + OpHi(SPY) + Lag(Cl(SPY))) modelData(m) ## End(Not run)
Extract model signal object from quantmodResults object
as an object of class zoo
.
modelSignal(x)
modelSignal(x)
x |
object of class |
For use after a call to tradeModel
to extract the generated
signal of a given quantmod
model. Normally this would
not need to be called by the end user unless he was manually
post processing the trade results.
A zoo
object indexed by signal dates.
Jeffrey A. Ryan
Functions to assist in the creation of indicators or content to be drawn on plots produced by chartSeries.
addTA(ta, order = NULL, on = NA, legend = "auto", yrange = NULL, ...) newTA(FUN, preFUN, postFUN, on = NA, yrange = NULL, legend.name, fdots = TRUE, cdots = TRUE, data.at = 1, ...)
addTA(ta, order = NULL, on = NA, legend = "auto", yrange = NULL, ...) newTA(FUN, preFUN, postFUN, on = NA, yrange = NULL, legend.name, fdots = TRUE, cdots = TRUE, data.at = 1, ...)
ta |
data to be plotted |
order |
which should the columns (if > 1) be plotted |
legend |
what custom legend text should be added to the chart. |
FUN |
Main filter function name - as a symbol |
preFUN |
Pre-filter transformation or extraction function |
postFUN |
Post-filter transformation or extraction function |
on |
where to draw |
yrange |
length 2 vector of y-axis range |
legend.name |
optional legend heading, automatically derived otherwise |
fdots |
should any ... be included in the main filter call |
cdots |
should any ... be included in the resultant function object.
|
data.at |
which arguement to the main filter function is for data. |
... |
any additonal graphical parameters/default to be included. |
Both addTA
and newTA
can be used to
dynamically add custom content to a displayed chart.
addTA
takes a series of values, either in
a form coercible to xts
or of the same length as
the charted series has rows, and displays the results in
either a new TA sub-window, or over/underlayed on
the main price chart. If the object can be coerced to
xts
, the time values present must only be within
the original series time-range. Internally a merge
of dates occurs and will allow for the plotting
of discontinuous series.
The order
argument allows for multiple column
data to be plotted in an order that makes the most visual
sense.
Specifying a legend
will override the standard
parsing of the addTA call to attempt a guess at a suitable
title for the sub-chart. Specifying this will cause the standard
last value to not be printed.
The ... arg to addTA
is used to set graphical parameters
interpretable by lines
.
newTA
acts as more of a skeleton function, taking
functions as arguments, as well as charting parameters,
and returns a function that can be called in the same
manner as the built-in TA tools, such as addRSI
and
addMACD
. Essentially a dynamic code generator
that allows for highly customizable chart tools with
minimal (possibly zero) coding. It is also possible
to modify the resultant code to further change behavior.
To create a new TA function with newTA
certain arguments
must be specified.
The FUN
argument is a function symbol (or coercible to such)
that is the primary filter to be used on the core-data of a chartSeries
chart. This can be like most of the functions
within the TTR package — e.g. RSI or EMA. The resultant object
of the function call will be equal to calling the function
on the original data passed into the chartSeries function that created the
chart. It should be coercible to a matrix object, of one or more
columns of output. By default all columns of output will be added to the chart,
unless suppressed by passing the appropriately positioned type='n'
as
the ... arg. Note that this will not suppress the labels added to the chart.
The preFUN
argument will be called on the main chart's data prior
to passing it to FUN. This must be a function symbol or a character
string of the name function to be called.
The postFUN
argument will be called on the resultant data
returned from the FUN
filter. This is useful for extracting
the relevant data from the returned filter data. Like preFUN
it must be a function symbol or a character string of the name
of the function to be called.
The yrange
argument is used to provide a custom
scale to the y-axis. If NULL
the min and
max of the data to be plotted will be used for the y-axis
range.
The on
is used to identify which subchart to add the
graphic to. By default, on=NA
will draw the series
in a new subchart below the last indicator. Setting this
to either a positive or negative value will allow for
the series to be super-imposed on, or under, the (sub)chart
specified, respectively. A value of 1 refers to the main chart, and at present
is the only location supported.
legend.name
will change the main label for a new plot.
fdots
and cdots
enable inclusion or suppression
of the ... within the resulting TA code's call to FUN
,
or the argument list of the new TA function, respectively.
In order to facilitate user-specified graphical
parameters it is usually desireable to not impose
artificial limits on the end-user
with constraints on types of parameters available.
By default the new TA function will include the dots
argument, and the internal FUN call will keep all arguments, including
the dots. This may pose issues if the internal function then
passes those ... arguments to a function that can't handle them.
The final argument is data.at
which is the position
in the FUN
argument list which expects the data
to be passed in at. This default to the sensible
first position, though can be changed at the time of creation
by setting this argument to the required value.
While the above functions are usually sufficient
to construct very pleasing graphical additions to
a chart, it may be necessary to modify by-hand
the code produced. This can be accomplished by
dumping the function to a file, or using fix
on it during an interactive session.
Another item of note, with respect to newTA
is the
naming of the main legend label. Following
addTA convention, the first ‘add’ is stripped
from the function name, and the rest of the call's
name is used as the label. This can be overridden
by specifying legend.name
in the construction
of the new TA call, or by passing legend
into
the new TA function. Subtle differences exist, with
the former being the preferred solution.
While both functions can be used to build new indicators without any understanding of the internal chartSeries process, it may be beneficial in more complex cases to have a knowledge of the multi-step process involved in creating a chart via chartSeries.
to be added...
addTA
will invisibly return an S4 object of
class chobTA
. If this function is called
interactively, the chobTA
object will be
evaluated and added to the current chart.
newTA
will return a function object that
can either be assigned or evaluated. Evaluating
this function will follow the logic of any standard
addTA-style call, returning invisibly a chobTA
object, or adding to the chart.
Both interfaces are meant to fascilitate custom
chart additions. addTA
is for
adding any arbitrary series to a chart, where-as
newTA
works with the underlying series with
the main chart object. The latter also
acts as a dynamic TA skeleton generation tool
to help develop reusable TA generation code
for use on any chart.
Jeffrey A. Ryan
chartSeries
,
TA
,
chob
,
chobTA
## Not run: getSymbols('SBUX') barChart(SBUX) addTA(EMA(Cl(SBUX)), on=1, col=6) addTA(OpCl(SBUX), col=4, type='b', lwd=2) # create new EMA TA function newEMA <- newTA(EMA, Cl, on=1, col=7) newEMA() newEMA(on=NA, col=5) ## End(Not run)
## Not run: getSymbols('SBUX') barChart(SBUX) addTA(EMA(Cl(SBUX)), on=1, col=6) addTA(OpCl(SBUX), col=4, type='b', lwd=2) # create new EMA TA function newEMA <- newTA(EMA, Cl, on=1, col=7) newEMA() newEMA(on=NA, col=5) ## End(Not run)
Create a new series with all values advanced forward one period.
The value of period 1, becomes the value at period 2,
value at 2 becomes the original value at 3, etc. The opposite
of Lag
. NA
is used to fill.
Next(x, k = 1) ## S3 method for class 'quantmod.OHLC' Next(x,k=1) ## S3 method for class 'zoo' Next(x,k=1) ## S3 method for class 'data.frame' Next(x,k=1) ## S3 method for class 'numeric' Next(x,k=1)
Next(x, k = 1) ## S3 method for class 'quantmod.OHLC' Next(x,k=1) ## S3 method for class 'zoo' Next(x,k=1) ## S3 method for class 'data.frame' Next(x,k=1) ## S3 method for class 'numeric' Next(x,k=1)
x |
vector or series to be advanced |
k |
periods to advance |
Shift series k-periods up, appending NA
s to end of series.
Specifically designed to handle quantmod.OHLC
and
zoo
series within the quantmod workflow.
If no S3 method is found, a call to lag
in base is made,
with the indexing reversed to shift the time series forward.
The original x
appended with k
NA
s and
missing the leading k
values.
The returned series maintains the number of obs. of the original.
Unlike Lag
, only one value for k
is allowed.
This function's purpose is to get the “next” value of
the data you hope to forecast, e.g. a stock's closing value
at t+1. Specifically to be used within
the quantmod framework of specifyModel
, as a
functional wrapper to the LHS of the model equation.
It is not magic - and thus will not get tomorrow's values...
Jeffrey A. Ryan
Stock.Close <- c(102.12,102.62,100.12,103.00,103.87,103.12,105.12) Close.Dates <- as.Date(c(10660,10661,10662,10665,10666,10667,10668),origin="1970-01-01") Stock.Close <- zoo(Stock.Close,Close.Dates) Next(Stock.Close) #one period ahead Next(Stock.Close,k=1) #same merge(Next(Stock.Close),Stock.Close) ## Not run: # a simple way to build a model of next days # IBM close, given todays. Technically both # methods are equal, though the former is seen # as more intuitive...ymmv specifyModel(Next(Cl(IBM)) ~ Cl(IBM)) specifyModel(Cl(IBM) ~ Lag(Cl(IBM))) ## End(Not run)
Stock.Close <- c(102.12,102.62,100.12,103.00,103.87,103.12,105.12) Close.Dates <- as.Date(c(10660,10661,10662,10665,10666,10667,10668),origin="1970-01-01") Stock.Close <- zoo(Stock.Close,Close.Dates) Next(Stock.Close) #one period ahead Next(Stock.Close,k=1) #same merge(Next(Stock.Close),Stock.Close) ## Not run: # a simple way to build a model of next days # IBM close, given todays. Technically both # methods are equal, though the former is seen # as more intuitive...ymmv specifyModel(Next(Cl(IBM)) ~ Cl(IBM)) specifyModel(Cl(IBM) ~ Lag(Cl(IBM))) ## End(Not run)
Extract (transformed) data from a suitable OHLC object.
Column names must contain the
complete description - either “Open”, “High”,
“Low”, “Close”,
“Volume”, or “Adjusted” - though may
also contain additional characters. This is the default for objects
returned from most getSymbols
calls.
In the case of functions consisting of combined
Op, Hi, Lo, Cl (e.g. ClCl(x)
) the one period
transformation will be applied.
For example, to return the Open to Close of a
object it is
possible to call OpCl(x)
. If multiple periods
are desired a call to the function Delt
is
necessary.
seriesLo
and seriesHi
will return the
low and high, respectively, of a given series.
seriesAccel
, seriesDecel
, seriesIncr
,
and seriesDecr
, return a vector of logicals
indicating if the series is accellerating, decellerating,
increasing, or decreasing. This is managed by diff
,
which provides NA fill and suitable re-indexing. These
are here to make trade rules easier to read.
HL
extracts the High and Low columns.
HLC
extracts the High, Low, and Close columns.
OHLC
extracts the Open, High, Low, and Close columns.
These functions are merely to speed the model specification process. All columns may also be extracted through standard R methods.
Assignment will not work at present.
getPrice
will attempt to extract price column(s) from a time series,
using sensible defaults. Additionally, the user may provide by symbol and price
preference.
Op(x) Hi(x) Lo(x) Cl(x) Vo(x) Ad(x) seriesHi(x) seriesLo(x) seriesIncr(x, thresh=0, diff.=1L) seriesDecr(x, thresh=0, diff.=1L) OpCl(x) ClCl(x) ClOp(x) HiCl(x) LoCl(x) LoHi(x) OpHi(x) OpLo(x) OpOp(x) HL(x) HLC(x) OHLC(x) OHLCV(x) getPrice(x, symbol=NULL, prefer=NULL, ...)
Op(x) Hi(x) Lo(x) Cl(x) Vo(x) Ad(x) seriesHi(x) seriesLo(x) seriesIncr(x, thresh=0, diff.=1L) seriesDecr(x, thresh=0, diff.=1L) OpCl(x) ClCl(x) ClOp(x) HiCl(x) LoCl(x) LoHi(x) OpHi(x) OpLo(x) OpOp(x) HL(x) HLC(x) OHLC(x) OHLCV(x) getPrice(x, symbol=NULL, prefer=NULL, ...)
x |
A data object with columns containing data to be extracted. |
thresh |
noise threshold (seriesIncr/seriesDecr) |
diff. |
differencing (seriesIncr/seriesDecr) |
symbol |
text string containing the symbol to extract |
prefer |
price type preference (see Details) |
... |
not currently used |
Internally, the code uses grep to locate the appropriate columns. Therefore it is necessary to use inputs with column names matching the requirements in the description section, though the exact naming convention is not as important.
prefer
can be used with getPrice
to extract many commonly used
financial time series prices descriptions (e.g. open, high, low, close, bid,
ask/offer, midpoint, trade, price). If the value of prefer
does not
match one of the currently supported types, it will be matched against the
object column names using grep
.
Returns an object of the same class as the original
series, with the appropriately column names
if applicable and/or possible. The only exceptions are for quantmod.OHLC
objects which will be returned as zoo
objects, and calls to
seriesLo
and seriesHi
which may return a numeric
value instead of the original object type.
Jeffrey A. Ryan
## Not run: getSymbols('IBM',src='yahoo') Ad(IBM) Cl(IBM) ClCl(IBM) seriesHi(IBM) seriesHi(Lo(IBM)) removeSymbols('IBM') ## End(Not run)
## Not run: getSymbols('IBM',src='yahoo') Ad(IBM) Cl(IBM) ClCl(IBM) seriesHi(IBM) seriesHi(Lo(IBM)) removeSymbols('IBM') ## End(Not run)
Return the index of the contract expiration date. The third Friday of the month for options, the last third Friday of the quarter for futures.
options.expiry(x) futures.expiry(x)
options.expiry(x) futures.expiry(x)
x |
a time-indexed zoo object |
Designed to be used within a charting context via addExpiry
, the values returned
are based on the description above. Exceptions, though rare, are not accounted for.
A numeric vector of values to index on.
There is currently no accounting for holidays that may interfere with the general rule. Additionally all efforts have been focused on US equity and futures markets.
Jeffrey A. Ryan
~put references to the literature/web site here ~
## Not run: getSymbols("AAPL") options.expiry(AAPL) futures.expiry(AAPL) AAPL[options.expiry(AAPL)] ## End(Not run)
## Not run: getSymbols("AAPL") options.expiry(AAPL) futures.expiry(AAPL) AAPL[options.expiry(AAPL)] ## End(Not run)
Given a set of prices, return periodic returns.
periodReturn(x, period='monthly', subset=NULL, type='arithmetic', leading=TRUE, ...) dailyReturn(x, subset=NULL, type='arithmetic', leading=TRUE, ...) weeklyReturn(x, subset=NULL, type='arithmetic', leading=TRUE, ...) monthlyReturn(x, subset=NULL, type='arithmetic', leading=TRUE, ...) quarterlyReturn(x, subset=NULL, type='arithmetic', leading=TRUE, ...) annualReturn(x, subset=NULL, type='arithmetic', leading=TRUE, ...) yearlyReturn(x, subset=NULL, type='arithmetic', leading=TRUE, ...) allReturns(x, subset=NULL, type='arithmetic', leading=TRUE)
periodReturn(x, period='monthly', subset=NULL, type='arithmetic', leading=TRUE, ...) dailyReturn(x, subset=NULL, type='arithmetic', leading=TRUE, ...) weeklyReturn(x, subset=NULL, type='arithmetic', leading=TRUE, ...) monthlyReturn(x, subset=NULL, type='arithmetic', leading=TRUE, ...) quarterlyReturn(x, subset=NULL, type='arithmetic', leading=TRUE, ...) annualReturn(x, subset=NULL, type='arithmetic', leading=TRUE, ...) yearlyReturn(x, subset=NULL, type='arithmetic', leading=TRUE, ...) allReturns(x, subset=NULL, type='arithmetic', leading=TRUE)
x |
object of state prices, or an OHLC type object |
period |
character string indicating time period. Valid entries are ‘daily’, ‘weekly’, ‘monthly’, ‘quarterly’, ‘yearly’. All are accessible from wrapper functions described below. Defaults to monthly returns (same as monthlyReturn) |
subset |
an xts/ISO8601 style subset string |
type |
type of returns: arithmetic (discrete) or log (continuous) |
leading |
should incomplete leading period returns be returned |
... |
passed along to to.period |
periodReturn
is the underlying function for wrappers:
allReturns:
calculate all available return periods
dailyReturn:
calculate daily returns
weeklyReturn:
calculate weekly returns
monthlyReturn:
calculate monthly returns
quarterlyReturn:
calculate quarterly returns
annualReturn:
calculate annual returns
Returns object of the class that was originally passed in,
with the possible exception of monthly and quarterly return
indicies being changed to class yearmon
and yearqtr
where available. This can be overridden with the indexAt
argument passed in the ... to the to.period
function.
By default, if subset
is NULL, the full dataset will
be used.
Attempts are made to re-convert the resultant series to its original
class, if supported by the xts package. At present, objects inheriting
from the ‘ts’ class are returned as xts
objects. This
is to make the results more visually appealling and informative. All
xts
objects can be converted to class ts
with
as.ts
if that is desirable.
The first and final row of returned object will have the period return to last date,
i.e. this week/month/quarter/year return to date even if the start/end is not the start/end
of the period. Leading period calculations can be suppressed by setting leading=FALSE
.
Jeffrey A. Ryan
## Not run: getSymbols('QQQ',src='yahoo') allReturns(QQQ) # returns all periods periodReturn(QQQ,period='yearly',subset='2003::') # returns years 2003 to present periodReturn(QQQ,period='yearly',subset='2003') # returns year 2003 rm(QQQ) ## End(Not run)
## Not run: getSymbols('QQQ',src='yahoo') allReturns(QQQ) # returns all periods periodReturn(QQQ,period='yearly',subset='2003::') # returns years 2003 to present periodReturn(QQQ,period='yearly',subset='2003') # returns year 2003 rm(QQQ) ## End(Not run)
Objects of class quantmod
help to
manage the process of model building within the quantmod
package. Created automatically by a call to specifyModel
they carry information to be used by a variety of accessor
functions and methods.
Objects can be created by calls of the form new("quantmod", ...)
.
Normally objects are created as a result of a call to specifyModel
.
model.id
:Object of class "character"
~~
model.spec
:Object of class "formula"
~~
model.formula
:Object of class "formula"
~~
model.target
:Object of class "character"
~~
model.inputs
:Object of class "character"
~~
build.inputs
:Object of class "character"
~~
symbols
:Object of class "character"
~~
product
:Object of class "character"
~~
price.levels
:Object of class "zoo"
~~
training.data
:Object of class "Date"
~~
build.date
:Object of class "Date"
~~
fitted.model
:Object of class "ANY"
~~
model.data
:Object of class "zoo"
~~
quantmod.version
:Object of class "numeric"
~~
No methods defined with class "quantmod" in the signature.
Jeffrey A. Ryan
showClass("quantmod")
showClass("quantmod")
Coerce an object with the apporpriate columns to class
quantmod.OHLC
, which extends zoo.
as.quantmod.OHLC(x, col.names = c("Open", "High", "Low", "Close", "Volume", "Adjusted"), name = NULL, ...)
as.quantmod.OHLC(x, col.names = c("Open", "High", "Low", "Close", "Volume", "Adjusted"), name = NULL, ...)
x |
object of class |
col.names |
suffix for columns |
name |
name to attach unique column suffixes to, defaults to the object name |
... |
additional arguments (unused) |
quantmod.OHLC
is actually just a renaming of an object
of class zoo
, with the convention of NAME.Open, NAME.High, ...
for the column names.
Additionally methods may be written to handle or check for the above conditions within other functions - as is the case within the quantmod package.
An object of class c('quantmod.OHLC','zoo')
Jeffrey A. Ryan
OHLC.Transformations
, getSymbols
Save selected chart to an external file.
saveChart(.type = "pdf", ..., dev = dev.cur())
saveChart(.type = "pdf", ..., dev = dev.cur())
.type |
type of export. See Details. |
... |
arguments to pass to device |
dev |
which device should be exported |
This function wraps the base R function pdf
,
postscript
, png
, jpeg
, and bitmap
.
The .type
argument must specify which device
driver is desired.
The currently active device is used if dev
is
missing. The result is an exact copy (within the device limits)
of the chart specified.
The name of the resultant file is derived from the name of the chart,
with the appropriate extension appended. (from .type
). Specifying
the appropriate device file/filename will override this name.
The caller may specify any parameters that are valid for the device called. Internally, effort is made to match the dimensions of the device being used to create the output file. User supplied dimensions will override this internal calculation.
A file in the current directory (default) matching the type of the output requested.
As this uses do.call
internally to create the new output device,
any device that makes use of R conventions should be acceptable as a
value for .type
Jeffrey A. Ryan
pdf
png
jpeg
bitmap
postscript
## Not run: getSymbols("AAPL") chartSeries(AAPL) require(TTR) addBBands() saveChart('pdf') saveChart('pdf', width=13) ## End(Not run)
## Not run: getSymbols("AAPL") chartSeries(AAPL) require(TTR) addBBands() saveChart('pdf') saveChart('pdf', width=13) ## End(Not run)
Create and manage Symbol defaults lookup table within
R session for use in getSymbols
calls.
setSymbolLookup(...) getSymbolLookup(Symbols=NULL) saveSymbolLookup(file,dir="") loadSymbolLookup(file,dir="")
setSymbolLookup(...) getSymbolLookup(Symbols=NULL) saveSymbolLookup(file,dir="") loadSymbolLookup(file,dir="")
... |
name=value pairs for symbol defaults |
Symbols |
name of symbol(s) |
file |
filename |
dir |
directory of filename |
Use of these functions allows the user to specify
a set of default parameters for each Symbol
to be
loaded.
Different sources (e.g. yahoo, MySQL, csv),
can be specified for each Symbol of
interest. The sources must be valid
getSymbols
methods - see getSymbols
for details on which methods are available, as well as
how to add additional methods.
The argument list to setSymbolLookup
is
simply the unquoted name of the Symbol
matched
to the desired default source, or list of Symbol
specific parameters.
For example, to signify that the stock data for
Sun Microsystems (JAVA) should be downloaded from
Yahoo! Finance, one would call
setSymbolLookup(JAVA='yahoo')
or setSymbolLookup(JAVA=list(src='yahoo'))
It is also possible to specify additional,
possibly source specific, lookup details on
a per symbol basis. These include an alternate
naming convention (useful for sites like Yahoo! where
certain non-traded symbols are prepended with a caret,
or more correctly a curcumflex accent. In that case one would
specify setSymbolLookup(DJI=list(name="^DJI",src="yahoo"))
)
as well as passed parameters like dbname
and
password
for database sources. See the
specific getSymbols function related to the source
in question for more details of each implementation.
If a single named list is passed into the function without naming the list as a parameter, the names of this list will be presumed to be symbol names to be added to the current list of symbols.
All changes are made to the current list, and will
persist only until the end of the session. To always
use the same defaults it is necessary to call
setSymbolLookup
with the appropriate
parameters from a startup file (e.g.
.Rprofile) or to use saveSymbolLookup
and
loadSymbolLookup
to save and restore lookup
tables.
To unset a specific Symbol's defaults, simply assign
NULL
to the Symbol.
Called for its side effects, the function changes the
options
value for the specified Symbol
through a call to options(getSymbols.sources=...)
Changes are NOT persistent across sessions, as the table is stored in the session options by default.
This may change to allow for an easier to manage process, as for now it is designed to minimize the clutter created during a typical session.
Jeffrey A. Ryan
setSymbolLookup(QQQ='yahoo',DIA='MySQL') getSymbolLookup('QQQ') getSymbolLookup(c('QQQ','DIA')) ## Not run: ## Will download QQQ from yahoo ## and load DIA from MySQL getSymbols(c('QQQ','DIA')) ## End(Not run) ## Use something like this to always retrieve ## from the same source .First <- function() { require(quantmod,quietly=TRUE) quantmod::setSymbolLookup(JAVA="MySQL") } ## OR ## Not run: saveSymbolLookup() loadSymbolLookup() ## End(Not run)
setSymbolLookup(QQQ='yahoo',DIA='MySQL') getSymbolLookup('QQQ') getSymbolLookup(c('QQQ','DIA')) ## Not run: ## Will download QQQ from yahoo ## and load DIA from MySQL getSymbols(c('QQQ','DIA')) ## End(Not run) ## Use something like this to always retrieve ## from the same source .First <- function() { require(quantmod,quietly=TRUE) quantmod::setSymbolLookup(JAVA="MySQL") } ## OR ## Not run: saveSymbolLookup() loadSymbolLookup() ## End(Not run)
Used to manage the TA arguments used inside chartSeries
calls.
setTA(type = c("chartSeries", "barChart", "candleChart")) listTA(dev)
setTA(type = c("chartSeries", "barChart", "candleChart")) listTA(dev)
type |
the function to apply defaults TAs to |
dev |
the device to display TA arguments for |
setTA
and unsetTA
provide a simple
way to reuse the same TA arguments for multiple
charts. By default all charting functions will be
set to use the current chart's defaults.
It is important to note that the current device will be used to extract the list of TA arguments to apply. This is done with a call to listTA internally, and followed by calls to setDefaults of the appropriate functions.
An additional way to set default TA arguments for subsequent
charts is via setDefaults
. See the examples.
Called for its side-effect of setting the default TA arguments to quantmod's charting functions.
Using setDefaults
directly will require the vector
of default TA calls to be wrapped in a call to
substitute
to prevent unintended evaluations; OR
a call to listTA
to get the present TA arguments. This last
approach is what setTA
wraps.
Jeffrey A. Ryan
## Not run: listTA() setTA() # a longer way to accomplish the same setDefaults(chartSeries,TA=listTA()) setDefaults(barCart,TA=listTA()) setDefaults(candleChart,TA=listTA()) setDefaults(chartSeries,TA=substitute(c(addVo(),addBBands()))) ## End(Not run)
## Not run: listTA() setTA() # a longer way to accomplish the same setDefaults(chartSeries,TA=listTA()) setDefaults(barCart,TA=listTA()) setDefaults(candleChart,TA=listTA()) setDefaults(chartSeries,TA=substitute(c(addVo(),addBBands()))) ## End(Not run)
Create a single reusable model specification for subsequent buildModel calls.
An object of class quantmod
is created that can be then be reused with different
modelling methods and parameters. No data frame is specified, as data is retrieved
from potentially multiple environments, and internal calls to getSymbols.
specifyModel(formula, na.rm=TRUE)
specifyModel(formula, na.rm=TRUE)
formula |
an object of class |
na.rm |
remove all incomplete rows. |
Models are specified through the standard formula mechanism.
As financial models may include a
variety of financial and economic indicators,
each differing in source, frequency, and/or class,
a single mechanism to specify sources is
included within a call to specifyModel.
See getModelData
for details of
how this process works.
Currently, objects of class quantmod.OHLC
,
zoo
and ts
are supported within the
model formula.
All symbols are first retrieved from the global environment, without inheritence.
If an object is not found in the global environment, it is added to a
list of objects to load through the getSymbols
function. getSymbols retrieves each
object specified by using information
as to its location specified apriori
via setDefaults
or setSymbolLookup
.
Internally all data is coerced to zoo
,data.frame
,
or numeric
classes.
Returns an object of class quantmod
.
Use modelData
to extract
full data set as zoo
object.
It is possible to include any supported series in the formula by simply specifying the object's symbol. See *Details* for a list of currently supported classes.
Use getSymbols.skeleton
to create additional
methods of data sourcing, e.g. from a proprietary
data format or currently unimplemented source
(Bloomberg, Oracle).
See getSymbols.MySQL
and getSymbols.yahoo
for examples of adding additional functionality
Jeffrey Ryan
quantmod.com http://www.quantmod.com
getModelData
,getSymbols
,
buildModel
,tradeModel
,formula
setSymbolLookup
## Not run: # if QQQ is not in the Global environment, an attempt will be made # to retrieve it from the source specified with getSymbols.Default specifyModel(Next(OpCl(QQQ)) ~ Lag(OpHi(QQQ),0:3) + Hi(DIA)) ## End(Not run)
## Not run: # if QQQ is not in the Global environment, an attempt will be made # to retrieve it from the source specified with getSymbols.Default specifyModel(Next(OpCl(QQQ)) ~ Lag(OpHi(QQQ),0:3) + Hi(DIA)) ## End(Not run)
Functions to add technical indicators to a chart.
The general mechanism to add technical analysis studies or overlays
to a financial chart created with chartSeries
.
General TA charting tool functions:
addTA
: add data as custom indicator
dropTA
: remove technical indicator
moveTA
: move a technical indicator
swapTA
: swap two technical indicators
Current technical indicators include:
addADX
: add Welles Wilder's Directional Movement Indicator
addATR
: add Average True Range
addAroon
: add Aroon Indicator
addAroonOsc
: add Aroon Oscillator
addBBands
: add Bollinger Bands
addCCI
: add Commodity Channel Index
addCMF
: add Chaiken Money Flow
addChAD
: add Chaiken Accumulation Distribution Line
addChVol
: add Chaiken Volatility
addCMO
: add Chande Momentum Oscillator
addDEMA
: add Double Exponential Moving Average
addDPO
: add Detrended Price Oscillator
addEMA
: add Exponential Moving Average
addEMV
: add Arm's Ease of Movement
addEnvelope
: add Moving Average Envelope
addEVWMA
: add Exponential Volume Weighted Moving Average
addExpiry
: add options or futures expiration lines
addKST
: add Know Sure Thing
addLines
: add line(s)
addMACD
: add Moving Average Convergence Divergence
addMFI
: add Money Flow Index
addMomentum
: add Momentum
addOBV
: add On-Balance Volume
addPoints
: add point(s)
addROC
: add Rate of Change
addRSI
: add Relative Strength Indicator
addSAR
: add Parabolic SAR
addSMA
: add Simple Moving Average
addSMI
: add Stochastic Momentum Index
addTDI
: add Trend Direction Index
addTRIX
: add Triple Smoothed Exponential Oscillator
addVo
: add Volume (if available)
addVolatility
: add volatility
addWMA
: add Weighted Moving Average
addWPR
: add Williams Percent R
addZigZag
: add Zig Zag
addZLEMA
: add ZLEMA
See the individual functions for specific implementation and argument details. Details of the underlying TTR implementations can be found in TTR.
The primary changes between the add*** version of an indicator and the TTR base function is the absense of the data argument in the former.
Notable additions include on
, with.col
.
Called for its side effects, an object to class chobTA
will be returned invisibly. If called from the R command line
the method will draw the appropriate indicator on the current chart.
Calling any of the above methods from within a function or script
will generally require them to be wrapped in a plot
call
as they rely on the context of the call to initiate the actual
charting addition.
Jeffrey A. Ryan
Josh Ulrich - TTR package
Simulated trading of fitted quantmod object. Given a fitted model,
tradeModel calculates the signal generated over a given historical
period, then applies specified trade.rule
to calculate
and return a tradeLog
object. Additional methods can then
be called to evaluate the performance of the model's strategy.
tradeModel(x, signal.threshold = c(0, 0), leverage = 1, return.model = TRUE, plot.model = FALSE, trade.dates = NULL, exclude.training = TRUE, ret.type = c("weeks", "months", "quarters", "years"), ...)
tradeModel(x, signal.threshold = c(0, 0), leverage = 1, return.model = TRUE, plot.model = FALSE, trade.dates = NULL, exclude.training = TRUE, ret.type = c("weeks", "months", "quarters", "years"), ...)
x |
a quantmod object from |
signal.threshold |
a numeric vector describing simple lower and upper thresholds before trade occurs |
leverage |
amount of leverage to apply - currently a constant |
return.model |
should the full model be returned? |
plot.model |
plot the model? |
trade.dates |
specific trade interval - defaults to full dataset |
exclude.training |
exclude the period trained on? |
ret.type |
a table of period returns |
... |
additional parameters needed by the underlying modelling function, if any |
Still highly experimental and changing. The purpose is to apply
a newly contructed model from buildModel
to a new dataset
to investigate the model's trading potential.
At present all parameters are very basic. The near term changes include allowing for a trade.rule argument to allow for a dynamic trade rule given a set of signals. Additional the application of variable leverage and costs will become part of the final structure.
Any suggestions as to inclusions or alterations are appreciated and should be directed to the maintainer of the package.
A quantmodResults object
Jeffrey A. Ryan
## Not run: m <- specifyModel(Next(OpCl(QQQ)) ~ Lag(OpHi(QQQ))) m.built <- buildModel(m,method='rpart',training.per=c('2007-01-01','2007-04-01')) tradeModel(m.built) tradeModel(m.built,leverage=2) ## End(Not run)
## Not run: m <- specifyModel(Next(OpCl(QQQ)) ~ Lag(OpHi(QQQ))) m.built <- buildModel(m,method='rpart',training.per=c('2007-01-01','2007-04-01')) tradeModel(m.built) tradeModel(m.built,leverage=2) ## End(Not run)
Using xts style date subsetting, zoom into or out of the current chart.
zooom(n=1, eps=2) zoomChart(subset, yrange=NULL)
zooom(n=1, eps=2) zoomChart(subset, yrange=NULL)
n |
the number of interactive view changes per call |
eps |
the distance between clicks to be considered a valid subset request |
subset |
a valid subset string |
yrange |
override y-scale |
These function allow for viewing of specific
areas of a chart produced by chartSeries
by simply specifying the dates of interest
zooom
is an interactive chart version
of zoomChart
which utilizes the standard
R device interaction tool locator
to
estimate the subset desired. This estimate is
then passed to zoomChart for actual redrawing.
At present it is
quite experimental in its interface and arguments.
Its usage entails a call to zooom()
followed
by the selection of the leftmost and rightmost points
desired in the newly zoomed chart. This selection
is accomplished by the user left-clicking each extreme
point. Two click are required to determine the level
of zooming. Double clicking will reset the chart to
the full data range. The arguments and internal
working of this function are likely to change dramatically
in future releases, though its use will likely remain.
Standard format for the subset
argument
is the same as the subsetting for xts objects,
which is how the data is stored internally for
rendering.
Calling zoomChart
with no arguments (NULL)
resets the chart to the original data.
Examples include '2007' for all of the year 2007,
'2007::2008' for years 2007 through 2008, '::2007'
for all data from the beginning of the set to the
end of 2007, '2007::' all data from the beginning of
2007 through the end of the data. For specifics
regarding the level of detail and internal interpretation
please see [.xts
This function is called for its side effect - notably changing the perspective of the current chart, and changing its formal subset level. The underlying data attached to the chart is left unchanged.
Jeffrey A. Ryan
## Not run: data(sample_matrix) chartSeries(sample_matrix) zoomChart('2007-04::') zoomChart() zooom() # interactive example ## End(Not run)
## Not run: data(sample_matrix) chartSeries(sample_matrix) zoomChart('2007-04::') zoomChart() zooom() # interactive example ## End(Not run)