Sie sind auf Seite 1von 64

Computational Finance and Risk Management

mm 40 60 80 100 120

The quantmod package


40

September, 2011
60

Guy Yollin
Principal Consultant, r-programming.org Visiting Lecturer, University of Washington

80

Guy Yollin (Copyright

2011)

R for Finance

quantmod

1 / 64

Outline
mm
1

40

60

80

100

120

Introduction to R for Finance Introduction to data retrieval and charting


40

Time series in R More data retrieval


60

Technical indicators and TTR High frequency example


80

Guy Yollin (Copyright

2011)

R for Finance

quantmod

2 / 64

Outline
mm
1

40

60

80

100

120

Introduction to R for Finance Introduction to data retrieval and charting


40

Time series in R More data retrieval


60

Technical indicators and TTR High frequency example


80

Guy Yollin (Copyright

2011)

R for Finance

quantmod

3 / 64

The R programming language


R ismm a language and environment for statistical computing and 40 60 80 100 graphics
120

R is based on the S language originally developed by John Chambers and 40 colleagues at AT&T Bell Labs in the late 1970s and 1980s R (sometimes called GNU S ) is free open source software licensed under the GNU general public license (GPL 2)
60

R development was initiated by Robert Gentleman and Ross Ihaka at the University of Auckland, New Zealand in the early 1990s R is 80 formally known as The R Project for Statistical Computing
www.r-project.org
Guy Yollin (Copyright

2011)

R for Finance

quantmod

4 / 64

R timeline
mm 40
1991 Statistical Models in S (white book) S3 methods 1984 S: An Interactive Envirnoment for Data Analysis and Graphics 1988 (Brown Book) The New S Language Written in C (Blue Book) Work on S Version 1

60
1999 John Chambers 1998 ACM Software Award

80
2001 R 1.4.0 (S4)

100

120

40

1993 R on Statlib 1997 R on CRAN GNU Project

2000 R 1.0.0 (S3)

2002 Modern Applied Statistics with S 4th Edition (S+ 6.x, R 1.5.0)

2004 R 2.0.0

2010 R&R Given ASA Statistical Computing and Graphics Award

1976

60
S-PLULS developed by Statistical Sciences, Inc. 1988 StatSci Licenses S 1993 Modern Applied Statistics with S-PLUS 1994 Modern Applied Statistics with S-PLUS 2nd Edition 1997 Modern Applied Statistics with S-PLUS Programming with Data 3rd Edition (Green Book) (S+ 2000, 5.x) (S+ 5.x) (R complements) 1998 1999

2011

Exponential growth of R Users and R packages

80

S era

S-PLUS era

R era

Guy Yollin (Copyright

2011)

R for Finance

quantmod

5 / 64

Finance Task View


There are many R packages for computational nance; a description of mm 40 60 80 120 these packages can be found on the Finance Task View of100 CRAN:

40

60

80

http://cran.r-project.org/web/views/Finance.html
Guy Yollin (Copyright

2011)

R for Finance

quantmod

6 / 64

R-SIG-FINANCE
mm 40 60 80 100 120

https://stat.ethz.ch/mailman/ listinfo/r-sig-finance Nerve center of the R nance community Daily must read Exclusively for Finance-specic 60 questions, not general R questions
80 40

Guy Yollin (Copyright

2011)

R for Finance

quantmod

7 / 64

Packages for trading system development in R


mm
PerformanceAnalytics: Econometric tools for performance and risk analysis

40

Performance metrics and graphs

60

80

100

120

quantstrat: quantitative strategy model framework blotter: tools for transaction-oriented trading systems development

40
Quantitative trading rules and trading accouting

quantmod: quantitative financial modelling framework TTR: technical trading rules

60

Data access, charting, indicators

xts: extensible time series

80

zoo: ordered observations

Time series objects

Guy Yollin (Copyright

2011)

R for Finance

quantmod

8 / 64

Lecture references
quantmod package mm 40
60 80 100 Jerey Ryans quantmod website: http://www.quantmod.com/ quantmod project page on R-forge: http://r-forge.r-project.org/projects/quantmod 40 Joshua Ulrichs Foss Trading blog: http://blog.fosstrading.com/ TTR project page on R-forge: 60 http://r-forge.r-project.org/projects/ttr/ 120

TTR package

xts package
xts project page on R-forge: http://r-forge.r-project.org/projects/xts/ 80

Guy Yollin (Copyright

2011)

R for Finance

quantmod

9 / 64

R-forge
R-forge is a hosting platform for R package development which mm 40 60 80 100 120 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 40 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
60

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

Outline
mm
1

40

60

80

100

120

Introduction to R for Finance Introduction to data retrieval and charting


40

Time series in R More data retrieval


60

Technical indicators and TTR High frequency example


80

Guy Yollin (Copyright

2011)

R for Finance

quantmod

11 / 64

The quantmod package


The quantmod package for R is designed to assist the quantitative trader mm 40 60 80 100 120 in the development, testing, and deployment of statistically based trading models. Key functions: getSymbols load or download price data 40 Yahoo Finance / Google Finance FRED Oanda csv, RData 60 MySQL, SQLite chartSeries charting tool to create standard nancial charts

Author: 80 Jerey Ryan


Guy Yollin (Copyright

2011)

R for Finance

quantmod

12 / 64

The getSymbols function


The getSymbols function loads (downloads) historic price data
mm 40 60 80 100 120
R Code: The getSymbols function
> library(quantmod) > args(getSymbols) function (Symbols = NULL, env = .GlobalEnv, reload.Symbols = FALSE, 40 verbose = FALSE, warnings = TRUE, src = "yahoo", symbol.lookup = TRUE, auto.assign = TRUE, ...) NULL

Main arguments: 60 Symbols src symbols to be loaded source of the data

Return value: 80 a time series object


Guy Yollin (Copyright

2011)

R for Finance

quantmod

13 / 64

The getSymbols function


R Code: Download prices from Yahoo
> getSymbols("^GSPC")

mm

40

60

80

100

120

[1] "GSPC" > ls() [1] "GSPC" > showSymbols() 40 GSPC "yahoo" > first(GSPC) GSPC.Open GSPC.High GSPC.Low GSPC.Close GSPC.Volume GSPC.Adjusted 60 2007-01-03 > last(GSPC) 2011-09-06 GSPC.Open GSPC.High GSPC.Low GSPC.Close GSPC.Volume GSPC.Adjusted 1173.97 1173.97 1140.13 1165.24 5103980000 1165.24 1418.03 1429.42 1407.86 1416.6 3429160000 1416.6

> class(GSPC) [1] "xts" "zoo"


Guy Yollin (Copyright

80

2011)

R for Finance

quantmod

14 / 64

The chartSeries function


The chartSeries function creates nancial charts
40 R Code: mm chartSeries function 60 The
> 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 = ";", 40 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

80

100

120

60 Main arguments: x an OHLC object type style of chart to draw theme a chart.theme object 80 subset xts style date subsetting argument TA a vector of technical indicators and params
Guy Yollin (Copyright

2011)

R for Finance

quantmod

15 / 64

The chartSeries function


R Code: The chartSeries function

mm > chartSeries(GSPC,subset="2011",theme="white") 40 60
GSPC
Last 1165.24

80

100

120

[20110103/20110906]
1350

40

1300

1250

1200

60
6000 5000 4000 3000 2000 1000 Volume (millions): 5,103,980,000

1150

1100

80

Jan 03 2011

Feb 01 2011

Mar 01 2011

Apr 01 2011

May 02 2011

Jun 01 2011

Jul 01 2011

Aug 01 2011

Sep 01 2011

Guy Yollin (Copyright

2011)

R for Finance

quantmod

16 / 64

Customize a chartSeries plot


R Code: Customize a chartSeries plot

mm > whiteTheme <- chartTheme("white") 40 > names(whiteTheme)


[1] [6] [11] [16] [21] > > > > > > "fg.col" "major.tick" "dn.dn.col" "up.up.border" 40 "area" "bg.col" "up.col" "up.dn.col" "dn.dn.border" "fill"

60
"grid.col" "dn.col" "up.border" "up.dn.border" "Expiry"

80
"border" "dn.up.col" "dn.border" "main.col" "theme.name"

100

120

"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" 60 x <- chartSeries(GSPC,subset="2011",theme=whiteTheme,TA=NULL) class(x)

[1] "chob" attr(,"package") [1] "quantmod"

80

totally white background no volume sub-graph (TA=NULL)


Guy Yollin (Copyright

2011)

R for Finance

quantmod

17 / 64

A chartSeries plot
GSPC [20110103/20110906]

mm

40

60

80

100

120
1350

1300

40
1250

1200

60
1150

80
Jan 03 2011
Guy Yollin (Copyright

1100 Mar 01 2011


2011)

Apr 01 2011

Jun 01 2011
R for Finance

Jul 01 2011

Sep 01 2011
quantmod 18 / 64

Outline
mm
1

40

60

80

100

120

Introduction to R for Finance Introduction to data retrieval and charting


40

Time series in R More data retrieval


60

Technical indicators and TTR High frequency example


80

Guy Yollin (Copyright

2011)

R for Finance

quantmod

19 / 64

Time series data


mm 40 60 80 100 120

Almost all data related to trading is a time series: market data


40

technical analysis indicators trades


60 position data

P&L
80

Guy Yollin (Copyright

2011)

R for Finance

quantmod

20 / 64

Time series data


Time series
mm 40 60 80 100 120

A time series is a sequence of observations in chronological order

Time series object


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

class 60 ts mts timeSeries zoo 80 xts


Guy Yollin (Copyright

package base base rmetrics zoo xts


2011)

overview regularly spaced time series multiple regularly spaced time series default for Rmetrics packages reg/irreg and arbitrary time stamp classes an extension of the zoo class
R for Finance quantmod 21 / 64

Time series methods


Time series classes in R will typically implement the following methods:
mm 40 60 80 100 120

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
60 coredata return data of time series 40

diff dierence of the time series lag lag of the time series aggregate aggregate to lower resolution time series 80 cbind merge 2 or more time series together
Guy Yollin (Copyright

2011)

R for Finance

quantmod

22 / 64

The zoo package


The zoomm package provides an infrastructure for regularly-spaced and 40 60 80 100 irregularly-space time series Key functions: zoo merge
40 120

create a zoo time series object merges time series (automatically handles of time alignment)

aggregate create coarser resolution time series with summary statistics rollapply calculate rolling window statistics readzoo 60read a text le into a zoo time series object Authors: Achim Zeileis
80 Gabor Grothendieck

Guy Yollin (Copyright

2011)

R for Finance

quantmod

23 / 64

The xts package


40 80 100 120 The xtsmm package extends the zoo60 time series class with ne-grained time indexes, interoperability with other R time series classes, and user dened attributes

Key functions: xts


40

create an xts time series object convert time series data to an OHLC series

align.time align time series to a coarser resolution to.period [.xts Authors: Jerey Ryan Josh80 Ulrich
60 subset time series

Guy Yollin (Copyright

2011)

R for Finance

quantmod

24 / 64

Components of an xts object


mm 40 60 An xts object is composed of 3 components: 80 100 120

Index
40

a Data class or Time-Date class used for the time-stamp of observations the time series observations (univariate or multivariate) can be numeric, character, logical, etc. but must be homogeneous
60

Matrix

Attr

80

hidden attributes and user attributes class of the index format of the index time zone

Guy Yollin (Copyright

2011)

R for Finance

quantmod

25 / 64

Date class
Date Dates are represented as the number of days since 1970-01-01
mm 40 60 80 100 120

R Code: Date class examples


> myStr <- "2011-07-04" > class(myStr) [1] "character" 40 > myDate <- as.Date(myStr) > class(myDate) [1] "Date" > as.numeric(myDate) 60 [1] 15159 > format(myDate,"%m/%d/%y") [1] "07/04/11"

80 > as.Date("110704",format="%y%m%d")
[1] "2011-07-04"
Guy Yollin (Copyright

2011)

R for Finance

quantmod

26 / 64

Date-time classes
POSIXct
mm

represents time and date as the number of seconds since 40 60 80 100 120 1970-01-01 represents time and date as 9 calendar and time components

POSIXlt

40 R Code: POSIXct and POSIXlt examples


> d <- Sys.time() > class(d) [1] "POSIXct" "POSIXt"

60 > unclass(d)
[1] 1315440935 > sapply(unclass(as.POSIXlt(d)), function(x) x) sec 34.94161 isdst 0.00000 min

80 15.00000

hour 0.00000

mday 8.00000

mon year 8.00000 111.00000

wday yday 4.00000 250.00000

Guy Yollin (Copyright

2011)

R for Finance

quantmod

27 / 64

xts subsetting
mm 40 60 80 100 120

xts time series objects can be easily subset: Date and time organized from most signicant to least signicant
CCYY-MM-DD HH:MM:SS[.s] 40

Separators can be omitted


CCYYMMDDHHMMSS 60 Intervals can be designated with the / or :: 2010/2011 2011-04::2011-07 80

Guy Yollin (Copyright

2011)

R for Finance

quantmod

28 / 64

xts subsetting
R Code: Subset xts object

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


S&P 500
Last 1165.24

100

120

[20110103/20110906]
1350 1300 1250 1200

40

60
6000 5000 4000 3000 2000 1000 Volume (millions): 5,103,980,000

1150 1100

80

Jan 03 2011

Mar 01 2011

Apr 01 2011

Jun 01 2011

Jul 01 2011

Sep 01 2011

Guy Yollin (Copyright

2011)

R for Finance

quantmod

29 / 64

xts subsetting
R Code: Subset xts object

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


S&P 500
Last 1165.24

120

[20100104/20110906]
1350 1300 1250 1200 1150

40

60
10000 8000 6000 4000 2000 Volume (millions): 5,103,980,000

1100 1050 1000

80

Jan 04 2010

Apr 01 2010

Jul 01 2010

Oct 01 2010

Jan 03 2011

Apr 01 2011

Jul 01 2011

Guy Yollin (Copyright

2011)

R for Finance

quantmod

30 / 64

xts subsetting
R Code: Subset xts object

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


S&P 500
Last 1292.28

100

120

[20110701/20110729]

40

1340

1320

60
5000 4500 4000 Volume (millions): 5,061,190,000

1300

1280

80

3500 Jul 01 2011 Jul 07 2011 Jul 12 2011 Jul 15 2011 Jul 20 2011 Jul 25 2011 Jul 28 2011

Guy Yollin (Copyright

2011)

R for Finance

quantmod

31 / 64

xts subsetting
R Code: Subset xts object

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


S&P 500
Last 1292.28 1360

120

[20110401/20110729]

40

1340 1320 1300

60
5000 4500 4000 3500 3000 2500 Volume (millions): 5,061,190,000

1280 1260

80
Apr 01 2011 Apr 18 2011 May 09 2011 May 31 2011 Jun 20 2011 Jul 05 2011 Jul 25 2011

Guy Yollin (Copyright

2011)

R for Finance

quantmod

32 / 64

Outline
mm
1

40

60

80

100

120

Introduction to R for Finance Introduction to data retrieval and charting


40

Time series in R More data retrieval


60

Technical indicators and TTR High frequency example


80

Guy Yollin (Copyright

2011)

R for Finance

quantmod

33 / 64

The getSymbols.yahoo function


The getSymbols.yahoo downloads symbols from nance.yahoo.com 120 mm 40 60 80 100
R Code: The getSymbols.yahoo function
> args(getSymbols.yahoo) function (Symbols, env, return.class = "xts", index.class = "Date", 40 from = "2007-01-01", to = Sys.Date(), ...) NULL

Arguments: return.class time series class of returned object 60 index.class class of date/time index from starting date of time series to ending date of time series
80 adjust

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

Guy Yollin (Copyright

2011)

R for Finance

quantmod

34 / 64

Download historic quotes: specifying the start date


R Code: mm historic data from a specied start date Get 40 60 80
> getSymbols("SPY",from="2000-01-01") [1] "SPY" > head(SPY)

100

120

40 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-1060 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"

80

Guy Yollin (Copyright

2011)

R for Finance

quantmod

35 / 64

Download historic quotes: specifying the time stamp class


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

mm 40 60 80 > getSymbols("SBUX",index.class="POSIXct",from="2000-01-01")
[1] "SBUX" > head(SBUX)

100

120

SBUX.Open SBUX.High SBUX.Low SBUX.Close SBUX.Volume SBUX.Adjusted 2000-01-0340 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

60

80

2011)

R for Finance

quantmod

36 / 64

Unadjusted SBUX data


SBUX [20000103/20110907]

mm Last 39.18

40

60

80

100

120
60 50 40 30 20

40

60
150 100 50 0 Jan 03 2000 Jul 02 Jul 01 2001 2002 Volume (millions): 8,398,900

10

80

Guy Yollin (Copyright

Jul 01 2003

Jul 01 2004

Jul 01 2005

Jul 03 Jul 02 2006 2007

Jul 01 2008

Jul 01 2009

Jul 01 2010

Jul 01 2011
37 / 64

2011)

R for Finance

quantmod

Get stock splits and dividend history


R Code: Get stock splits and dividend history
> (spl <- getSplits("SBUX"))

mm

40

60

80

100

120

SBUX.spl 1993-09-30 0.5 1995-12-04 0.5 1999-03-22 0.5 2001-04-30 0.5 2005-10-2440 0.5 > class(spl) [1] "xts" "zoo" > (div <- getDividends("SBUX"))

60 [,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-0880 0.13
> class(div) [1] "xts" "zoo"
Guy Yollin (Copyright

2011)

R for Finance

quantmod

38 / 64

The adjustOHLC function


The adjustOHLC adjusts all columns of an OHLC object for split and 40 60 80 100 120 dividendmm
R Code: The adjustOHLC function
> args(adjustOHLC) function (x, adjust = c("split", "dividend"), use.Adjusted = FALSE, 40 ratio = NULL, symbol.name = deparse(substitute(x))) NULL

Arguments:
60 x

an OHLC object

use.Adjusted calculated from dividends and splits (F), or used Adjusted price column (T) Note from package author:
80
Using use.Adjusted = TRUE will be less precise than the method that employs actual split and dividend information.
Guy Yollin (Copyright

2011)

R for Finance

quantmod

39 / 64

Adjust for split and dividend


R Code: mm for split40 dividend60 Adjust and
> 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-0540 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)

80

100

120

60

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

Compare adjustment methods


R Code: Adjust for split and dividend and compare results

mm > head(adj1)

40

60

80

100

120

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

60 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-10806.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

Adjusted SBUX plot


SBUX [20000103/20110907]

mm Last 39.18

40

60

80

100

120 40
35 30

40

25 20 15

60
150 100 50 0 Jan 03 2000 Jul 02 Jul 01 2001 2002 Volume (millions): 8,398,900

10 5

80

Guy Yollin (Copyright

Jul 01 2003

Jul 01 2004

Jul 01 2005

Jul 03 Jul 02 2006 2007

Jul 01 2008

Jul 01 2009

Jul 01 2010

Jul 01 2011
42 / 64

2011)

R for Finance

quantmod

Download historic quotes: specifying adjusted OHLC


R Code: Get historic data and return adjusted OHLC

mm 40 60 80 100 > 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-03405.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-06805.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

120

60

2011)

R for Finance

quantmod

43 / 64

Federal reserve economic data


The function getSymbols can also be used to access data from the Federal Reserve Economic Data (FRED) database mm 40 60 80 100
120

40

60

80

Guy Yollin (Copyright

2011)

R for Finance

quantmod

44 / 64

Download interest rate data from FRED


mm 40 R Code: Download interest rate data 60 from FRED 80
> getSymbols('DTB3',src='FRED') [1] "DTB3" > first(DTB3,'1 week')

100

120

40

DTB3 1954-01-04 1.33 > last(DTB3,'1 week') DTB3 2011-08-2960 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") 80

Guy Yollin (Copyright

2011)

R for Finance

quantmod

45 / 64

Three-month U.S. Treasury bill rate


DTB3 [19540104/20110902]

mm

Last 0.02

40

60

80

100

120
15

40
10

60

80
Jan 04 1954 Jan 04 1960 Jan 03 1966
2011)

0 Jan 03 1972 Jan 03 1978 Jan 03 1984 Jan 02 1990 Jan 02 1996 Jan 02 2002 Jan 02 2008
quantmod 46 / 64

Guy Yollin (Copyright

R for Finance

Outline
mm
1

40

60

80

100

120

Introduction to R for Finance Introduction to data retrieval and charting


40

Time series in R More data retrieval


60

Technical indicators and TTR High frequency example


80

Guy Yollin (Copyright

2011)

R for Finance

quantmod

47 / 64

The TTR package


mm 40 60 80 100 120

The TTR package is a comprehensive collection of technical analysis indicators for R Key features: moving averages oscillators price channels trend indicators 60 Author: Joshua Ulrich
80 40

Guy Yollin (Copyright

2011)

R for Finance

quantmod

48 / 64

Selected technical analysis indicators in TTR


Function stoch aroon BBands chaikinAD ROC CLV CMO EMA VWMA DonchianChannel EMV

mm

Description

40

60

Function ADX ATR CCI

80

Description

100

120

stochastic oscillator Aroon indicator Bollinger bands Chaikin Acc/Dist rate of change Close Location Value Chande Momentum Oscillator exponential moving average volume weighted MA Donchian Channel Ease of Movement Value MA converge/diverge Relative Strength Index Trend Detection Index Vertical Horizontal Filter

Directional Movement Index Average True Range Commodity Channel Index Chaikin Volatility momentum indicator Chaikin Money Flow simple moving average double exp mov avg volume weighed avg price Detrended Price Oscillator volatility estimators Money Flow Index Parabolic Stop-and-Reverse Triple Smoothed Exponential Osc Williams Acc/Dist Zig Zag trend line

chaikinVolatility momentum CMF SMA DEMA VWAP DPO volatility MFI SAR TRIX williamsAD ZigZag

40

60

MACD RSI TDI VHF WPR

80

Williams % R

Technical Analysis from A to Z by Steven Achelis


Guy Yollin (Copyright

2011)

R for Finance

quantmod

49 / 64

Calculate and plot Bollinger bands


mm 40 60 80 100 120

R Code: Plot and calculate Bollinger bands


> b <- BBands(HLC=HLC(SBUX["2011"]), n=20, sd=2) > tail(b,10) dn 2011-08-2440 33.83678 2011-08-25 33.90271 2011-08-26 34.03176 2011-08-29 34.20780 2011-08-30 34.24769 2011-08-31 34.24530 2011-09-0160 34.21113 2011-09-02 34.25267 2011-09-06 34.54411 2011-09-07 34.74668 mavg 37.24133 37.08908 36.93900 36.84324 36.81947 36.82068 36.86701 36.92300 37.04633 37.22483 up 40.64587 40.27544 39.84625 39.47869 39.39126 39.39607 39.52290 39.59333 39.54855 39.70299 pctB 0.4748383 0.4582998 0.4984514 0.7004892 0.7949691 0.8732743 0.7967595 0.6317563 0.5580152 0.8252080

> chartSeries(SBUX,TA='addBBands();addBBands(draw="p");addVo()', subset='2011',theme="white")

80

Guy Yollin (Copyright

2011)

R for Finance

quantmod

50 / 64

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

[20110103/20110907]

mm

40

60

80

100

40 120 38

36

40

34

32

1.5 1.0 0.5 0.0 35 30 25 20 15 10 5

30 Bollinger %b (20,2): 0.825

60
Volume (millions): 8,398,900

80
Jan 03 2011 Feb 01 2011

Guy Yollin (Copyright

Mar 01 2011

Apr 01 2011

May 02 2011

Jun 01 2011

Jul 01 2011

Aug 01 2011

Sep 01 2011

2011)

R for Finance

quantmod

51 / 64

MACD and DPO


40 R Code: mm MACD and DPO 60 80 100 120

> macd <- MACD( Cl(SBUX), 12, 26, 9, maType="EMA" ) > last(macd,'1 week') macd signal 2011-09-06 0.01005927 -0.4979056 2011-09-0740 0.34641082 -0.3290423 > priceDPO <- DPO(Cl(SBUX)) > tail(na.omit(priceDPO)) SBUX.Close 2011-08-22 -1.900 60 -0.052 2011-08-23 2011-08-24 0.244 2011-08-25 -0.945 2011-08-26 -0.261 2011-08-29 0.154

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

Guy Yollin (Copyright

2011)

R for Finance

quantmod

52 / 64

MACD and DPO


SBUX
Last 39.18

[20110103/20110907]

mm

40

60

80

100

120 40
38

36

40

34

32

3 2 1 0 1 2 3 4 2 0 2 4

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

60

Detrended Price Oscillator (10): 0.130

80
Jan 03 2011 Feb 01 2011

Guy Yollin (Copyright

Mar 01 2011

Apr 01 2011

May 02 2011

Jun 01 2011

Jul 01 2011

Aug 01 2011

Sep 01 2011

2011)

R for Finance

quantmod

53 / 64

Experimental chart_Series chart


mm 40 60 80 100 120

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 are experimental version 2 functions: chart Series add TA chart Theme
60
> > > > > 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))

40

80

Guy Yollin (Copyright

2011)

R for Finance

quantmod

54 / 64

Experimental chart_Series chart


SBUX
42

20110103 / 20110907

mm

40

60

80

100

120
42 41 40

41

40

39

39

38

40

38

37

37

36

36

35

35

60
34 34 33 33

32

32

31

80
Jan Feb Feb 01 2011 Mar 01 2011 Mar Apr 01 2011 Apr May 02 2011 May Jun 01 2011 Jun Jul 01 2011 Jul Aug 01 2011 Aug Sep Sep 01 2011

31

Jan 03 2011

Guy Yollin (Copyright

2011)

R for Finance

quantmod

55 / 64

Outline
mm
1

40

60

80

100

120

Introduction to R for Finance Introduction to data retrieval and charting


40

Time series in R More data retrieval


60

Technical indicators and TTR High frequency example


80

Guy Yollin (Copyright

2011)

R for Finance

quantmod

56 / 64

High-frequency versus low-frequency time series analysis


High-frequency begins when indexing by date alone is not enough mm
40 60 80 100 beyond the capabilities of zoo objects with Date indexes
intra-day bars tick data

120

High-frequency time series require formal time-based classes for 40 indexing Recommended classes for high-frequency time series:
xts (extensible time series) class 60 POSIXct/POSIXlt date-time class for indexing
Class time series class Low frequency zoo Date High Frequency xts POSIXlt

80

time index class

Guy Yollin (Copyright

2011)

R for Finance

quantmod

57 / 64

The strptime function


The strptime function converts character strings to POSIXlt date-time 40 60 80 100 120 objects mm
R Code: The strptime function
> args(strptime)

40 function (x, format, tz = "") NULL

Arguments:
60

vector of character strings to be converted to POSIXlt objects

format date-time format specication tz timezone to use for conversion Return value: 80 POSIXlt object(s)
Guy Yollin (Copyright

2011)

R for Finance

quantmod

58 / 64

The xts function


The function xts is the constructor function for extensible time-series mm 40 60 80 100 120 objects
R Code: The xts function
> library(xts) 40 > args(xts) function (x = NULL, order.by = index(x), frequency = NULL, unique = TRUE, tzone = Sys.getenv("TZ"), ...) NULL

Arguments: 60 x Return value:


80

data matrix (or vector) with time series data

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

Guy Yollin (Copyright

2011)

R for Finance

quantmod

59 / 64

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

mm

40

60

80

100

120

> tm <- strptime(paste(dat[,"Date"], 60 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

80

2011)

R for Finance

quantmod

60 / 64

Create and plot xts object


mm 40 60 80 100 120

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

40
2007-01-01 17:30:00 2007-01-01 18:00:00 2007-01-01 18:30:00 2007-01-01 19:00:00 2007-01-01 19:30:00 60 2007-01-01 20:00:00 2007-01-01 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 = 6, col = "red");addSMA(n = 45, col = "blue")', subset='2007-12-24/2007-12-26',theme="white",name="GBPUSD")

80

Guy Yollin (Copyright

2011)

R for Finance

quantmod

61 / 64

GBPUSD crossover example


GBPUSD [20071224/20071226 23:30:00]

mm

Last 1.98542

40

60

80

100

120

1.988

1.986

40

1.984

1.982

60

1.980

1.978

1.976

80
Dec 24 00:00 Dec 24 04:00 Dec 24 08:00
2011)

Dec 24 12:00

Dec 26 02:00

Dec 26 06:00

Dec 26 10:00

Dec 26 14:30

Dec 26 20:00
quantmod 62 / 64

Guy Yollin (Copyright

R for Finance

GBPUSD crossover example with annotation


GBPUSD
20071224 / 20071226 23:30:00

1.988

mm

40

60

80

100

120
1.988 1.987

1.987

1.986

1.986

1.985

1.985

1.984

40

1.984

1.983

1.983

1.982

1.982

1.981

1.981

1.980

60
Crossover bar

1.980

1.979

1.979

1.978

1.978

1.977

1.977

1.976

80
Dec 24 04:00

1.976

Dec 24 00:00

Guy Yollin (Copyright

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

2011)

R for Finance

quantmod

63 / 64

GBPUSD crossover example with annotation


mm 40 60 80 100 120

R Code: GBPUSD crossover example with annotation


> > > > > > fastMA <- SMA(Cl(GBP),n=6) slowMA <- SMA(Cl(GBP),n=45) 40 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) 60 > text(x=x,y=ss[x,"Low"]-0.0005,"Crossover\nbar",pos=1)

80

Guy Yollin (Copyright

2011)

R for Finance

quantmod

64 / 64

Das könnte Ihnen auch gefallen