R version 2.9.2 (2009-08-24)
Copyright (C) 2009 The R Foundation for Statistical Computing
ISBN 3-900051-07-0
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
Natural language support but running in an English locale
R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.
Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
>
>
> # Read in Dow Jones historical data
> # saved from http://finance.yahoo.com/q/hp?a=&b=&c=&d=8&e=22&f=2009&g=d&s=^DJI
>
> dji = read.table("http://www-stat.stanford.edu/~jtaylo/courses/stats202/data/dowjones.csv", sep=',', header=T)
>
> # the data has several columns -- we can see them with this
>
> names(dji)
[1] "Date" "Open" "High" "Low" "Close" "Volume"
[7] "Adj.Close"
>
> # the column Date represents the day, but
> # R has to be told its a time
>
> print(class(dji$Date))
[1] "factor"
>
> # This little bit of code tells R to interpret it like a date
>
> djiDate = strptime(dji$Date, format="%Y-%m-%d")
>
> # its class is different: POSIX is a standard used to represent
> # time in a computer
>
> print(class(djiDate))
[1] "POSIXt" "POSIXlt"
>
> # plot the closing price as a red line, starting from
> # 01/01/2006, which happens to be the 946th entry
>
> day1 = strptime("2006-01-01", format="%Y-%m-%d")
> djisubset = (djiDate > day1)
>
> plot(djiDate[djisubset], dji$Close[djisubset], type='l', col='red')
>
> # Let's add in the S&P500 as a blue line
>
> sp = read.table("http://www-stat.stanford.edu/~jtaylo/courses/stats202/data/spx500.csv", sep=',', header=T)
>
> spDate = strptime(sp$Date, format='%Y-%m-%d')
> spsubset = (spDate > day1)
>
>
>
> # we have to replot because the scales are different
>
> plot(djiDate[djisubset], dji$Close[djisubset], type='l', col='red', ylim=c(0,14500))
> lines(spDate[spsubset], sp$Close[spsubset], col='blue')
>
>
>
>
> # better
> par(mfrow=c(2,1))
>
> plot(djiDate[djisubset], dji$Close[djisubset], type='l', col='red', ylab='Dow Jones close')
> plot(spDate[spsubset], sp$Close[spsubset], col='blue', type='l', ylab='S&P 500 close')
>
>
>
>
> proc.time()
user system elapsed
2.940 1.908 5.866
R script


