{quantmod} Learning Notes

library(quantmod)   
library(TTR)   

1 Getting data

1.1 Load data directly into your workspace, with the name of the object returned from the call

options("getSymbols.warning4.0"=FALSE)   
getSymbols("YHOO",src="google")               # from google finance   
getSymbols("GOOG",src="yahoo")                # from yahoo finance   
head(YHOO)   
head(GOOG) 

1.2 Load data from different sources into your workspace

setSymbolLookup(SBUX='google', AAPL='yahoo')   
getSymbols(c("SBUX","AAPL"))   
head(SBUX)   
head(AAPL)   

2 Charting with quantmod

setSymbolLookup(SBUX='yahoo', AAPL='yahoo',YHOO='yahoo',GOOG='yahoo')     
getSymbols(c("SBUX","AAPL","YHOO","GOOG"))   

2.1 barChart

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

2.2 candleChart

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

2.3 lineChart

lineChart(GS,line.type='h',TA=NULL, subset='2013-05::2013-06')

2.4 chartSeries

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)  

3 Technical analysis charting tools

getSymbols("AAPL")    
chartSeries(AAPL,subset='2013-03::2013-06')    
addMACD()    
addBBands()   

4 Using the data to generate signals

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)).

5 The OHLC Basics

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) 

6 Beyond OHLC Obviousnes

6.1 Get price changes

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

6.2 Three main functions that work together to get the above accomplished.

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 

7 Subsetting by Time and Date? – xts Makes It Easy

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.

8 The Last 3 Days of The First 2 Weeks

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           

9 Aggregating to a different time scale

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          

10 Apply by Period

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.

11 Period Returns

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                            

12 Technical Analysis and chartSeries

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')