library(quantmod)
library(TTR)
options("getSymbols.warning4.0"=FALSE)
getSymbols("YHOO",src="google") # from google finance
getSymbols("GOOG",src="yahoo") # from yahoo finance
head(YHOO)
head(GOOG)
setSymbolLookup(SBUX='google', AAPL='yahoo')
getSymbols(c("SBUX","AAPL"))
head(SBUX)
head(AAPL)
setSymbolLookup(SBUX='yahoo', AAPL='yahoo',YHOO='yahoo',GOOG='yahoo')
getSymbols(c("SBUX","AAPL","YHOO","GOOG"))
barChart(AAPL,theme=chartTheme('white'),TA=c(addVo(),addBBands()),subset='2013-01::2013-06')
barChart(GS,theme='white.mono',bar.type='hlc') # some high-low-close style bars, monochromatic theme
candleChart(SBUX,multi.col=TRUE,theme="white",subset='2012::2013-01') # Add multi-coloring and change background to white
candleChart(GS,multi.col=TRUE,theme='white') # candles with color
lineChart(GS,line.type='h',TA=NULL, subset='2013-05::2013-06')
chartSeries(GOOG, type="line", subset='last 4 months') #type = c("auto", "candlesticks", "matchsticks", "bars","line")
chartSeries(to.weekly(GOOG),up.col='white',dn.col='blue',subset='2013-03::2013-06')
chartSeries(GS)
getSymbols("AAPL")
chartSeries(AAPL,subset='2013-03::2013-06')
addMACD()
addBBands()
setSymbolLookup(SPY='yahoo', VXN=list(name='^VIX',src='yahoo'))
mm <- specifyModel(Next(OpCl(SPY)) ~ OpCl(SPY) + Cl(VIX))
mmData <- modelData(mm) #extracts the relevant data set, with transforms magically applied.
mm is now a quantmod object holding the model formula and data structure implying the next (Next) period's open to close of the S&P 500 ETF (OpCl(SPY)) is modelled as a fucntion of the current period open to close and the current close of the VIX (Cl(VIX)).
There are 3 primary types:
(1) Op,Hi,Lo,Cl,Vo,Ad - extract the columns Open, High, Low, Close, Volume, and Adjusted (Yahoo)
(2) is.OHLC, has.OHLC, has.Op,has.Cl,has.Hi,has.Lo,has.Ad, and has.Vo - fairly obvious
(3) seriesHi and seriesLo
getSymbols("GS") # Goldman OHLC from yahoo
is.OHLC(GS) # does the data contain at least OHL and C?
has.Vo(GS) # how about volume?
Op(GS) # just the Open column please.
seriesHi(GS) # where and what was the high point
chartSeries(GS)
OpCl(GS) # daily percent change open to close
OpOp(GS) # one period open to open change
HiCl(GS) # the percent change from high to close
Lag: What was the previous value in the series
Next: What is the next value in the series
Delt: Compute the change (delta) from two prices
Lag(Cl(GS)) # One period lag of the close
Lag(Cl(GS),c(1,3,5)) # One, three, and five period lags
Next(OpCl(GS)) # The next periods open to close - today!
Delt(Op(GS),Cl(GS),k=1:3) # Open to close one-day, two-day and three-day lags
GS['2007'] #returns all Goldman's 2007 OHLC
GS['2008'] #now just 2008
GS['2008-01'] #now just January of 2008
GS['2007-06::2008-01-12'] #Jun of 07 through Jan 12 of 08
GS['::'] # everything in GS
GS['2008::'] # everything in GS, from 2008 onward
non.contiguous <- c('2007-01','2007-02','2007-12')
GS[non.contiguous]
The general format for the above is CCYY-MM-DD HH:MM:SS, with ranges specified via the '::' operator. The only requirement is that you specify the level of detail from left to right - that is to get January, you need to specify the year first.
To facilitate this 'time-based' subsetting, one can use the functions first and last. Essentially extending the concept of head and tail, one can now use character strings to describe the part of the data to be returned.
last(GS) # returns the last obs.
last(GS,8) # returns the last 8 obs.
last(GS, '3 weeks') # returns the last 3 weeks obs.
last(GS, '-3 weeks') # all except the last 3 weeks
last(GS, '3 months') # returns the last 3 months obs.
last(first(GS, '2 weeks'), '3 days') # The Last 3 Days of The First 2 Weeks
You can convert daily data to weekly or monthly OHLC data (to.weekly & to.monthly). It is currently possible to take everything from minute data all the way up to quarterly data and convert it into something lower frequency. Minute data can become 5 or 10 minute data (to.minutes5 and to.minutes10, respectively), which can in turn be turned into hourly or daily data. Daily data can become weekly, monthly, or even yearly.
periodicity(GS)
unclass(periodicity(GS))
to.weekly(GS)
to.monthly(GS)
periodicity(to.monthly(GS))
ndays(GS) # the number of days
nweeks(GS) # the number of weeks
nyears(GS) # the number of years
It may be useful to identify endpoints in your data by date with the function endpoints.
endpoints(GS,on="months")
apply.weekly(GS,FUN=function(x) { max(Cl(x)) } ) # find the maximum closing price each week
period.apply(GS,endpoints(GS,on='weeks'), FUN=function(x) { max(Cl(x)) } ) # the same thing - only more general
period.max(Cl(GS),endpoints(GS,on='weeks'))
as.numeric(period.max(Cl(GS),endpoints(GS,on='weeks'))) # same thing - only 50x faster!
There are also Fortran-based routines for period.min, period.sum, and period.prod, in addition to the period.max function.
calculate returns over calendar periods.
dailyReturn(SBUX) # returns by day
weeklyReturn(SBUX) # returns by week
monthlyReturn(SBUX) # returns by month, indexed by yearmon
allReturns(SBUX) # daily,weekly,monthly,quarterly, and yearly -- note the plural
Indicator TTR Name quantmod Name
Welles Wilder's Directional Movement Indicator ADX addADX
Average True Range ATR addATR
Bollinger Bands BBands addBBands
Bollinger Band Width N/A addBBands
Bollinger %b N/A addBBands
Commodity Channel Index CCI addCCI
Chaiken Money Flow CMF addCMF
Chande Momentum Oscillator CMO addCMO
Double Exponential Moving Average DEMA addDEMA
Detrended Price Oscillator DPO addDPO
Exponential Moving Average EMA addEMA
Price Envelope N/A addEnvelope
Exponential Volume Weigthed Moving Average EVWMA addEVWMA
Options and Futures Expiration N/A addExpiry
Moving Average Convergence Divergence MACD addMACD
Momentum momentum addMomentum
Rate of Change ROC addROC
Relative Strength Indicator RSI addRSI
Parabolic Stop and Reverse SAR addSAR
Simple Moving Average SMA addSMA
Stocastic Momentum Index SMI addSMI
Triple Smoothed Exponential Oscillator TRIX addTRIX
Volume N/A addVo
Weighted Moving Average WMA addWMA
Williams %R WPR addWPR
ZLEMA ZLEMA addZLEMA
chartSeries(GS, TA=NULL, subset='2013-04::2013-06')
chartSeries(GS, theme="white", TA="addVo();addBBands();addCCI()", subset='2013-04::2013-06')
chartSeries(GS, TA=NULL, theme="white",subset='2013-04::2013-06') # draw the chart
addVo() # add volume
addBBands() # add Bollinger Bands
addCCI() # add Commodity Channel Index
chartSeries(YHOO, TA=NULL)
addTA(OpCl(YHOO),col='blue', type='h')
addTA(HiCl(YHOO),col='green', type='h')
addTA(OpOp(YHOO),col='orange', type='h')