Transcription of quantmod
1 QuantmodJune 9, 2008 TypePackageTitleQuantitative Financial Modelling A. RyanDependsxts(>= ),zoo,DefaultsSuggestsDBI,RMySQL,RSQLite ,TTR(>= ),fSeries,itsMaintainerJeffrey A. Ryan build, trade, and analyse quantitative financial trading strategiesLazyLoadyesLicenseGPL-3 documented:Delt ..2 Lag ..3 Next ..6TA ..8addADX ..10addBBands ..11addExpiry ..12addMA ..12addMACD ..14addROC ..15addRSI ..16addSAR ..17addSMI ..18addVo ..1912 DeltaddWPR ..19buildData ..20buildModel ..21chartSeries ..22chartTheme ..25chob-class ..27chobTA-class ..28fittedModel ..29getDividends ..31getFX ..32getFinancials ..33getMetals ..35getModelData ..36getQuote ..39getSymbols ..53internal- quantmod ..55modelData ..55modelSignal ..56newTA ..59periodReturn ..61quantmod-class ..62quantmod-package ..64setSymbolLookup ..65setTA ..67specifyModel ..68tradeModel ..69zoomChart ..71 Index73 DeltCalculate Percent ChangeDescriptionCalculate the k-period percent difference within one series, or between two series.
2 Primarily used tocalculate the percent change from one period to another of a given series, or to calculate the percentdifference between two series over the full (x1, x2 = NULL, k = 0, type = c("arithmetic", "log"))Argumentsx1m x 1vectorx2m x 1vectorkchange overk-periods. default k=1 when x2 is of difference. log or arithmetic (defauly).DetailsWhen called with onlyx1, the one period percent change of the series is returned by this happens by copying x1 to x2. A two period difference would be specified withk= called with bothx1andx2, the difference between the two is returned. That is, k=0. A oneperiod difference would be specified byk= also be a vector to calculate more than oneperiod at a time. The results will then be an m x length(k)Log differences are used by default: Lag = log(x2(t)/x1(t-k))Arithmetic differences are calculated: Lag = (x2(t) - x1(t-k))/x1(t-k)ValueAn matrix oflength(x1)rows andlength(k) (s)Jeffrey A.
3 RyanSee <- c( , , , , , , ) <- c( , , , , , , )Delt( ) #one period pct. price changeDelt( ,k=1) #sameDelt( ,type='arithmetic') #using arithmetic differencesDelt( , ) #Open to Close pct. changeDelt( , ,k=0:2) #..for 0,1, and 2 periods4 LagLagLag a Time SeriesDescriptionCreate a lagged series from data, withNAused to (x, k = 1)## S3 method for class ' ':Lag(x, k = 1)## S3 method for class 'zoo':Lag(x, k = 1)## S3 method for class ' ':Lag(x, k = 1)## S3 method for class 'numeric':Lag(x, k = 1)Argumentsxvector or series to be laggedkperiods to series k-periods down, prependingNAs to front of designed to within no S3 method is found, a call tolaginbaseis originalxprepended withk NAs and missing the returned series maintains the number of obs. of the function differs fromlagby returning the original series modified, as opposed to simplychanging the time series properties.
4 It differs from the like namedLagin theHmiscas it dealsprimarily with time-series like is important to realize that if there is no applicable method forLag, the value returned will befromlaginbase. That is, coerced to ts if necessary, and subsequently (s)Jeffrey A. RyanNext5 See <- c( , , , , , , ) <- (c(10660,10661,10662,10665,10666,10667,1 0668),origin="1970-01-01") <- zoo( , )Lag( ) #lag by 1 periodLag( ,k=1) #sameLag( ,k=1:3) #lag 1,2 and 3 periodsNextAdvance a Time SeriesDescriptionCreate a new series with all values advanced forward one period. The value of period 1, becomesthe value at period 2, value at 2 becomes the original value at 3, etc. The opposite to (x, k = 1)## S3 method for class ' ':Next(x,k=1)## S3 method for class 'zoo':Next(x,k=1)## S3 method for class ' ':Next(x,k=1)## S3 method for class 'numeric':Next(x,k=1)Argumentsxvector or series to be advancedkperiods to advanceDetailsShift series k-periods up, appendingNAs to end of designed to within no S3 method is found, a call tolaginbaseis made, with the indexing reversed to shift the timeseries originalxappended withk NAs and missing the returned series maintains the number of obs.
5 Of the , only one value forkis function s purpose is to get the next value of the data you hope to forecast, a stock sclosing value at t+1. Specifically to be used within thequantmodframework ofspecifyModel,as a functional wrapper to the LHS of the model is not magic - and thus will not get tomorrow s values..Author(s)Jeffrey A. RyanSee AlsospecifyModel, <- c( , , , , , , ) <- (c(10660,10661,10662,10665,10666,10667,1 0668),origin="1970-01-01") <- zoo( , )Next( ) #one period aheadNext( ,k=1) #samemerge(Next( ), )## 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 (Next(Cl(IBM)) ~ Cl(IBM))specifyModel(Cl(IBM) ~ Lag(Cl(IBM)))## End(Not run) and Transform OHLC Time-Series ColumnsDescriptionExtract (transformed) data from a suitable OHLC object. Column names must contain the completedescription - either Open , High , Low , Close , Volume , or Adjusted - though may alsocontain additional characters.
6 This is the default for objects returned from the case of functions consisting of combined Op, Hi, Lo, Cl ( (x)) the one periodtransformation will be example, to return the Open to Close of a object it is possible to callOpCl(x). If multipleperiods are desired a call to the functionDeltis return the low and high, respectively, of a given the High, Low, and Close the Open, High, Low, and functions are merely to speed the model specification process. All columns may also beextracted through standard R will not work at (x)Hi(x)Lo(x)Cl(x)Vo(x)Ad(x)seriesHi(x)s eriesLo(x)OpCl(x)ClCl(x)HiCl(x)LoCl(x)Lo Hi(x)OpHi(x)OpLo(x)OpOp(x)HLC(x)OHLC(x)A rgumentsxA data object with columns containing data to be , the code uses grep to locate the appropriate columns. Therefore it is necessary to useinputs with column names matching the requirements in the description section, though the exactnaming convention is not as an object of the same class as the original series, with the appropriately column namesif applicable and/or possible.
7 The only exceptions are which willbe returned aszooobjects, and calls toseriesLoandseriesHiwhichmayreturn a numericvalue instead of the original object (s)Jeffrey A. RyanSee AlsospecifyModelExamples## Not run:getSymbols('IBM',src='yahoo')Ad(IBM) Cl(IBM)ClCl(IBM)seriesHi(IBM)seriesHi(Lo (IBM))removeSymbols('IBM')## End(Not run)TAAdd Technical Indicator to ChartDescriptionFunctions to add technical indicators to a general mechanism to add technical analysis studies or overlays to a financial chart marked with a * is via TA charting tool functions:addTAadd data as custom indicatordropTAremove technical indicatormoveTAmove a technical indicatorswapTAswap two technical indicatorsCurrent technical indicators include:addADXadd Welles Wilder s Directional Movement Indicator*addATRadd Average True Range *addBBands:add Bollinger Bands *addCCIadd Commodity Channel Index *addCMFadd Chaiken Money Flow *addCMOadd Chande Momentum Oscillator *addDEMAadd Double Exponential Moving Average *TA9addDPOadd Detrended Price Oscillator *addEMAadd Exponential Moving Average *addEnvelopeadd Moving Average EnvelopeaddEVWMAadd Exponential Volume Weighted Moving Average *addExpiryadd options or futures expiration linesaddLinesadd line(s)addMACD:add Moving Average Convergence Divergence *addMomentumadd Momentum *addPointsadd point(s)addROC:add Rate of Change *addRSIadd Relative Strength Indicator *addSARadd Parabolic SAR *addSMAadd Simple Moving Average *addSMIadd Stochastic Momentum Index *addTRIXadd Triple Smoothed Exponential Oscillator *addVo.
8 Add Volume if availableaddWMAadd Weighted Moving Average *addWPRadd Williams Percent R *addZLEMAadd ZLEMA *See the individual functions for specific implementation and argument details. Details of the under-lying TTR implementations can be found primary changes between the add** version of an indicator and theTTRbase function is theabsense of the data argument in the additions includeon, (deprecated).ValueCalled for its side effects, an object to classchobTAwill be returned invisibly. If called from theRcommand line the method will draw the appropriate indicator on the current any of the above methods from within a function or script will generally require them to bewrapped in aplotcall as they rely on the context of the call to initiate the actual charting (s)Jeffrey A. RyanReferencesJosh Ulrich - TTR package10addADXaddADXAdd Directional Movement IndexDescriptionAdd Directional Movement IndexUsageaddADX(n = 14, maType="EMA", wilder=TRUE)Argumentsnperiods to use for DX calculationmaTypemoving average typewildershould Welles Wilder EMA be used?
9 DetailsSee ADX inTTRfor specific details and ADX indicator will be draw in a new window on the current chart. A chobTA object will bereturned (s)Jeffrey A. RyanReferencessee ADX inTTRwritten by Josh UlrichSee AlsoaddTAExamples## Not run:addADX()## End(Not run)addBBands11addBBandsAdd Bollinger Bands to ChartDescriptionAdd Bollinger Bands to current (n = 20, sd = 2, ma = "SMA", draw = 'bands', on = -1)Argumentsnnumber of moving average periodsmatype of moving average to be usedsdnumber of standard deviationsdrawindicator to draw: bands, percent, or widthonwhich figure area of chart to apply toDetailsThe primary addition to this function call over theTTRversion is in thedrawargument. bands will draw standard Bollinger Bands, percent will draw Bollinger %b and width will draw BolingerBands Width. The last two will be drawn in new figure bollingerBands inTTRfor specific details as to implementation and Bands will be drawn, or scheduled to be drawn, on the current chart.
10 Ifdrawis eitherpercent or width a new figure will be added to the current TA figures chobTA object will be returned (s)Jeffrey A. RyanReferencesSee bollingerBands inTTRwritten by Josh UlrichSee AlsoaddTAExamples## Not run:addBBands()## End(Not run)12addMAaddExpiryAdd Contract Expiration Bars to ChartDescriptionApply options or futures expiration vertical bars to current (type = "options", lty = "dotted")Argumentstypeoptions or futures expirationltytype of lines to drawDetailsSee and inquantmodfor details and lines will be drawn at appropriate dates. A chibTA object will be returned (s)Jeffrey A. RyanSee AlsoaddTAExamples## Not run:addExpiry()## End(Not run)addMAAdd Moving Average to ChartDescriptionAdd one or more moving averages to a (n = 10, on = 1, = Cl, overlay = TRUE, col = "brown")addEMA(n = 10, wilder = FALSE, ratio=NULL, on = 1, = Cl, overlay = TRUE, col = "blue")addWMA(n = 10, wts=1:n, on = 1, = Cl, overlay = TRUE, col = "green")addDEMA(n = 10, on = 1, = Cl, overlay = TRUE, col = "pink")addEVWMA(n = 10, on = 1, = Cl, overlay = TRUE, col = "yellow")addZLEMA(n = 10, ratio=NULL, on = 1, = Cl, overlay = TRUE, col = "red")Argumentsnperiods to average overwilderlogical; use wilder?