the quantmod package

64
Computational Finance and Risk Management The quantmod package September, 2011 Guy Yollin Principal Consultant, r-programming.org Visiting Lecturer, University of Washington Guy Yollin (Copyright 2011) R for Finance quantmod 1 / 64

Upload: lycancapital

Post on 28-Apr-2015

391 views

Category:

Documents


1 download

DESCRIPTION

The quantmod package

TRANSCRIPT

Page 1: The quantmod package

40 60 80 100 120

40

60

80

mm

Computational Finance and Risk Management

The quantmod package

September, 2011

Guy YollinPrincipal Consultant, r-programming.org

Visiting Lecturer, University of Washington

Guy Yollin (Copyright© 2011) R for Finance quantmod 1 / 64

Page 2: The quantmod package

40 60 80 100 120

40

60

80

mm

Outline

1 Introduction to R for Finance

2 Introduction to data retrieval and charting

3 Time series in R

4 More data retrieval

5 Technical indicators and TTR

6 High frequency example

Guy Yollin (Copyright© 2011) R for Finance quantmod 2 / 64

Page 3: The quantmod package

40 60 80 100 120

40

60

80

mm

Outline

1 Introduction to R for Finance

2 Introduction to data retrieval and charting

3 Time series in R

4 More data retrieval

5 Technical indicators and TTR

6 High frequency example

Guy Yollin (Copyright© 2011) R for Finance quantmod 3 / 64

Page 4: The quantmod package

40 60 80 100 120

40

60

80

mm

The R programming language

R is a language and environment for statistical computing andgraphics

R is based on the S language originally developed by John Chambersand colleagues at AT&T Bell Labs in the late 1970s and 1980s

R (sometimes called“GNU S” ) is free open source software licensedunder the GNU general public license (GPL 2)

R development was initiated by Robert Gentleman and Ross Ihaka atthe University of Auckland, New Zealand in the early 1990s

R is formally known as The R Project for Statistical Computing

www.r-project.org

Guy Yollin (Copyright© 2011) R for Finance quantmod 4 / 64

Page 5: The quantmod package

40 60 80 100 120

40

60

80

mm

R timeline

1976 2011

Work on S

Version 1

Exponential

growth of

R Users and

R packages

1993

StatSci Licenses S

1999

John Chambers

1998 ACM Software Award

2010

R & R

Given ASA

Statistical Computing

and Graphics Award

1997

Modern Applied Statistics

with S-PLUS

2nd Edition

2004

R 2.0.0

1984

S: An Interactive Envirnoment for

Data Analysis and Graphics

(Brown Book)1988

The New S Language

Written in C

(Blue Book)

1993

R on Statlib

1991

Statistical Models in S

(white book)

S3 methods

1999

Modern Applied Statistics

with S-PLUS

3rd Edition

(S+ 2000, 5.x)

(R complements)

1997

R on CRAN

GNU Project

2002

Modern Applied Statistics

with S

4th Edition

(S+ 6.x, R 1.5.0)

1988

S-PLULS

developed by

Statistical Sciences, Inc.

2001

R 1.4.0

(S4)

1998

Programming with Data

(Green Book)

(S+ 5.x)

1994

Modern Applied Statistics

with S-PLUS

2000

R 1.0.0

(S3)

S era S-PLUS era R era

Guy Yollin (Copyright© 2011) R for Finance quantmod 5 / 64

Page 6: The quantmod package

40 60 80 100 120

40

60

80

mm

Finance Task View

There are many R packages for computational finance; a description ofthese packages can be found on the Finance Task View of CRAN:

http://cran.r-project.org/web/views/Finance.html

Guy Yollin (Copyright© 2011) R for Finance quantmod 6 / 64

Page 7: The quantmod package

40 60 80 100 120

40

60

80

mm

R-SIG-FINANCE

https://stat.ethz.ch/mailman/

listinfo/r-sig-finance

Nerve center of the R financecommunity

Daily must read

Exclusively for Finance-specificquestions, not general Rquestions

Guy Yollin (Copyright© 2011) R for Finance quantmod 7 / 64

Page 8: The quantmod package

40 60 80 100 120

40

60

80

mm

Packages for trading system development in R

Data access, charting, indicators

Time series objects

Quantitative trading rules and trading accouting

Performance metrics and graphs

zoo: ordered observations

xts: extensible time series

TTR: technical trading rules

quantmod: quantitative financial modelling framework

blotter: tools for transaction-oriented trading systems development

quantstrat: quantitative strategy model framework

PerformanceAnalytics: Econometric tools for performance and risk analysis

Guy Yollin (Copyright© 2011) R for Finance quantmod 8 / 64

Page 9: The quantmod package

40 60 80 100 120

40

60

80

mm

Lecture references

quantmod package

Jeffrey Ryan’s quantmod website:http://www.quantmod.com/

quantmod project page on R-forge:http://r-forge.r-project.org/projects/quantmod

TTR package

Joshua Ulrich’s 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© 2011) R for Finance quantmod 9 / 64

Page 10: The quantmod package

40 60 80 100 120

40

60

80

mm

R-forge

R-forge is a hosting platform for R package development whichincludes 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 thetrading system development packages mentioned earlier

It is common for new packages to be developed on R-forge and formature packages to be maintained on R-forge even after being hostedon CRAN

R-forge packages can be installed as follows:

R Code: Install packages from R-forge

> install.packages("xts", repos = "http://R-Forge.R-project.org",lib=.Library)

> install.packages("TTR", repos = "http://R-Forge.R-project.org",lib=.Library)

> install.packages("quantmod",repos="http://R-Forge.R-project.org",lib=.Library)

Guy Yollin (Copyright© 2011) R for Finance quantmod 10 / 64

Page 11: The quantmod package

40 60 80 100 120

40

60

80

mm

Outline

1 Introduction to R for Finance

2 Introduction to data retrieval and charting

3 Time series in R

4 More data retrieval

5 Technical indicators and TTR

6 High frequency example

Guy Yollin (Copyright© 2011) R for Finance quantmod 11 / 64

Page 12: The quantmod package

40 60 80 100 120

40

60

80

mm

The quantmod package

The quantmod package for R is designed to assist the quantitative traderin the development, testing, and deployment of statistically based tradingmodels.

Key functions:

getSymbols load or download price data

Yahoo Finance / Google FinanceFREDOandacsv, RDataMySQL, SQLite

chartSeries charting tool to create standard financial charts

Author:

Jeffrey Ryan

Guy Yollin (Copyright© 2011) R for Finance quantmod 12 / 64

Page 13: The quantmod package

40 60 80 100 120

40

60

80

mm

The getSymbols function

The getSymbols function loads (downloads) historic price data

R Code: The getSymbols function

> library(quantmod)

> args(getSymbols)

function (Symbols = NULL, env = .GlobalEnv, reload.Symbols = FALSE,

verbose = FALSE, warnings = TRUE, src = "yahoo", symbol.lookup = TRUE,

auto.assign = TRUE, ...)

NULL

Main arguments:

Symbols symbols to be loaded

src source of the data

Return value:

a time series object

Guy Yollin (Copyright© 2011) R for Finance quantmod 13 / 64

Page 14: The quantmod package

40 60 80 100 120

40

60

80

mm

The getSymbols function

R Code: Download prices from Yahoo

> getSymbols("^GSPC")

[1] "GSPC"

> ls()

[1] "GSPC"

> showSymbols()

GSPC

"yahoo"

> first(GSPC)

GSPC.Open GSPC.High GSPC.Low GSPC.Close GSPC.Volume GSPC.Adjusted

2007-01-03 1418.03 1429.42 1407.86 1416.6 3429160000 1416.6

> last(GSPC)

GSPC.Open GSPC.High GSPC.Low GSPC.Close GSPC.Volume GSPC.Adjusted

2011-09-06 1173.97 1173.97 1140.13 1165.24 5103980000 1165.24

> class(GSPC)

[1] "xts" "zoo"

Guy Yollin (Copyright© 2011) R for Finance quantmod 14 / 64

Page 15: The quantmod package

40 60 80 100 120

40

60

80

mm

The chartSeries function

The chartSeries function creates financial charts

R Code: The chartSeries function

> args(chartSeries)

function (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,

...)

NULL

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

Guy Yollin (Copyright© 2011) R for Finance quantmod 15 / 64

Page 16: The quantmod package

40 60 80 100 120

40

60

80

mm

The chartSeries function

R Code: The chartSeries function

> chartSeries(GSPC,subset="2011",theme="white")

1100

1150

1200

1250

1300

1350

GSPC [2011−01−03/2011−09−06]

Last 1165.24

Volume (millions):5,103,980,000

100020003000400050006000

Jan 032011

Feb 012011

Mar 012011

Apr 012011

May 022011

Jun 012011

Jul 012011

Aug 012011

Sep 012011

Guy Yollin (Copyright© 2011) R for Finance quantmod 16 / 64

Page 17: The quantmod package

40 60 80 100 120

40

60

80

mm

Customize a chartSeries plot

R Code: Customize a chartSeries plot

> whiteTheme <- chartTheme("white")

> names(whiteTheme)

[1] "fg.col" "bg.col" "grid.col" "border" "minor.tick"

[6] "major.tick" "up.col" "dn.col" "dn.up.col" "up.up.col"

[11] "dn.dn.col" "up.dn.col" "up.border" "dn.border" "dn.up.border"

[16] "up.up.border" "dn.dn.border" "up.dn.border" "main.col" "sub.col"

[21] "area" "fill" "Expiry" "theme.name"

> whiteTheme$bg.col <- "white"

> whiteTheme$dn.col <- "pink"

> whiteTheme$up.col <- "lightgreen"

> whiteTheme$border <- "lightgray"

> x <- chartSeries(GSPC,subset="2011",theme=whiteTheme,TA=NULL)

> class(x)

[1] "chob"

attr(,"package")

[1] "quantmod"

totally white backgroundno volume sub-graph (TA=NULL)

Guy Yollin (Copyright© 2011) R for Finance quantmod 17 / 64

Page 18: The quantmod package

40 60 80 100 120

40

60

80

mm

A chartSeries plot

1100

1150

1200

1250

1300

1350

GSPC [2011−01−03/2011−09−06]

Jan 032011

Mar 012011

Apr 012011

Jun 012011

Jul 012011

Sep 012011

Guy Yollin (Copyright© 2011) R for Finance quantmod 18 / 64

Page 19: The quantmod package

40 60 80 100 120

40

60

80

mm

Outline

1 Introduction to R for Finance

2 Introduction to data retrieval and charting

3 Time series in R

4 More data retrieval

5 Technical indicators and TTR

6 High frequency example

Guy Yollin (Copyright© 2011) R for Finance quantmod 19 / 64

Page 20: The quantmod package

40 60 80 100 120

40

60

80

mm

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© 2011) R for Finance quantmod 20 / 64

Page 21: The quantmod package

40 60 80 100 120

40

60

80

mm

Time series data

Time series

A time series is a sequence of observations in chronological order

Time series object

A time series object in R is a compound data object that includes a datamatrix as well as a vector of associated time stamps

class package overviewts base regularly spaced time seriesmts base multiple regularly spaced time seriestimeSeries rmetrics default for Rmetrics packageszoo zoo reg/irreg and arbitrary time stamp classesxts xts an extension of the zoo class

Guy Yollin (Copyright© 2011) R for Finance quantmod 21 / 64

Page 22: The quantmod package

40 60 80 100 120

40

60

80

mm

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

Guy Yollin (Copyright© 2011) R for Finance quantmod 22 / 64

Page 23: The quantmod package

40 60 80 100 120

40

60

80

mm

The zoo package

The zoo package provides an infrastructure for regularly-spaced andirregularly-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

readzoo read a text file into a zoo time series object

Authors:

Achim Zeileis

Gabor Grothendieck

Guy Yollin (Copyright© 2011) R for Finance quantmod 23 / 64

Page 24: The quantmod package

40 60 80 100 120

40

60

80

mm

The xts package

The xts package extends the zoo time series class with fine-grained timeindexes, interoperability with other R time series classes, and user definedattributes

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© 2011) R for Finance quantmod 24 / 64

Page 25: The quantmod package

40 60 80 100 120

40

60

80

mm

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-stampof observations

Matrix the time series observations (univariate or multivariate)

can be numeric, character, logical, etc. but must behomogeneous

Attr hidden attributes and user attributes

class of the indexformat of the indextime zone

Guy Yollin (Copyright© 2011) R for Finance quantmod 25 / 64

Page 26: The quantmod package

40 60 80 100 120

40

60

80

mm

Date class

Date Dates are represented as the number of days since 1970-01-01

R Code: Date class examples

> myStr <- "2011-07-04"

> class(myStr)

[1] "character"

> myDate <- as.Date(myStr)

> class(myDate)

[1] "Date"

> as.numeric(myDate)

[1] 15159

> format(myDate,"%m/%d/%y")

[1] "07/04/11"

> as.Date("110704",format="%y%m%d")

[1] "2011-07-04"

Guy Yollin (Copyright© 2011) R for Finance quantmod 26 / 64

Page 27: The quantmod package

40 60 80 100 120

40

60

80

mm

Date-time classes

POSIXct represents time and date as the number of seconds since1970-01-01

POSIXlt represents time and date as 9 calendar and timecomponents

R Code: POSIXct and POSIXlt examples

> d <- Sys.time()

> class(d)

[1] "POSIXct" "POSIXt"

> unclass(d)

[1] 1315440935

> sapply(unclass(as.POSIXlt(d)), function(x) x)

sec min hour mday mon year wday yday

34.94161 15.00000 0.00000 8.00000 8.00000 111.00000 4.00000 250.00000

isdst

0.00000

Guy Yollin (Copyright© 2011) R for Finance quantmod 27 / 64

Page 28: The quantmod package

40 60 80 100 120

40

60

80

mm

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/20112011-04::2011-07

Guy Yollin (Copyright© 2011) R for Finance quantmod 28 / 64

Page 29: The quantmod package

40 60 80 100 120

40

60

80

mm

xts subsetting

R Code: Subset xts object

> chartSeries(GSPC["2011"],theme=whiteTheme,name="S&P 500")

1100

1150

1200

1250

1300

1350

S&P 500 [2011−01−03/2011−09−06]

Last 1165.24

Volume (millions):5,103,980,000

100020003000400050006000

Jan 032011

Mar 012011

Apr 012011

Jun 012011

Jul 012011

Sep 012011

Guy Yollin (Copyright© 2011) R for Finance quantmod 29 / 64

Page 30: The quantmod package

40 60 80 100 120

40

60

80

mm

xts subsetting

R Code: Subset xts object

> chartSeries(GSPC["2010/2011"],theme=whiteTheme,name="S&P 500")

1000

1050

1100

1150

1200

1250

1300

1350

S&P 500 [2010−01−04/2011−09−06]

Last 1165.24

Volume (millions):5,103,980,000

2000400060008000

10000

Jan 042010

Apr 012010

Jul 012010

Oct 012010

Jan 032011

Apr 012011

Jul 012011

Guy Yollin (Copyright© 2011) R for Finance quantmod 30 / 64

Page 31: The quantmod package

40 60 80 100 120

40

60

80

mm

xts subsetting

R Code: Subset xts object

> chartSeries(GSPC["201107"],theme=whiteTheme,name="S&P 500")

1280

1300

1320

1340

S&P 500 [2011−07−01/2011−07−29]

Last 1292.28

Volume (millions):5,061,190,000

3500

4000

4500

5000

Jul 012011

Jul 072011

Jul 122011

Jul 152011

Jul 202011

Jul 252011

Jul 282011

Guy Yollin (Copyright© 2011) R for Finance quantmod 31 / 64

Page 32: The quantmod package

40 60 80 100 120

40

60

80

mm

xts subsetting

R Code: Subset xts object

> chartSeries(GSPC["2011-04::2011-07"],theme=whiteTheme,name="S&P 500")

1260

1280

1300

1320

1340

1360

S&P 500 [2011−04−01/2011−07−29]

Last 1292.28

Volume (millions):5,061,190,000

250030003500400045005000

Apr 012011

Apr 182011

May 092011

May 312011

Jun 202011

Jul 052011

Jul 252011

Guy Yollin (Copyright© 2011) R for Finance quantmod 32 / 64

Page 33: The quantmod package

40 60 80 100 120

40

60

80

mm

Outline

1 Introduction to R for Finance

2 Introduction to data retrieval and charting

3 Time series in R

4 More data retrieval

5 Technical indicators and TTR

6 High frequency example

Guy Yollin (Copyright© 2011) R for Finance quantmod 33 / 64

Page 34: The quantmod package

40 60 80 100 120

40

60

80

mm

The getSymbols.yahoo function

The getSymbols.yahoo downloads symbols from finance.yahoo.com

R Code: The getSymbols.yahoo function

> args(getSymbols.yahoo)

function (Symbols, env, return.class = "xts", index.class = "Date",

from = "2007-01-01", to = Sys.Date(), ...)

NULL

Arguments:

return.class time series class of returned object

index.class class of date/time index

from starting date of time series

to ending date of time series

adjust adjust time series for splits/dividends (T/F)

Guy Yollin (Copyright© 2011) R for Finance quantmod 34 / 64

Page 35: The quantmod package

40 60 80 100 120

40

60

80

mm

Download historic quotes: specifying the start date

R Code: Get historic data from a specified start date

> getSymbols("SPY",from="2000-01-01")

[1] "SPY"

> head(SPY)

SPY.Open SPY.High SPY.Low SPY.Close SPY.Volume SPY.Adjusted

2000-01-03 148.25 148.25 143.88 145.44 8164300 119.60

2000-01-04 143.53 144.06 139.64 139.75 8089800 114.92

2000-01-05 139.94 141.53 137.25 140.00 12177900 115.13

2000-01-06 139.63 141.50 137.75 137.75 6227200 113.28

2000-01-07 140.31 145.75 140.06 145.75 8066500 119.85

2000-01-10 146.25 146.91 145.03 146.25 5741700 120.27

> 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© 2011) R for Finance quantmod 35 / 64

Page 36: The quantmod package

40 60 80 100 120

40

60

80

mm

Download historic quotes: specifying the time stamp class

R Code: Get historic data and return a time-date class

> getSymbols("SBUX",index.class="POSIXct",from="2000-01-01")

[1] "SBUX"

> head(SBUX)

SBUX.Open SBUX.High SBUX.Low SBUX.Close SBUX.Volume SBUX.Adjusted

2000-01-03 23.87 24.69 23.25 24.66 12136400 6.01

2000-01-04 24.06 24.87 23.75 23.87 10795200 5.82

2000-01-05 23.94 24.62 23.69 24.19 14116400 5.90

2000-01-06 24.00 25.62 24.00 25.06 15420000 6.11

2000-01-07 24.75 25.00 24.25 24.94 13035200 6.08

2000-01-10 25.87 26.75 25.81 26.00 14535600 6.34

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

Guy Yollin (Copyright© 2011) R for Finance quantmod 36 / 64

Page 37: The quantmod package

40 60 80 100 120

40

60

80

mm

Unadjusted SBUX data

10

20

30

40

50

60

SBUX [2000−01−03/2011−09−07]

Last 39.18

Volume (millions):8,398,900

0

50

100

150

Jan 032000

Jul 022001

Jul 012002

Jul 012003

Jul 012004

Jul 012005

Jul 032006

Jul 022007

Jul 012008

Jul 012009

Jul 012010

Jul 012011

Guy Yollin (Copyright© 2011) R for Finance quantmod 37 / 64

Page 38: The quantmod package

40 60 80 100 120

40

60

80

mm

Get stock splits and dividend history

R Code: Get stock splits and dividend history

> (spl <- getSplits("SBUX"))

SBUX.spl

1993-09-30 0.5

1995-12-04 0.5

1999-03-22 0.5

2001-04-30 0.5

2005-10-24 0.5

> class(spl)

[1] "xts" "zoo"

> (div <- getDividends("SBUX"))

[,1]

2010-04-05 0.10

2010-08-02 0.13

2010-11-16 0.13

2011-02-07 0.13

2011-05-09 0.13

2011-08-08 0.13

> class(div)

[1] "xts" "zoo"Guy Yollin (Copyright© 2011) R for Finance quantmod 38 / 64

Page 39: The quantmod package

40 60 80 100 120

40

60

80

mm

The adjustOHLC function

The adjustOHLC adjusts all columns of an OHLC object for split anddividend

R Code: The adjustOHLC function

> args(adjustOHLC)

function (x, adjust = c("split", "dividend"), use.Adjusted = FALSE,

ratio = NULL, symbol.name = deparse(substitute(x)))

NULL

Arguments:

x an OHLC object

use.Adjusted calculated from dividends and splits (F), or used Adjustedprice column (T)

Note from package author:

Using use.Adjusted = TRUE will be less precise than the method that employs actual splitand dividend information.

Guy Yollin (Copyright© 2011) R for Finance quantmod 39 / 64

Page 40: The quantmod package

40 60 80 100 120

40

60

80

mm

Adjust for split and dividend

R Code: Adjust for split and dividend

> head(SBUX)

SBUX.Open SBUX.High SBUX.Low SBUX.Close SBUX.Volume SBUX.Adjusted

2000-01-03 23.87 24.69 23.25 24.66 12136400 6.01

2000-01-04 24.06 24.87 23.75 23.87 10795200 5.82

2000-01-05 23.94 24.62 23.69 24.19 14116400 5.90

2000-01-06 24.00 25.62 24.00 25.06 15420000 6.11

2000-01-07 24.75 25.00 24.25 24.94 13035200 6.08

2000-01-10 25.87 26.75 25.81 26.00 14535600 6.34

> adj1 <- adjustOHLC(SBUX)

> head(adj1)

SBUX.Open SBUX.High SBUX.Low SBUX.Close SBUX.Volume SBUX.Adjusted

2000-01-03 5.821792 6.021786 5.670577 6.014470 12136400 6.01

2000-01-04 5.868132 6.065688 5.792524 5.821792 10795200 5.82

2000-01-05 5.838865 6.004714 5.777891 5.899839 14116400 5.90

2000-01-06 5.853498 6.248610 5.853498 6.112028 15420000 6.11

2000-01-07 6.036420 6.097394 5.914472 6.082760 13035200 6.08

2000-01-10 6.309584 6.524212 6.294950 6.341290 14535600 6.34

Guy Yollin (Copyright© 2011) R for Finance quantmod 40 / 64

Page 41: The quantmod package

40 60 80 100 120

40

60

80

mm

Compare adjustment methods

R Code: Adjust for split and dividend and compare results

> head(adj1)

SBUX.Open SBUX.High SBUX.Low SBUX.Close SBUX.Volume SBUX.Adjusted

2000-01-03 5.821792 6.021786 5.670577 6.014470 12136400 6.01

2000-01-04 5.868132 6.065688 5.792524 5.821792 10795200 5.82

2000-01-05 5.838865 6.004714 5.777891 5.899839 14116400 5.90

2000-01-06 5.853498 6.248610 5.853498 6.112028 15420000 6.11

2000-01-07 6.036420 6.097394 5.914472 6.082760 13035200 6.08

2000-01-10 6.309584 6.524212 6.294950 6.341290 14535600 6.34

> adj2 <- adjustOHLC(SBUX, use.Adjusted=TRUE)

> head(adj2)

SBUX.Open SBUX.High SBUX.Low SBUX.Close SBUX.Volume SBUX.Adjusted

2000-01-03 5.817466 6.017311 5.666363 6.01 12136400 6.01

2000-01-04 5.866326 6.063821 5.790742 5.82 10795200 5.82

2000-01-05 5.839024 6.004878 5.778049 5.90 14116400 5.90

2000-01-06 5.851556 6.246536 5.851556 6.11 15420000 6.11

2000-01-07 6.033681 6.094627 5.911788 6.08 13035200 6.08

2000-01-10 6.308300 6.522885 6.293669 6.34 14535600 6.34

> chartSeries(adj1,theme=whiteTheme,name="SBUX")

Guy Yollin (Copyright© 2011) R for Finance quantmod 41 / 64

Page 42: The quantmod package

40 60 80 100 120

40

60

80

mm

Adjusted SBUX plot

5

10

15

20

25

30

35

40

SBUX [2000−01−03/2011−09−07]

Last 39.18

Volume (millions):8,398,900

0

50

100

150

Jan 032000

Jul 022001

Jul 012002

Jul 012003

Jul 012004

Jul 012005

Jul 032006

Jul 022007

Jul 012008

Jul 012009

Jul 012010

Jul 012011

Guy Yollin (Copyright© 2011) R for Finance quantmod 42 / 64

Page 43: The quantmod package

40 60 80 100 120

40

60

80

mm

Download historic quotes: specifying adjusted OHLC

R Code: Get historic data and return adjusted OHLC

> getSymbols("SBUX",index.class="POSIXct",from="2000-01-01",adjust=T)

[1] "SBUX"

> head(SBUX)

SBUX.Open SBUX.High SBUX.Low SBUX.Close SBUX.Volume SBUX.Adjusted

2000-01-03 5.821792 6.021786 5.670577 6.014470 12440150 6.01

2000-01-04 5.868132 6.065688 5.792524 5.821792 11065383 5.82

2000-01-05 5.838865 6.004714 5.777891 5.899839 14469706 5.90

2000-01-06 5.853498 6.248610 5.853498 6.112028 15805932 6.11

2000-01-07 6.036420 6.097394 5.914472 6.082760 13361445 6.08

2000-01-10 6.309584 6.524212 6.294950 6.341290 14899398 6.34

> head(adj1)

SBUX.Open SBUX.High SBUX.Low SBUX.Close SBUX.Volume SBUX.Adjusted

2000-01-03 5.821792 6.021786 5.670577 6.014470 12136400 6.01

2000-01-04 5.868132 6.065688 5.792524 5.821792 10795200 5.82

2000-01-05 5.838865 6.004714 5.777891 5.899839 14116400 5.90

2000-01-06 5.853498 6.248610 5.853498 6.112028 15420000 6.11

2000-01-07 6.036420 6.097394 5.914472 6.082760 13035200 6.08

2000-01-10 6.309584 6.524212 6.294950 6.341290 14535600 6.34

Guy Yollin (Copyright© 2011) R for Finance quantmod 43 / 64

Page 44: The quantmod package

40 60 80 100 120

40

60

80

mm

Federal reserve economic data

The function getSymbols can also be used to access data from theFederal Reserve Economic Data (FRED) database

Guy Yollin (Copyright© 2011) R for Finance quantmod 44 / 64

Page 45: The quantmod package

40 60 80 100 120

40

60

80

mm

Download interest rate data from FRED

R Code: Download interest rate data from FRED

> getSymbols('DTB3',src='FRED')

[1] "DTB3"

> first(DTB3,'1 week')

DTB3

1954-01-04 1.33

> last(DTB3,'1 week')

DTB3

2011-08-29 0.02

2011-08-30 0.01

2011-08-31 0.02

2011-09-01 0.02

2011-09-02 0.02

> chartSeries(DTB3,theme="white")

Guy Yollin (Copyright© 2011) R for Finance quantmod 45 / 64

Page 46: The quantmod package

40 60 80 100 120

40

60

80

mm

Three-month U.S. Treasury bill rate

0

5

10

15

DTB3 [1954−01−04/2011−09−02]

Last 0.02

Jan 041954

Jan 041960

Jan 031966

Jan 031972

Jan 031978

Jan 031984

Jan 021990

Jan 021996

Jan 022002

Jan 022008

Guy Yollin (Copyright© 2011) R for Finance quantmod 46 / 64

Page 47: The quantmod package

40 60 80 100 120

40

60

80

mm

Outline

1 Introduction to R for Finance

2 Introduction to data retrieval and charting

3 Time series in R

4 More data retrieval

5 Technical indicators and TTR

6 High frequency example

Guy Yollin (Copyright© 2011) R for Finance quantmod 47 / 64

Page 48: The quantmod package

40 60 80 100 120

40

60

80

mm

The TTR package

The TTR package is a comprehensive collection of technical analysisindicators for R

Key features:

moving averages

oscillators

price channels

trend indicators

Author:

Joshua Ulrich

Guy Yollin (Copyright© 2011) R for Finance quantmod 48 / 64

Page 49: The quantmod package

40 60 80 100 120

40

60

80

mm

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 William’s % R ZigZag Zig Zag trend line

Technical Analysis from A to Z by Steven AchelisGuy Yollin (Copyright© 2011) R for Finance quantmod 49 / 64

Page 50: The quantmod package

40 60 80 100 120

40

60

80

mm

Calculate and plot Bollinger bands

R Code: Plot and calculate Bollinger bands

> b <- BBands(HLC=HLC(SBUX["2011"]), n=20, sd=2)

> tail(b,10)

dn mavg up pctB

2011-08-24 33.83678 37.24133 40.64587 0.4748383

2011-08-25 33.90271 37.08908 40.27544 0.4582998

2011-08-26 34.03176 36.93900 39.84625 0.4984514

2011-08-29 34.20780 36.84324 39.47869 0.7004892

2011-08-30 34.24769 36.81947 39.39126 0.7949691

2011-08-31 34.24530 36.82068 39.39607 0.8732743

2011-09-01 34.21113 36.86701 39.52290 0.7967595

2011-09-02 34.25267 36.92300 39.59333 0.6317563

2011-09-06 34.54411 37.04633 39.54855 0.5580152

2011-09-07 34.74668 37.22483 39.70299 0.8252080

> chartSeries(SBUX,TA='addBBands();addBBands(draw="p");addVo()',

subset='2011',theme="white")

Guy Yollin (Copyright© 2011) R for Finance quantmod 50 / 64

Page 51: The quantmod package

40 60 80 100 120

40

60

80

mm

Bollinger bands

30

32

34

36

38

40

SBUX [2011−01−03/2011−09−07]

Last 39.18Bollinger Bands (20,2) [Upper/Lower]: 39.703/34.747

Bollinger %b (20,2): 0.825

0.0

0.5

1.0

1.5

Volume (millions):8,398,900

5

10

15

20

25

30

35

Jan 032011

Feb 012011

Mar 012011

Apr 012011

May 022011

Jun 012011

Jul 012011

Aug 012011

Sep 012011

Guy Yollin (Copyright© 2011) R for Finance quantmod 51 / 64

Page 52: The quantmod package

40 60 80 100 120

40

60

80

mm

MACD and DPO

R Code: MACD and DPO

> macd <- MACD( Cl(SBUX), 12, 26, 9, maType="EMA" )

> last(macd,'1 week')

macd signal

2011-09-06 0.01005927 -0.4979056

2011-09-07 0.34641082 -0.3290423

> priceDPO <- DPO(Cl(SBUX))

> tail(na.omit(priceDPO))

SBUX.Close

2011-08-22 -1.900

2011-08-23 -0.052

2011-08-24 0.244

2011-08-25 -0.945

2011-08-26 -0.261

2011-08-29 0.154

> chartSeries(SBUX, TA = "addMACD();addDPO()",subset="2011",theme=whiteTheme)

Guy Yollin (Copyright© 2011) R for Finance quantmod 52 / 64

Page 53: The quantmod package

40 60 80 100 120

40

60

80

mm

MACD and DPO

30

32

34

36

38

40

SBUX [2011−01−03/2011−09−07]

Last 39.18

Moving Average Convergence Divergence (12,26,9):MACD: 0.346Signal: −0.329

−3−2−1

0123

De−trended Price Oscillator (10):0.130

−4

−2

0

2

4

Jan 032011

Feb 012011

Mar 012011

Apr 012011

May 022011

Jun 012011

Jul 012011

Aug 012011

Sep 012011

Guy Yollin (Copyright© 2011) R for Finance quantmod 53 / 64

Page 54: The quantmod package

40 60 80 100 120

40

60

80

mm

Experimental chart_Series chart

R Code: Plot and calculate Bollinger bands

The chartSeries functions are in the process of being updated;quantmod functions incorporating an underscore in their name areexperimental 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["2011"],theme=myTheme,name="SBUX")

> plot(add_BBands(on=1,sd=2,n=20,lwd=2,col=4))

Guy Yollin (Copyright© 2011) R for Finance quantmod 54 / 64

Page 55: The quantmod package

40 60 80 100 120

40

60

80

mm

Experimental chart_Series chart

Jan Feb Mar Apr May Jun Jul Aug Sep

Jan 032011

Feb 012011

Mar 012011

Apr 012011

May 022011

Jun 012011

Jul 012011

Aug 012011

Sep 012011

SBUX 2011−01−03 / 2011−09−07

31

32

33

34

35

36

37

38

39

40

41

42

31

32

33

34

35

36

37

38

39

40

41

42

Guy Yollin (Copyright© 2011) R for Finance quantmod 55 / 64

Page 56: The quantmod package

40 60 80 100 120

40

60

80

mm

Outline

1 Introduction to R for Finance

2 Introduction to data retrieval and charting

3 Time series in R

4 More data retrieval

5 Technical indicators and TTR

6 High frequency example

Guy Yollin (Copyright© 2011) R for Finance quantmod 56 / 64

Page 57: The quantmod package

40 60 80 100 120

40

60

80

mm

High-frequency versus low-frequency time series analysis

High-frequency begins when indexing by date alone is not enoughbeyond the capabilities of zoo objects with Date indexes

intra-day barstick data

High-frequency time series require formal time-based classes forindexing

Recommended classes for high-frequency time series:

xts (extensible time series) classPOSIXct/POSIXlt date-time class for indexing

Class Low frequency High Frequency

time series class zoo xts

time index class Date POSIXlt

Guy Yollin (Copyright© 2011) R for Finance quantmod 57 / 64

Page 58: The quantmod package

40 60 80 100 120

40

60

80

mm

The strptime function

The strptime function converts character strings to POSIXlt date-timeobjects

R Code: The strptime function

> args(strptime)

function (x, format, tz = "")

NULL

Arguments:

x vector of character strings to be converted to POSIXltobjects

format date-time format specification

tz timezone to use for conversion

Return value:

POSIXlt object(s)

Guy Yollin (Copyright© 2011) R for Finance quantmod 58 / 64

Page 59: The quantmod package

40 60 80 100 120

40

60

80

mm

The xts function

The function xts is the constructor function for extensible time-seriesobjects

R Code: The xts function

> library(xts)

> args(xts)

function (x = NULL, order.by = index(x), frequency = NULL, unique = TRUE,

tzone = Sys.getenv("TZ"), ...)

NULL

Arguments:

x data matrix (or vector) with time series data

order.by vector of unique times/dates (POSIXct is recommended)

Return value:

xts object

Guy Yollin (Copyright© 2011) R for Finance quantmod 59 / 64

Page 60: The quantmod package

40 60 80 100 120

40

60

80

mm

Read GBPUSD 30-minute bars

R Code: Read GBPUSD 30-minute bars

> fn1 <- "GBPUSD.txt"

> dat <- read.table(file=fn1,sep=",",header=T,as.is=T)

> head(dat)

Date Time Open High Low Close Up Down

1 10/20/2002 2330 1.5501 1.5501 1.5481 1.5482 0 0

2 10/21/2002 0 1.5481 1.5483 1.5472 1.5472 0 0

3 10/21/2002 30 1.5471 1.5480 1.5470 1.5478 0 0

4 10/21/2002 100 1.5477 1.5481 1.5471 1.5480 0 0

5 10/21/2002 130 1.5480 1.5501 1.5479 1.5493 0 0

6 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" "2002-10-21 00:00:00" "2002-10-21 00:30:00"

[4] "2002-10-21 01:00:00" "2002-10-21 01:30:00" "2002-10-21 02:00:00"

Guy Yollin (Copyright© 2011) R for Finance quantmod 60 / 64

Page 61: The quantmod package

40 60 80 100 120

40

60

80

mm

Create and plot xts object

R Code: Create and plot xts object

> GBP <- xts(x=dat[,c("Open","High","Low","Close")],order.by=tm)

> GBP <- GBP['2007']

> first(GBP,'4 hours')

Open High Low Close

2007-01-01 17:30:00 1.9649 1.9650 1.9644 1.9645

2007-01-01 18:00:00 1.9646 1.9648 1.9641 1.9644

2007-01-01 18:30:00 1.9645 1.9653 1.9645 1.9650

2007-01-01 19:00:00 1.9651 1.9652 1.9647 1.9650

2007-01-01 19:30:00 1.9651 1.9658 1.9651 1.9654

2007-01-01 20:00:00 1.9655 1.9657 1.9650 1.9654

2007-01-01 20:30:00 1.9653 1.9656 1.9651 1.9655

> barChart(GBP,TA='addSMA(n = 6, col = "red");addSMA(n = 45, col = "blue")',

subset='2007-12-24/2007-12-26',theme="white",name="GBPUSD")

Guy Yollin (Copyright© 2011) R for Finance quantmod 61 / 64

Page 62: The quantmod package

40 60 80 100 120

40

60

80

mm

GBPUSD crossover example

1.976

1.978

1.980

1.982

1.984

1.986

1.988

GBPUSD [2007−12−24/2007−12−26 23:30:00]

Last 1.98542

Dec 2400:00

Dec 2404:00

Dec 2408:00

Dec 2412:00

Dec 2602:00

Dec 2606:00

Dec 2610:00

Dec 2614:30

Dec 2620:00

Guy Yollin (Copyright© 2011) R for Finance quantmod 62 / 64

Page 63: The quantmod package

40 60 80 100 120

40

60

80

mm

GBPUSD crossover example with annotation

Dec 24 00:00 Dec 24 04:00 Dec 24 08:00 Dec 24 12:00 Dec 26 00:00 Dec 26 04:00 Dec 26 08:00 Dec 26 12:00 Dec 26 16:00 Dec 26 20:00 Dec 26 23:30

GBPUSD 2007−12−24 / 2007−12−26 23:30:00

1.976

1.977

1.978

1.979

1.980

1.981

1.982

1.983

1.984

1.985

1.986

1.987

1.988

1.976

1.977

1.978

1.979

1.980

1.981

1.982

1.983

1.984

1.985

1.986

1.987

1.988

Crossoverbar

Guy Yollin (Copyright© 2011) R for Finance quantmod 63 / 64

Page 64: The quantmod package

40 60 80 100 120

40

60

80

mm

GBPUSD crossover example with annotation

R Code: GBPUSD crossover example with annotation

> fastMA <- SMA(Cl(GBP),n=6)

> slowMA <- SMA(Cl(GBP),n=45)

> co <- fastMA > slowMA

> x <- which(co['2007-12-24/2007-12-26'])[1]

> ss <- GBP['2007-12-24/2007-12-26']

> chart_Series(GBP,subset='2007-12-24/2007-12-26',theme=myTheme,name="GBPUSD",

TA='add_SMA(n=6,col="red",lwd=2);add_SMA(n=45,col="blue",lwd=2)')

> 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© 2011) R for Finance quantmod 64 / 64