Computational Finance and Risk Management
Introduction to Trading Systems
Guy Yollin
Applied Mathematics
University of Washington
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
1 / 74
Outline
Introduction
Data download and charting
Time series in R
More data retrieval
Technical indicators and TTR
Intra-day data example
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
2 / 74
Outline
Introduction
Data download and charting
Time series in R
More data retrieval
Technical indicators and TTR
Intra-day data example
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
3 / 74
Lecture references
quantmod package
Jeffrey Ryans quantmod website:
http://www.quantmod.com/
quantmod project page on R-forge:
http://r-forge.r-project.org/projects/quantmod
TTR package
Joshua Ulrichs Foss Trading blog:
http://blog.fosstrading.com/
TTR project page on R-forge:
http://r-forge.r-project.org/projects/ttr/
xts package
xts project page on R-forge:
http://r-forge.r-project.org/projects/xts/
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
4 / 74
Packages for trading system development in R
Quantitative analysis package hierarchy
Application Area
Performance metrics
and graphs
Portfolio optimization
and quantitative
trading strategies
Data access and
financial charting
R Package
PerformanceAnalytics - Tools for performance and risk analysis
PortfolioAnalytics - Portfolio analysis and optimization
quantstrat Rules-based trading system development
blotter Trading system accounting infrastructure
quantmod - Quantitative financial modeling framework
TTR - Technical trading rules
xts - Extensible time series
Time series objects
zoo - Ordered observation
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
5 / 74
The zoo package
The zoo package provides an infrastructure for regularly-spaced and
irregularly-space time series
Key functions:
zoo
create a zoo time series object
merge
merges time series (automatically handles of time alignment)
aggregate
create coarser resolution time series with summary statistics
rollapply
calculate rolling window statistics
read.zoo
read a text file into a zoo time series object
Authors:
Achim Zeileis
Gabor Grothendieck
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
6 / 74
The xts package
The xts package extends the zoo time series class with fine-grained time
indexes, interoperability with other R time series classes, and user defined
attributes
Key functions:
xts
create an xts time series object
align.time
align time series to a coarser resolution
to.period
convert time series data to an OHLC series
[.xts
subset time series
Authors:
Jeffrey Ryan
Josh Ulrich
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
7 / 74
R-forge
R-forge is a hosting platform for R package development which
includes SVN, daily build and check, mailing lists, bug tracking,
message boards etc.
More then 1000 R packages are hosted on R-forge including all of the
trading system development packages mentioned earlier
It is common for new packages to be developed on R-forge and for
mature packages to be maintained on R-forge even after being hosted
on CRAN
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
8 / 74
Install trading system development packages
#
# install these packages from CRAN (or r-forge)
#
install.packages("xts", dependencies=TRUE)
install.packages("PerformanceAnalytics", dependencies=TRUE)
#
# Install these package from r-forge
#
install.packages("quantmod", repos = "http://R-Forge.R-project.org")
install.packages("TTR", repos = "http://R-Forge.R-project.org")
install.packages("FinancialInstrument", repos = "http://R-Forge.R-project.org")
install.packages("blotter", repos = "http://R-Forge.R-project.org")
install.packages("quantstrat", repos = "http://R-Forge.R-project.org")
R-Forge packages can be installed by setting the repos argument to
http://R-Forge.R-project.org
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
9 / 74
Outline
Introduction
Data download and charting
Time series in R
More data retrieval
Technical indicators and TTR
Intra-day data example
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
10 / 74
The quantmod package
The quantmod package for R is designed to assist the quantitative trader
in the development, testing, and deployment of statistically based trading
models.
Key functions:
getSymbols
load or download price data
Yahoo Finance / Google Finance
FRED
Oanda
csv, RData
MySQL, SQLite
chartSeries
charting tool to create standard financial charts
Author:
Jeffrey Ryan
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
11 / 74
The getSymbols function
The getSymbols function loads (downloads) historic price data
Usage:
getSymbols(Symbols = NULL, env = parent.frame(), src = "yahoo",
auto.assign = getOption('getSymbols.auto.assign',TRUE), ...)
Main arguments:
Symbols
a vector of ticker symbols
env
where to create objects. Setting env=NULL is equal to
auto.assign=FALSE
src
source of data (yahoo)
auto.assign
should results be returned or loaded to env
...
additional parameters
Return value:
an object of type return.class depending on env and auto.assign
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
12 / 74
The getSymbols.yahoo function
The getSymbols.yahoo function downloads historic price data from
finance.yahoo.com
Usage:
getSymbols.yahoo(Symbols, env, return.class = 'xts', index.class
from = "2007-01-01", to = Sys.Date(), ...)
= 'Date',
Main arguments:
return.class
class of returned object
index.class
class of returned object index (xts only)
...
additional parameters
Return value:
an object of type return.class depending on env and auto.assign
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
13 / 74
The getSymbols function
library(quantmod)
getSymbols("^GSPC")
ls()
## [1] "filename" "GSPC"
class(GSPC)
## [1] "xts" "zoo"
class(index(GSPC))
## [1] "Date"
dim(GSPC)
## [1] 1933
By default, the symbol was auto-assigned to the parent environment
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
14 / 74
The getSymbols function
tail(GSPC,4)
##
##
##
##
##
2014-09-02
2014-09-03
2014-09-04
2014-09-05
GSPC.Open GSPC.High GSPC.Low GSPC.Close GSPC.Volume GSPC.Adjusted
2004.07
2006.12 1994.85
2002.28 2819980000
2002.28
2003.57
2009.28 1998.14
2000.72 2809980000
2000.72
2001.67
2011.17 1992.54
1997.65 3072410000
1997.65
1998.00
2007.71 1990.10
2007.71 2818300000
2007.71
tail(Cl(GSPC),4)
##
##
##
##
##
2014-09-02
2014-09-03
2014-09-04
2014-09-05
GSPC.Close
2002.28
2000.72
1997.65
2007.71
tail(Ad(GSPC),4)
##
##
##
##
##
2014-09-02
2014-09-03
2014-09-04
2014-09-05
GSPC.Adjusted
2002.28
2000.72
1997.65
2007.71
Note that the symbol is prepended to columns names of the xts
object; use extractor functions to access column data (e.g. Cl(GSPC))
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
15 / 74
xts extractor functions
The xts package includes a number of functions to extract specific series
from an xts object of market data:
Function
Description
Op(x)
Get Open
Hi(x)
Get High
Lo(x)
Get Low
Cl(x)
Get Close
Vo(x)
Get Volume
Ad(x)
Get Adjusted Close
HLC(x)
Get High, Low, and Close
OHLC(x)
Get Open, High, Low, and Close
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
16 / 74
The chartSeries function
The chartSeries function creates financial charts
Usage:
getSymbols(Symbols = NULL, env = parent.frame(), src = "yahoo",
auto.assign = getOption('getSymbols.auto.assign',TRUE), ...)
Main arguments:
x
an OHLC object
type
style of chart to draw
theme
a chart.theme object
subset
xts style date subsetting argument
TA
a vector of technical indicators and params
Return value:
a chob object
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
17 / 74
The chartSeries function
chartSeries(GSPC,subset="2014",theme="white")
GSPC
[20140102/20140905]
Last 2007.71
2000
1950
1900
1850
1800
1750
5000
4500
4000
3500
3000
2500
2000
Volume (millions):
2,818,300,000
Jan 02 2014
Guy Yollin (Copyright 2014)
Mar 03 2014
May 01 2014
Jul 01 2014
Introduction to Trading Systems
Sep 02 2014
Quantmod
18 / 74
Customize a chartSeries plot
whiteTheme <- chartTheme("white")
names(whiteTheme)
## [1] "fg.col"
"bg.col"
## [6] "major.tick"
"up.col"
## [11] "dn.dn.col"
"up.dn.col"
## [16] "up.up.border" "dn.dn.border"
## [21] "area"
"fill"
"grid.col"
"dn.col"
"up.border"
"up.dn.border"
"Expiry"
"border"
"dn.up.col"
"dn.border"
"main.col"
"theme.name"
"minor.tick"
"up.up.col"
"dn.up.border"
"sub.col"
whiteTheme$bg.col <- "white"
whiteTheme$dn.col <- "pink"
whiteTheme$up.col <- "lightgreen"
whiteTheme$border <- "lightgray"
x <- chartSeries(GSPC,subset="last 3 months",theme=whiteTheme,TA=NULL)
class(x)
## [1] "chob"
## attr(,"package")
## [1] "quantmod"
subset to last 3 months
totally white background
no volume sub-graph (TA=NULL)
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
19 / 74
A chartSeries plot
GSPC
[20140701/20140905]
2000
1980
1960
1940
1920
Jul 01 2014
Guy Yollin (Copyright 2014)
Jul 21 2014
Aug 04 2014
Aug 18 2014
Introduction to Trading Systems
Sep 02 2014
Quantmod
20 / 74
Outline
Introduction
Data download and charting
Time series in R
More data retrieval
Technical indicators and TTR
Intra-day data example
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
21 / 74
Time series data
Almost all data related to trading is a time series:
market data
technical analysis indicators
trades
position data
P&L
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
22 / 74
Time series data
Time series
A time series is a sequence of ordered data points measured at specific
points in time
Time series object
A time series object in R is a compound data structure that includes a
data matrix as well as a vector of associated time stamps
class
ts
mts
zoo
xts
package
stats
stats
zoo
xts
Guy Yollin (Copyright 2014)
overview
regularly spaced time series
multiple regularly spaced time series
reg/irreg and arbitrary time stamp classes
an extension of the zoo class
Introduction to Trading Systems
Quantmod
23 / 74
Time series methods
Time series classes in R will typically implement the following methods:
start
return start of time series
end
return end of time series
frequency
return frequency of time series
window
Extract subset of time series
index
return time index of time series
time
return time index of time series
coredata
return data of time series
diff
difference of the time series
lag
lag of the time series
aggregate
aggregate to lower resolution time series
cbind
merge 2 or more time series together
merge
merge 2 or more time series together
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
24 / 74
Components of an xts object
An xts object is composed of 3 components:
Index
a Data class or Time-Date class used for the time-stamp of
observations
Matrix
the time series observations (univariate or multivariate)
can be numeric, character, logical, etc. but must be
homogeneous
Attr
hidden attributes and user attributes
class of the index
format of the index
time zone
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
25 / 74
Date class
A Date object is stored internally as the days since 1970-01-01
myStr <- "2013-07-04"
class(myStr)
## [1] "character"
myDate <- as.Date(myStr)
class(myDate)
## [1] "Date"
as.numeric(myDate)
## [1] 15890
format(myDate,"%m/%d/%y")
## [1] "07/04/13"
as.Date("110704",format="%y%m%d")
## [1] "2011-07-04"
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
26 / 74
Date-Time classes
A POSIXct object is a Date-Time object internally stored as the
number of seconds since 1970-01-01
A POSIXlt object is a Date-Time object internally stored as 9
calendar and time components
d <- Sys.time()
class(d)
## [1] "POSIXct" "POSIXt"
unclass(d)
## [1] 1410038854
sapply(unclass(as.POSIXlt(d)), function(x) x)
##
sec
## "33.5228459835052"
##
mon
##
"8"
##
isdst
##
"1"
Guy Yollin (Copyright 2014)
min
"27"
year
"114"
zone
"PDT"
hour
"14"
wday
"6"
gmtoff
"-25200"
Introduction to Trading Systems
mday
"6"
yday
"248"
Quantmod
27 / 74
xts subsetting
xts time series objects can be easily subset:
Date and time organized from most significant to least significant
CCYY-MM-DD HH:MM:SS[.s]
Separators can be omitted
CCYYMMDDHHMMSS
Intervals can be designated with the "/" or "::"
2010/2011
2011-04::2011-07
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
28 / 74
xts subsetting
chartSeries(GSPC["2014"],theme=whiteTheme,name="S&P 500")
S&P 500
[20140102/20140905]
Last 2007.71
2000
1950
1900
1850
1800
1750
5000
4500
4000
3500
3000
2500
2000
Volume (millions):
2,818,300,000
Jan 02 2014
Guy Yollin (Copyright 2014)
Mar 03 2014
May 01 2014
Jul 01 2014
Introduction to Trading Systems
Sep 02 2014
Quantmod
29 / 74
xts subsetting
chartSeries(GSPC["2013/2014"],theme=whiteTheme,name="S&P 500")
S&P 500
[20130102/20140905]
2000
Last 2007.71
1900
1800
1700
1600
1500
5000
4000
3000
2000
Volume (millions):
2,818,300,000
Jan 02 2013
Guy Yollin (Copyright 2014)
Jun 03 2013 Oct 01 2013 Feb 03 2014
Introduction to Trading Systems
Jul 01 2014
Quantmod
30 / 74
xts subsetting
chartSeries(GSPC["2014-06::2014-07"],theme=whiteTheme,name="S&P 500")
S&P 500
[20140602/20140731]
Last 1930.67
1980
1960
1940
1920
4000
3500
3000
2500
2000
Volume (millions):
4.193e+09
Jun 02 2014
Guy Yollin (Copyright 2014)
Jun 16 2014
Jun 30 2014
Jul 14 2014
Introduction to Trading Systems
Jul 28 2014
Quantmod
31 / 74
xts subsetting
chartSeries(GSPC["201406::"],theme=whiteTheme,name="S&P 500")
S&P 500
[20140602/20140905]
Last 2007.71
2000
1980
1960
1940
1920
4000
3500
3000
2500
2000
Volume (millions):
2,818,300,000
Jun 02 2014
Guy Yollin (Copyright 2014)
Jun 23 2014
Jul 14 2014
Aug 04 2014
Introduction to Trading Systems
Aug 25 2014
Quantmod
32 / 74
Outline
Introduction
Data download and charting
Time series in R
More data retrieval
Technical indicators and TTR
Intra-day data example
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
33 / 74
Download historic quotes: specifying the start date
getSymbols("SPY",from="2000-01-01")
class(SPY)
## [1] "xts" "zoo"
head(SPY)
##
##
##
##
##
##
##
2000-01-03
2000-01-04
2000-01-05
2000-01-06
2000-01-07
2000-01-10
SPY.Open SPY.High SPY.Low SPY.Close SPY.Volume SPY.Adjusted
148.25
148.25 143.88
145.44
8164300
111.46
143.53
144.06 139.64
139.75
8089800
107.10
139.94
141.53 137.25
140.00
12177900
107.29
139.62
141.50 137.75
137.75
6227200
105.56
140.31
145.75 140.06
145.75
8066500
111.70
146.25
146.91 145.03
146.25
5741700
112.08
head(index(SPY))
## [1] "2000-01-03" "2000-01-04" "2000-01-05" "2000-01-06" "2000-01-07" "2000-01-10"
class(index(SPY))
## [1] "Date"
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
34 / 74
Download historic quotes: specifying the time stamp class
getSymbols("SBUX",index.class="POSIXct",from="2000-01-01")
class(SBUX)
## [1] "xts" "zoo"
head(SBUX)
##
##
##
##
##
##
##
2000-01-03
2000-01-04
2000-01-05
2000-01-06
2000-01-07
2000-01-10
SBUX.Open SBUX.High SBUX.Low SBUX.Close SBUX.Volume SBUX.Adjusted
23.88
24.69
23.25
24.66
12116000
5.76
24.06
24.88
23.75
23.88
10782400
5.58
23.94
24.62
23.69
24.19
14103200
5.65
24.00
25.62
24.00
25.06
15412800
5.86
24.75
25.00
24.25
24.94
13022400
5.83
25.88
26.75
25.81
26.00
14515600
6.08
head(index(SBUX))
## [1] "2000-01-03 UTC" "2000-01-04 UTC" "2000-01-05 UTC" "2000-01-06 UTC"
## [5] "2000-01-07 UTC" "2000-01-10 UTC"
class(index(SBUX))
## [1] "POSIXct" "POSIXt"
chartSeries(SBUX,theme=whiteTheme,minor.ticks=FALSE)
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
35 / 74
Unadjusted SBUX data
SBUX
[20000103/20140905]
80
Last 77.95
60
40
20
150
100
Volume (millions):
4,002,500
50
0
Jan 03 2000 Jan 02 2003
Guy Yollin (Copyright 2014)
Jan 03 2006 Jan 02 2009
Introduction to Trading Systems
Jan 03 2012
Quantmod
36 / 74
Get stock split history
(spl <- getSplits("SBUX"))
##
##
##
##
##
##
1993-09-30
1995-12-04
1999-03-22
2001-04-30
2005-10-24
SBUX.spl
0.5
0.5
0.5
0.5
0.5
class(spl)
## [1] "xts" "zoo"
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
37 / 74
Get stock dividend history
(div <- getDividends("SBUX"))
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
2010-04-05
2010-08-02
2010-11-16
2011-02-07
2011-05-09
2011-08-08
2011-11-15
2012-02-06
2012-05-07
2012-08-06
2012-11-13
2013-02-05
2013-05-07
2013-08-06
2013-11-12
2014-02-04
2014-05-06
2014-08-05
[,1]
0.10
0.13
0.13
0.13
0.13
0.13
0.17
0.17
0.17
0.17
0.21
0.21
0.21
0.21
0.26
0.26
0.26
0.26
class(div)
## [1] "xts" "zoo"
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
38 / 74
The adjustOHLC function
The adjustOHLC adjusts all columns of an OHLC object for split and
dividend
Usage:
adjustOHLC(x, adjust = c("split","dividend"), use.Adjusted = FALSE,
ratio = NULL, symbol.name=deparse(substitute(x)))
Main arguments:
x
an OHLC object
use.Adjusted
calculated from dividends and splits, or used Adjusted price
column
Return value:
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
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
39 / 74
Adjust for split and dividend
head(SBUX)
##
##
##
##
##
##
##
2000-01-03
2000-01-04
2000-01-05
2000-01-06
2000-01-07
2000-01-10
SBUX.Open SBUX.High SBUX.Low SBUX.Close SBUX.Volume SBUX.Adjusted
23.88
24.69
23.25
24.66
12116000
5.76
24.06
24.88
23.75
23.88
10782400
5.58
23.94
24.62
23.69
24.19
14103200
5.65
24.00
25.62
24.00
25.06
15412800
5.86
24.75
25.00
24.25
24.94
13022400
5.83
25.88
26.75
25.81
26.00
14515600
6.08
adj.exact <- adjustOHLC(SBUX)
head(adj.exact)
##
##
##
##
##
##
##
2000-01-03
2000-01-04
2000-01-05
2000-01-06
2000-01-07
2000-01-10
SBUX.Open
5.5818405
5.6239146
5.5958652
5.6098899
5.7851990
6.0493313
SBUX.High
5.7711743
5.8155859
5.7548121
5.9885575
5.8436353
6.2526898
SBUX.Low SBUX.Close SBUX.Volume SBUX.Adjusted
5.4345809 5.7641619
12116000
5.76
5.5514536 5.5818405
10782400
5.58
5.5374288 5.6543016
14103200
5.65
5.6098899 5.8576601
15412800
5.86
5.6683263 5.8296106
13022400
5.83
6.0329691 6.0773807
14515600
6.08
An article that describes how Yahoo calculates the adjusted close can
be found here:
http://help.yahoo.com/kb/index?locale=en_US&y=PROD_ACCT&page=content&id=SLN2311
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
40 / 74
Compare adjustment methods
head(adj.exact)
##
##
##
##
##
##
##
2000-01-03
2000-01-04
2000-01-05
2000-01-06
2000-01-07
2000-01-10
SBUX.Open
5.5818405
5.6239146
5.5958652
5.6098899
5.7851990
6.0493313
SBUX.High
5.7711743
5.8155859
5.7548121
5.9885575
5.8436353
6.2526898
SBUX.Low SBUX.Close SBUX.Volume SBUX.Adjusted
5.4345809 5.7641619
12116000
5.76
5.5514536 5.5818405
10782400
5.58
5.5374288 5.6543016
14103200
5.65
5.6098899 5.8576601
15412800
5.86
5.6683263 5.8296106
13022400
5.83
6.0329691 6.0773807
14515600
6.08
adj.approx <- adjustOHLC(SBUX, use.Adjusted=TRUE)
head(adj.approx)
##
##
##
##
##
##
##
2000-01-03
2000-01-04
2000-01-05
2000-01-06
2000-01-07
2000-01-10
SBUX.Open
5.5778102
5.6220603
5.5916081
5.6121309
5.7855854
6.0519385
SBUX.High
5.7670073
5.8136683
5.7504341
5.9909497
5.8440257
6.2553846
SBUX.Low SBUX.Close SBUX.Volume SBUX.Adjusted
5.4306569
5.76
12116000
5.76
5.5496231
5.58
10782400
5.58
5.5332162
5.65
14103200
5.65
5.6121309
5.86
15412800
5.86
5.6687049
5.83
13022400
5.83
6.0355692
6.08
14515600
6.08
chartSeries(adj.exact,theme=whiteTheme,name="SBUX",minor.ticks=FALSE)
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
41 / 74
Adjusted SBUX plot
SBUX
[20000103/20140905]
80
Last 77.95
60
40
20
150
100
Volume (millions):
4,002,500
50
0
Jan 03 2000 Jan 02 2003
Guy Yollin (Copyright 2014)
Jan 03 2006 Jan 02 2009
Introduction to Trading Systems
Jan 03 2012
Quantmod
42 / 74
Download historic quotes: specifying adjusted OHLC
getSymbols("SBUX",index.class="POSIXct",from="2000-01-01",adjust=T)
## [1] "SBUX"
head(SBUX)
##
##
##
##
##
##
##
2000-01-03
2000-01-04
2000-01-05
2000-01-06
2000-01-07
2000-01-10
SBUX.Open
5.5818405
5.6239146
5.5958652
5.6098899
5.7851990
6.0493313
SBUX.High
5.7711743
5.8155859
5.7548121
5.9885575
5.8436353
6.2526898
SBUX.Low SBUX.Close SBUX.Volume SBUX.Adjusted
5.4345809 5.7641619
12958543
5.76
5.5514536 5.5818405
11532205
5.58
5.5374288 5.6543016
15083932
5.65
5.6098899 5.8576601
16484602
5.86
5.6683263 5.8296106
13927974
5.83
6.0329691 6.0773807
15525011
6.08
SBUX.High
5.7711743
5.8155859
5.7548121
5.9885575
5.8436353
6.2526898
SBUX.Low SBUX.Close SBUX.Volume SBUX.Adjusted
5.4345809 5.7641619
12116000
5.76
5.5514536 5.5818405
10782400
5.58
5.5374288 5.6543016
14103200
5.65
5.6098899 5.8576601
15412800
5.86
5.6683263 5.8296106
13022400
5.83
6.0329691 6.0773807
14515600
6.08
head(adj.exact)
##
##
##
##
##
##
##
2000-01-03
2000-01-04
2000-01-05
2000-01-06
2000-01-07
2000-01-10
SBUX.Open
5.5818405
5.6239146
5.5958652
5.6098899
5.7851990
6.0493313
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
43 / 74
Federal reserve economic data
The function getSymbols can also be used to access data from the
Federal Reserve Economic Data (FRED) database
http://research.stlouisfed.org/fred2/
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
44 / 74
Download interest rate data from FRED
getSymbols('DTB3',src='FRED')
first(DTB3,'1 week')
##
DTB3
## 1954-01-04 1.33
last(DTB3,'1 week')
##
##
##
##
##
DTB3
2014-09-01
NA
2014-09-02 0.03
2014-09-03 0.03
2014-09-04 0.03
chartSeries(DTB3,theme="white",minor.ticks=FALSE)
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
45 / 74
Three-month U.S. Treasury bill rate
DTB3
[19540104/20140904]
Last 0.03
15
10
Jan 04 1954
Guy Yollin (Copyright 2014)
Jan 02 1970
Jan 02 1985
Jan 03 2000
Introduction to Trading Systems
Sep 04 2014
Quantmod
46 / 74
Quandl
Tammer Kamel the founder of www.quandl.com wants to do to
Bloomberg what Wikipedia did to Britannica.
http://www.quandl.com/
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
47 / 74
Quandl futures
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
48 / 74
The Quandl package
The Quandl package interacts directly with the Quandl API to offer data
in a number of formats usable in R
Key functions:
Quandl
Pulls data from the Quandl API
Quandl.auth
Query or set Quandl API token
Quandl.search
Search the Quandl database
Authors:
Raymond McTaggart
Anonymous API calls are limited to 50 requests per day; signed up users receive an
authorization token that allows them to get 500 API calls per day; see
http://www.quandl.com/help/r
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
49 / 74
The Quandl function
The Quandl function pulls data from the Quandl API
Usage:
Quandl(code, type
transformation =
collapse = c("",
sort = c("desc",
= c("raw", "ts", "zoo", "xts"), start_date, end_date,
c("", "diff", "rdiff", "normalize", "cumul", "rdiff_from"),
"weekly", "monthly", "quarterly", "annual"),
"asc"), meta = FALSE, authcode = Quandl.auth(), ...)
Main arguments:
code
Dataset code on Quandl specified as a string
type
Type of data returned (raw, ts, zoo or xts)
start_date Start date
end_date
End date
collapse
Frequency of data
Return value:
time series data in the specified format
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
50 / 74
Downloading data from Quandl
library(Quandl)
cl1 = Quandl("OFDP/FUTURE_CL1",type="xts")
class(cl1)
## [1] "xts" "zoo"
class(index(cl1))
## [1] "Date"
first(cl1)
##
Open High
Low Settle Volume Open Interest
## 1983-03-30 29.01 29.56 29.01
29.4
949
470
last(cl1)
##
Open High
Low Settle Volume Open Interest
## 2014-09-05 94.57 94.99 92.86 93.29 261386
235848
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
51 / 74
Downloading data from Quandl
cl1 <- cl1[,c("Open","High","Low","Settle","Volume")]
colnames(cl1) <- c("Open","High","Low","Close","Volume")
sum(is.na(coredata(cl1)))
## [1] 0
sum(coredata(cl1)<0.01)
## [1] 17
cl1[cl1 < 0.1] <- NA
cl1 <- na.approx(cl1)
chartSeries(cl1,name="Nymex Crude (front contract)",theme=chartTheme("white"))
Required data cleaning: replace zero values with NA and then use the
function na.approx to interpolate
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
52 / 74
Historic futures data from Quandl
Nymex Crude (front contract)
[19830330/20140905]
Last 93.29
140
120
100
80
60
40
20
60
50
40
30
20
10
0
Volume (10,000s):
261,386
Mar 30 1983
Guy Yollin (Copyright 2014)
Jan 02 1990
Jan 02 1998
Jan 03 2006
Introduction to Trading Systems
Jan 02 2014
Quantmod
53 / 74
Outline
Introduction
Data download and charting
Time series in R
More data retrieval
Technical indicators and TTR
Intra-day data example
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
54 / 74
The TTR package
The TTR package is a comprehensive collection of technical analysis
indicators for R
Key features:
moving averages
oscillators
price channels
trend indicators
Author:
Joshua Ulrich
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
55 / 74
Selected technical analysis indicators in TTR
Function
Description
Function
Description
stoch
stochastic oscillator
ADX
Directional Movement Index
aroon
Aroon indicator
ATR
Average True Range
BBands
Bollinger bands
CCI
Commodity Channel Index
chaikinAD
Chaikin Acc/Dist
chaikinVolatility
Chaikin Volatility
ROC
rate of change
momentum
momentum indicator
CLV
Close Location Value
CMF
Chaikin Money Flow
CMO
Chande Momentum Oscillator
SMA
simple moving average
EMA
exponential moving average
DEMA
double exp mov avg
VWMA
volume weighted MA
VWAP
volume weighed avg price
DonchianChannel
Donchian Channel
DPO
Detrended Price Oscillator
EMV
Ease of Movement Value
volatility
volatility estimators
MACD
MA converge/diverge
MFI
Money Flow Index
RSI
Relative Strength Index
SAR
Parabolic Stop-and-Reverse
TDI
Trend Detection Index
TRIX
Triple Smoothed Exponential Osc
VHF
Vertical Horizontal Filter
williamsAD
Williams Acc/Dist
WPR
Williams % R
ZigZag
Zig Zag trend line
see Technical Analysis from A to Z by Steven Achelis
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
56 / 74
Calculate and plot Bollinger bands
b <- BBands(HLC=HLC(SBUX["2014"]), n=20, sd=2)
tail(b,10)
##
##
##
##
##
##
##
##
##
##
##
2014-08-22
2014-08-25
2014-08-26
2014-08-27
2014-08-28
2014-08-29
2014-09-02
2014-09-03
2014-09-04
2014-09-05
dn
76.411021
76.428539
76.476472
76.554083
76.552982
76.625643
76.656180
76.698147
76.724373
76.812251
mavg
77.528909
77.511574
77.485948
77.453339
77.457245
77.503182
77.521167
77.533500
77.541000
77.574667
up
78.646797
78.594608
78.495424
78.352595
78.361509
78.380720
78.386153
78.368853
78.357627
78.337082
pctB
0.40208802
0.67932318
0.75131112
0.77615115
0.68030579
0.67481749
0.51088649
0.26447097
0.22794613
0.50131162
chartSeries(SBUX,TA='addBBands();addBBands(draw="p");addVo()',
subset='2014',theme="white")
pctB =
Close LowerBand
UpperBand LowerBand
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
57 / 74
Bollinger bands
SBUX
[20140102/20140905]
Last 77.95
Bollinger Bands (20,2) [Upper/Lower]: 78.337/76.812
80
78
76
74
72
70
68
1.0
Bollinger %b (20,2):
0.501
0.5
0.0
15
Volume (millions):
4,002,500
10
5
Jan 02 2014
Guy Yollin (Copyright 2014)
Mar 03 2014
May 01 2014
Introduction to Trading Systems
Jul 01 2014
Aug 01 2014
Sep 05 2014
Quantmod
58 / 74
Moving Average Convergence-Divergence (MACD)
macd <- MACD( Cl(SBUX), 12, 26, 9, maType="EMA" )
tail(macd)
##
##
##
##
##
##
##
macd
signal
2014-08-28 0.1152221277 0.079458718
2014-08-29 0.1195390995 0.087474794
2014-09-02 0.0876697703 0.087513789
2014-09-03 -0.0092470283 0.068161626
2014-09-04 -0.0470796190 0.045113377
2014-09-05 0.0051187401 0.037114450
chartSeries(SBUX, TA = "addMACD()",subset="2014",theme=whiteTheme)
MACD line = EMA(Close,12) EMA(Close,26)
Signal line = EMA(MACD line,9)
MACD histogram = MACD line Signal line
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
59 / 74
Moving Average Convergence-Divergence (MACD)
SBUX
[20140102/20140905]
80
Last 77.95
78
76
74
72
70
68
2
1
0
1
2
Moving Average Convergence Divergence (12,26,9):
MACD: 0.005
Signal: 0.037
Jan 02 2014
Guy Yollin (Copyright 2014)
Mar 03 2014
May 01 2014
Jul 01 2014
Introduction to Trading Systems
Sep 02 2014
Quantmod
60 / 74
Relative Strength Index (RSI)
rsi <- RSI( Cl(SBUX), n = 14 )
tail(rsi)
##
##
##
##
##
##
##
2014-08-28
2014-08-29
2014-09-02
2014-09-03
2014-09-04
2014-09-05
SBUX.Close.EMA.14
52.010352
52.010352
48.936808
43.189696
46.797814
53.577264
chartSeries(SBUX, TA = "addRSI()",subset="2013",theme=whiteTheme)
RSI = 100
RS =
100
1 + RS
average of up changes
average of down changes
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
61 / 74
Relative Strength Index (RSI)
SBUX
[20130102/20131231]
Last 77.5472535857189
80
75
70
65
60
55
80
70
60
50
40
30
Relative Strength Index (14):
48.641
Jan 02 2013
Guy Yollin (Copyright 2014)
Apr 01 2013
Jul 01 2013
Oct 01 2013
Introduction to Trading Systems
Dec 31 2013
Quantmod
62 / 74
Experimental chart_Series chart
The chartSeries functions are in the process of being updated;
quantmod functions incorporating an underscore in their name are
experimental version 2 functions:
chart_Series
add_TA
chart_Theme
myTheme<-chart_theme()
myTheme$col$up.col<-'lightgreen'
myTheme$col$dn.col<-'pink'
#
chart_Series(SBUX["2013"],TA='add_BBands(lwd=2)',theme=myTheme,name="SBUX")
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
63 / 74
Experimental chart_Series chart
SBUX
20130102 / 20131231
80
80
75
75
70
70
65
65
60
60
55
55
Jan
Jan 02 2013
Feb
Mar
Mar 01 2013
Guy Yollin (Copyright 2014)
Apr
May
Jun
May 01 2013 Jun 03 2013
Jul
Aug
Sep
Aug 01 2013 Sep 03 2013
Introduction to Trading Systems
Oct
Nov
Nov 01 2013
Dec
Dec 31 2013
Quantmod
64 / 74
Outline
Introduction
Data download and charting
Time series in R
More data retrieval
Technical indicators and TTR
Intra-day data example
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
65 / 74
Working with intra-day data
For intra-day data indexing by date alone is not enough
beyond the capabilities of zoo objects with Date indexes
intra-day bars
tick data
Intra-day time series require formal time-based classes for indexing
Recommended classes for high-frequency time series:
xts class
POSIXct/POSIXlt date-time class for indexing
Class
Daily data
Intra-day data
time series class
xts
xts
time index class
Date
POSIXlt
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
66 / 74
The strptime function
The strptime function converts character strings to POSIXlt date-time
objects
Usage:
strptime(x, format, tz = "")
Main arguments:
x
vector of character strings to be converted to POSIXlt objects
format
date-time format specification
tz
timezone to use for conversion
Return value:
a POSIXlt object
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
67 / 74
The xts function
The function xts is the constructor function for extensible time-series
objects
Usage:
xts(x = NULL, order.by = index(x), frequency = NULL,
unique = TRUE, tzone = Sys.getenv("TZ"), ...)
Main arguments:
x
data matrix (or vector) with time series data
order.by
vector of unique times/dates (POSIXct is recommended)
Return value:
an xts object
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
68 / 74
Read GBPUSD 30-minute bars
fn1 <- "GBPUSD.txt"
dat <- read.table(file=fn1,sep=",",header=T,as.is=T)
head(dat)
##
##
##
##
##
##
##
1
2
3
4
5
6
Date Time
Open
High
Low Close Up Down
10/20/2002 2330 1.5501 1.5501 1.5481 1.5482 0
0
10/21/2002
0 1.5481 1.5483 1.5472 1.5472 0
0
10/21/2002
30 1.5471 1.5480 1.5470 1.5478 0
0
10/21/2002 100 1.5477 1.5481 1.5471 1.5480 0
0
10/21/2002 130 1.5480 1.5501 1.5479 1.5493 0
0
10/21/2002 200 1.5492 1.5497 1.5487 1.5492 0
0
tm <- strptime(
paste(dat[,"Date"], sprintf("%04d",dat[,"Time"])),
format="%m/%d/%Y %H%M")
class(tm)
## [1] "POSIXlt" "POSIXt"
head(tm)
## [1] "2002-10-20 23:30:00 PDT" "2002-10-21 00:00:00 PDT" "2002-10-21 00:30:00 PDT"
## [4] "2002-10-21 01:00:00 PDT" "2002-10-21 01:30:00 PDT" "2002-10-21 02:00:00 PDT"
Use paste with sprintf to format a Date-Time string
Use the format argument of strptime to specify the formatting
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
69 / 74
Create and plot xts object
GBP <- xts(x=dat[,c("Open","High","Low","Close")],order.by=tm)
GBP <- GBP['2007']
first(GBP,'4 hours')
##
##
##
##
##
##
##
##
2007-01-01
2007-01-01
2007-01-01
2007-01-01
2007-01-01
2007-01-01
2007-01-01
17:30:00
18:00:00
18:30:00
19:00:00
19:30:00
20:00:00
20:30:00
Open
1.9649
1.9646
1.9645
1.9651
1.9651
1.9655
1.9653
High
1.9650
1.9648
1.9653
1.9652
1.9658
1.9657
1.9656
Low
1.9644
1.9641
1.9645
1.9647
1.9651
1.9650
1.9651
Close
1.9645
1.9644
1.9650
1.9650
1.9654
1.9654
1.9655
barChart(GBP,TA='addSMA(n = 7, col = "red");addSMA(n = 44, col = "blue")',
subset='2007-12-24/2007-12-26',theme="white",name="GBPUSD")
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
70 / 74
GBPUSD crossover example
GBPUSD
[20071224/20071226 23:30:00]
Last 1.98542
1.988
1.986
1.984
1.982
1.980
1.978
1.976
Dec 24 00:00
Guy Yollin (Copyright 2014)
Dec 24 10:00
Dec 26 04:00
Dec 26 14:30
Introduction to Trading Systems
Dec 26 23:30
Quantmod
71 / 74
GBPUSD crossover example with annotation
# make candle stick plot with moving averages
#
chart_Series(GBP,subset='2007-12-24/2007-12-26',theme=myTheme,name="GBPUSD",
TA='add_SMA(n=7,col="red",lwd=2);add_SMA(n=44,col="blue",lwd=2)')
#
# find cross-over bar
#
fastMA <- SMA(Cl(GBP),n=7)
slowMA <- SMA(Cl(GBP),n=44)
co <- fastMA > slowMA
x <- which(co['2007-12-24/2007-12-26'])[1]
#
# identify cross-over bar
#
ss <- GBP['2007-12-24/2007-12-26']
add_TA(ss[x,"Low"]-0.0005,pch=17,type="p",col="red", on=1,cex=2)
#
text(x=x,y=ss[x,"Low"]-0.0005,"Crossover\nbar",pos=1)
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
72 / 74
GBPUSD crossover example with annotation
GBPUSD
20071224 / 20071226 23:30:00
1.988
1.988
1.987
1.987
1.986
1.986
1.985
1.985
1.984
1.984
1.983
1.983
1.982
1.982
1.981
1.981
1.980
1.980
1.979
1.979
Crossover
bar
1.978
1.978
1.977
1.977
1.976
1.976
Dec 24 00:00
Dec 24 04:00
Dec 24 08:00
Guy Yollin (Copyright 2014)
Dec 24 12:00
Dec 26 02:00
Dec 26 06:00
Dec 26 10:00
Introduction to Trading Systems
Dec 26 14:30 Dec 26 18:00
Dec 26 22:00
Quantmod
73 / 74
Computational Finance and Risk Management
http://depts.washington.edu/compfin
Guy Yollin (Copyright 2014)
Introduction to Trading Systems
Quantmod
74 / 74